title: RFID access system with PN532 reader

text:
# Question
Title: RFID access system with PN532 reader
I have a PN532, so it's capable of both reading and writing. I've used it for a few perfectly functional things, but I want it to authenticate based on the contents (for example 1024 bytes) of a tag.

I'd generate some pseudorandom data, possibly on my PC, and write that into each card, and use a checksum of that as the key.

Should I just stick with the standard authentication of tokens, or is this a worthwhile alternative method? The UIDs of the tokens are not interesting for authentication.

If worthwhile, what checksumming algorithms should I use? If not, would someone care to explain how I can program the memory of tokens, and how to use that in addition to UID for auth?

Thanks in advance.

# Answer
> 1 votes
First off, you don't want to use a checksum for authentication.

A checksum can be thought of as a hash with a very small size. The smaller the size of a hash the less unique it is. The less unique it is the more likely it is that incorrect data will generate the same hash and authenticate someone it shouldn't.

For instance, a 32 bit checksum (hash) of 1kB data (8192 bits of information) is a 256-fold reduction in the uniqueness of the value. At 32 bits you get 232 unique values. With 8192 bits you get 28192 possible values. I can't calculate how many values that actually is, but as you can imagine there will be many billions of billions of combinations that would all equate to the same checksum.

If you must use a checksum then make it an actual recognised hash. For instance an MD5 (considered weak by today's standards) has 128 bits. SHA-256 has, as you would imagine, 256 bits.

However calculating these hashes on an Arduino is not a simple matter owing to a lack of memory. Not impossible, but not that easy.

If you're going as far as to use such large amounts of data for authentication and using heavy mathematical routines to create a hash you may as well go the whole hog and use a proper cryptographic key pair.

One method would be to encrypt the UUID of the card off-line and store the encrypted result on the card - that data would then be unique to that card and tied to it - you wouldn't be able to clone the card unless you could clone the UUID as well.

Then either the UUID is read by the Arduino and also encrypted using the same key and if the results match authentication succeeds. Or the encrypted value is decrypted by the Arduino and compared to the UUID to see if they match. Which you choose depends on if you have asymmetric or symmetric encryption (the former is more like a hash but requires the encryption key to replicate it whereas a hash doesn't).

You can also include other information with the UUID, such as the name of the card owner (for identification purposes), etc - as long as you are able to already know that data to create the cryptographic has to compare with what is on the card.

---
Tags: programming, rfid
---


title: Problem receiving full serial event+SMS

text:
# Question
Title: Problem receiving full serial event+SMS
I wrote code in Arduino to read SMS. I have a problem with receiving it from serial.

```
String str;

void setup() {
  Serial.begin(9600);
  Serial.println("AT+CMGF=1");
  delay(1000);
}

void loop() {
  Serial.println("AT+CMGF=1");
  delay(2000);
  Serial.println("AT+CMGR=1");
  delay(5000);
  while (Serial.available()>0) {
    str = char(Serial.read());
    Serial.print(str);
  }
  Serial.println();
}

```

I have an A6 GSM modem. When I read the serial I just get:

```
+CMGR: "REC READ

```

Nothing more!

I should get something like this:

```
+CMGL: 1,"REC READ","+989207201219",,"2017/08/26,21:54:56+05"
test 20

```

I changed my code to:

```
int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;
  if (readch > 0) {
    switch (readch) {
      case '\n': // Ignore new-lines
        break;
      case '\r': // Return on CR
        rpos = pos;
        pos = 0;  // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  // No end of line has been found, so return -1.
  return -1;
}

void setup() {
  Serial.begin(9600);
  Serial.println("AT+CMGF=1");
  Serial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");
}

void loop() {
  Serial.println("AT+CMGF=1");
  Serial.println("AT+CMGR=1");
  static char buffer[80];
  if (readline(Serial.read(), buffer, 80) > 0) {
    Serial.print("You entered: >");
    Serial.print(buffer);
    Serial.println("<");
  }
  delay(3000);
}

```

But I get nothing.

# Answer
I changed the code. so It works fine

```
String inputString = "";         // a String to hold incoming data
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("AT+CMGF=1");
  Serial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");
}

void loop() {

  Serial.println("AT+CMGR=1");

}

void serialEvent() {
    inputString = Serial.readString();
    Serial.println(inputString);
    delay(5000);
  }

```
> 0 votes

# Answer
The arduino is a "small memory" device. So it probably does not have a big serial buffer. On say "linux on a PC" you get a 4096 byte buffer, but on an arduino, probably only say 16. Now as luck will have it "+CMGR: "REC READ" is precisely 16 characters....

From the code that I see, you seem to be sending commands to the modem and then reading/echoing them. I would have liked to use two different serial ports or something like that.

In any case, if it sort of works for those first 16 characters, remove all the delays and put one of them near the end of the loop() function. Remove the initial print to the modem in the setup function.
> 1 votes

---
Tags: serial
---


# Question
Title: Analog output low voltage issue, how to troubleshoot
I have connected my arduino according to the schematics in the image, with a few additions.

**The setup**

1. A DC motor (water pump) drawing power from Vin, going to ground via a transistor based in A0 analog output. Between the transistor and A0 is a 270 ohm resistor. In parallel to the motors poles is a diode, for protection.
2. A 3,1" (4x20) LCD screen with an I^2C chip (draws 5V, A4 and A5 and GND)
3. A Potentiometer directly on the I^2C chip LED pins (replacing the jumper) - for control of the light intensity. (Vin and middle pin of pot, gnd unconnected)
4. A Potentiometer connected to A1, 3,3V and GND.

**Code description:** Using the Timer and the LiquidCrystal\_I2C library, Once every other second the LCD is refreshed Once every day the water pump is started with an analogWrite(A0, HIGH) and it runs for 1-60 seconds based on the potentiometer setting.

**The issue.**

It seems the output of A0 does not deliver enough voltage to trigger the pump. This is a new error, before I got the screen, it ran the pump fine.

I suspect one of three things. 1: I have broken something in the arduino power regulator, and the voltage outputs on analog pins are lower than they should be (or their ability to supply current) -\> Must get new arduino. 2: I have somehow saturated the ground pin or there is a connection issue. 3: The LCD display is drawing too much current. (Leading to either 2 or 1, but won't be fixed by getting a new arduino)

**What have I already tried**

I have tried, with the arduino connected via mains to short it between 3,3V and the transistor base, and then it runs. So the transistor is OK, the pump is OK. I have tried to map the output to another analog pin to display the value of this pin while the program is running, and it does display a value while the pump is supposed to be running, so it is doing something. I have used a multimeter to measure the pins, but I really don't know what "normal" is so I decided to stop fiddling around with that. I have also tried using other analog outputs (excepting 4 and 5, they are claimed by the lcd I^2C logics)

Can anyone of you please give me some pointers in the right direction, to help me to determine the error in question? What should I try?

Disclaimer, due to having the normal issues of life, love and the fact that a day only has 1440 minutes, I usually only have time to work on my pet projects during weekends...

If this question is not relevant or poorly written, please let me know, I'll try to clarify (or delete it).

# Answer
The analog pins are for analog **input** not output. You can only use them for *digital* output.

Change

```
analogWrite(A0, HIGH)

```

to:

```
digitalWrite(A0, HIGH)

```

`analogWrite()` can only be used on PWM capable pins (the ones marked with `~`). On any other pin it sets the pin HIGH if the analog value \> 127 and LOW if the analog value \<= 127.

Since you are writing HIGH, which is equal to 1, the output is LOW because 1 \< 127.
> 2 votes

# Answer
why analogWrite? analogWrite parameter values are 0 to 255 (or 1023) so analogWrite(pin, 1) is close to 0.

analogWrite is PWM on digital ports and doesn't work on analog ports analogWrite reference

use digitalWrite
> 2 votes

---
Tags: arduino-uno, lcd, voltage-level, hardware, electronics
---


title: Charging Li ion cell using arduino

text:
# Question
Title: Charging Li ion cell using arduino
2days back I opened my cousin brothers laptop battery as it was a spare one left unused over a year. I disintegrated it and found 6x 18650 batteries when I checked them with voltmeter individually I found that 2 were dead I.e.0V and 2 read 2.15 V and the last two read 1.5V. I thought of making a power bank using them individually. The battery are ideal for a power bank because they have 2200ah capacity. I need a circuit to charge it. I thought of chraging it with arduino. But how? To get the datasheet just search "lr1865ah" in google and click the one and only pdf link that is the cell's datasheet. I need the charing circuit using arduino.

# Answer
There is a far easier (and safer) way to charge them without using an Arduino. Over-voltage is an issue and another crucial factor with the 18650 batteries is to not let the voltage drop below 2.5 volts when you are dis-charging them. There is a simple "Charge/Discharge Board Module for 18650 Lithium Batteries" that sell for approx. $1 US:

http://www.ebay.ca/itm/2in1-1A-USB-Charge-Discharge-Board-Module-for-18650-Lithium-Battery-Phone-Bank-/302039028674?hash=item4652edd3c2:g:bDkAAOSw9NdXrBoE.

The board has a "fast charge" current of 1000 mA until the battery reaches 4.2 volts, then it switches to a "trickle charge mode". The circuit board also stops current flowing out of the battery once the voltage drops to 2.5 volts. Most of the older charger boards do not have this feature and it's almost as important. It also has a "over-current" protection current of 3.0 amps in case you try to draw too much power from it.

The circuit board has a mirco USB connection on it but be VERY careful before you plug it into a computer USB port. My old MacBook only provides up to 500 mA at each USB port, half of what's required.

The circuit board is 0.700" X 1.050". Here is a picture of it:
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: arduino sketch on Win7 vs. MAC op system?
I have a friend who is just getting started with Arduino UNO. He downloaded a sketch and is using a UNO on Mac OS. He loaded the sketch and verified. it comes up with errors. He sent me the same sketch and i opened it under Win7 arduino software. verified, and it says it is fine. i made an arduino file and emailed it back to him. he is still getting the same errors. can anyone help and let me know what is wrong? i am not a MAC expert and wonder why this works in win and not MAC???????? appreicate any help anyone can give me

# Answer
> -1 votes
I've had the same issue with Mac OSX 10.6.8 vs Windows XP SP3 using the same IDE version. I don't have a definitive answer for you, but I know that Microsoft has more frequent updates compared to Apple, which could be the reason. I suspect my issue and your friend's issue is the GCC compiler we're using. The compiler would be updated on OSX only when you update your entire OSX version. To get around that, there are third-party package managers: Homebrew and MacPorts that would allow you to just update the GCC compiler for example.

---
Tags: arduino-uno
---


# Question
Title: Arduino Wire communication with MCP23008 GPIO pin expander to turn on an LED with a button press
I am using an Arduino Uno and an MCP23008 GPIO pin expander, I have a momentary button connected to GPIO 2 on the MCP23008 and an LED light connected to GPIO 1 on the MCP23008. What I want is for the LED to turn on when the button is pressed down, and off otherwise. The code I currently have is this:

```
   #include "Wire.h"       //import Wire library
   byte inVal;             //declare byte variable

   void setup() {

      Serial.begin(9600);
      Wire.begin();
      Wire.beginTransmission(0x20);   //MCP23008 i2c addr
      Wire.write(0x00);               //MCP23008 internal register addr for I.O.dir
      Wire.write(00000010);           //set all pins as output, except for #2 as input
      Wire.endTransmission();
    }

    void loop() {

      Wire.begin();
      Wire.beginTransmission(0x20);   //MCP23008 i2c addr
      Wire.write(0x09);               //MCP23008 internal register addr for GPIO access
      //Wire.write(0xFF);             //set all output pins to HIGH, commented out for now.
      Wire.endTransmission();
      Wire.requestFrom(0x20,1);       //get one byte of input input from MCP23008
      inVal=Wire.read();              //set pyte as variable

      //Serial.println(inVal,BIN);    //output byte to serial monitor, commented out for now

      Serial.println(bitRead(inVal, 1)); //output second bit from byte(1 or 0, for HIGH or LOW, depending on the press of the momentary button.
      if((bitRead(inVal, 1)==1))      //if the bit from the button is high,
      {
        Wire.beginTransmission(0x20);
        Wire.write(0x09);
        Wire.write(0xFF);             //then set all output pins as HIGH
        Wire.endTransmission();
      }

      else if((bitRead(inVal, 1)==0))  //if the bit from the button is low,
      {
        Wire.beginTransmission(0x20);
        Wire.write(0x09);
        Wire.write(0x00);             //then set all output pins as LOW
        Wire.endTransmission();
      }
    }

```

I don't know as much Arduino as I do Python, and I have even less experience with i2c connections and the Wire library, but this looks to me like it should be working.

The bit printed on the serial monitor is HIGH, until I press the button once, then it stays LOW forever until I modify and re-upload the code to the Arduino. Not sure what's going wrong here. Anything helps, thanks.

# Answer
> 1 votes
I see one major thing wrong at first glance:

```
  Wire.write(00000010);           //set all pins as output, except for #2 as input

```

That doesn't set GPIO 1 (which you call number 2 - counting starts at 0 not 1) to be an input, that sets GPIO 3 (number 4) as an input. Numbers starting with `0` are octal, not binary. For binary the prefix is `0b`:

```
  Wire.write(0b00000010);           //set all pins as output, except for #2 as input

```

And then you read using:

```
bitRead(inVal, 1)

```

which would have read GPIO 1 which is configured as an output.

So you have a switch on GPIO 1 which is an output, which you then drive high (causing a short internally which can damage the pin), and as a result you drive the pin HIGH internally. Now it's always high, so a read of the pin sees the HIGH you are driving from it. Hence it gets stuck at 1.

Fixing your IODIR write should help solve that problem.

---
Tags: arduino-uno, led, pins, wire-library, io-expander
---


# Question
Title: Communication with ESP, HTTP requests or WebSocket?
Here is my problem. I'm working on making a wifi addressable RGB LED (like WS2812b) controller, I'm using an ESP8266 as the hardware. I'm also creating a phone application for controlling the device and setting different modes. What I'm doing right now is that I communicate with the module by sending GET commands from my phone app. For example to change the brightness I send `http://192.168.4.1/I125I` Then on the ESP side the code is as follows:

```
WiFiClient client = server.available();
  if (client) {
  String inData= client.readStringUntil('\r');
  if (inData.indexOf("I")!=-1){
 BRIGHTNESS=str2int(inData.substring(inData.indexOf("I")+1,inData.lastIndexOf("I")));
}}

```

It works, but I'm not sure if this way of sending data is efficient at all. if change colors too rapidly the ESP resets. I recently found another code that uses GET and POST commands but different methods are used, like the following

```
server.on("/brightness", HTTP_POST, []() {
    adjustBrightness();
  });

```

Then inside adjustBrightness function brightness is adjusted. This way it looks more professional but Is it more efficient?

I recently bought a commercial RGB LED controller that uses ESP8266 as its core. I tried to see what the phone app sends to the controller using the Drony app. For my app I could see all the get command the app was sending

```
192.168.4.1/I255I

192.168.4.1/R200RG90GB76B

...

```

but for the commercial controller I just saw one connection, something like "157.10.12.10:5172"

Is this using websockets? Is using websocket a better way? is it more robust?

I'm writing the code in Arduino IDE.

# Answer
> 1 votes
> This way it looks more professional but Is it more efficient?

No, the differences are minuscule. It's only really the location of any parameters that are different - either as part of the URL (`GET`) or as part of the body (`POST`).

> Is this using websockets? Is using websocket a better way? is it more robust?

No, it's just a TCP connection (or maybe UDP connection, it's hard to tell from your description) sending unknown data. It's impossible to tell what the data us from the port number, you would have to actively sniff the data and work out what it is.

Yes, it is generally more efficient doing that kind of thing (though not necessarily more "robust") - HTTP is a very generic system that can transfer many different kinds of data in a request so needs large amounts of superfluous information that is not applicable to controlling an LED, whereas a simple TCP or UDP socket only transfers the minimal amount of data needed to get the job done.

---
Tags: esp8266, communication, http
---


# Question
Title: RF receiver becomes weakened after motor turns on
I recently bought a simple SMAKN 315MHz RF receiver and transmitter, and I got everything working so that the transmitter transmits the value of a joystick, and the receiver receives that and uses it to set the analogWrite() of a motor on a PWM pin.

However, the moment the motor turns on, the receiver just weakens tremendously. At that point it only gets a message when I stick the receiver right against the transmitter. I’m powering the arduino and motor with a 3.7v LiPo battery btw.

Any help? I’ve tried with a 9V alkaline and a 9V adapter and nothing significantly changed.

# Answer
> 1 votes
That behaviour is to be expected. Motors are very noisy and cause massive amounts of interference in radio signals.

The best thing you can do is to try and suppress that interference. For this you will need three 0.1µF (100nF) ceramic capacitors.

One capacitor is connected between the terminals of the motor to reduce noise transferred down the wires (wires make good antennae). The other two connect between each of the terminals and the metal body of the motor.

The metal body of the motor then becomes a shield to trap the noise.

---
Tags: arduino-mega, rf
---


# Question
Title: Storing a counter to EEPROM - how to extend the life?
I am building a circuit that has a button, which when pressed, should increment a counter. I want to store this counter so that when I power off my circuit, it can be read when I power it back on. However, I am worried about the lifetime of the EEPROM - apparently it is only rated to handle 100k writes.

I am using an Adafruit Trinket Pro. Should I cycle my writes through different addresses so as not to write to a single cell over and over? What other strategies are there? I don't expect to be pressing the button many times in a short period of time - maybe at most one press per minute.

Is there some other external storage option I should look at? I really don't want my little project to die randomly one day because I've exceeded ~100k button presses!

# Answer
If possible use a combination of wear-leveling like algorithm (as pointed out by Mikael Patel) and an power-down driven interrupt, to save onto EEPROM only when needed. At reset, load the last keypress count into a variable in RAM. Increment that variable in RAM on keypress, and save it to EEPROM only when a power down occurs (i.e. the interrupt is triggered). Optionally, when power down occurs, make sure to save the variable only if the new counter actually differs from the old value (i.e. if there actually were keypresses).

To implement the power-down driven interrupt use the built-in comparator to monitor a Vin (use a resistor divider!) against the internal Vref, and use the analog comparator interrupt to save the value. Remember to put enough capacitance between +5V and gnd, to make sure your arduino has enough time to save the state.

Alternatively, if you can afford errors (which might accumulate over time, and lead to a huge underestimation), save the value to EEPROM only every n keypresses.
> 2 votes

# Answer
`maybe at most one press per minute.`

That's great! You can just make some sort of timer to save every 2 or 3 minutes automatically. You said `at most`, so that should work. Here is example of code that can allow you to do so!

```
int cycleCnt = 0;    //Counter to count cycles
int cnt = EEPROM.read(0);         //Your press counter
bool currentlyCounting = false;   //Boolean to store if we are counting now or not
bool pressedBefore = false;

void loop() {
  if (digitalRead(button_pin) == HIGH) {    //You are holding the button
    if (!pressedBefore) {                   //And you didn't press it before
      //Here you do something you need with button
      currentlyCounting = true;       //After you pressed the button, we are starting to count time
      cycleCnt = 0;                        //and reset current counter (which would save us EEPROM writes!)
      cnt++;

      pressedBefore = true;                 //Mark button to be pressed so you don't do same code more then one time
    }
  }
  else pressedBefore = false;               //Mark, that you've unpressed the button

  delay(50);      //Delay in 50 mil won't affect speed of your button press, but it will allow us to count time
  if (currentlyCounting) cycleCnt++;          //Count cycles (every 50 mil)

  if (cycleCnt == 20 * 120) { //20 - amount of loop cycles to wait for one second. 120 - seconds in 2 minutes
    cycleCnt = 0;
    EEPROM.write(0, cnt);
    currentlyCounting = false;
  }
}

```

This might help you as well!

In case I misunderstood you and you meant "1 minute is the highest delay time beetween presses" then you should save automatically every half of minute or so
> 2 votes

# Answer
Cycling through the EEPROM is possible.

Is that button capable to last more than 100k presses ?

A button press every minute ? Really ? Is that during working hours ? That would take about year to get near the 100k writes (5 days per week, 8 hours per day, every minute).

If you want to count more than 100k key presses, then you probably store it in a 32-bit integer. That is 4 bytes. That means that when the Arduino is turned off while in the middle of writing that number to the EEPROM, that number is corrupted and lost forever.

With 1k EEPROM, you have 256 positions for the 32-bit integer. That means you can handle 25 million key presses.

My suggestion would be to store each new value of the 32-bit integer to the next location (circular). At startup you need code that interprets the numbers to find the last one and ignores a bad one and can handle a new Arduino with cleared EEPROM and even an Arduino that was used by you to develop the code. That means you need a command to clear the EEPROM.
> 0 votes

# Answer
Use brown out detection. Keep the count in ram until the mcu is losing power - only then save it to eeprom. Read the datasheet on bor.
> 0 votes

---
Tags: arduino-mega, eeprom
---


# Question
Title: Arduino - Getting error - 'TCCR2' was not declared in this scope
This code below:

```
void setup() {
  #if defined(__AVR_ATmega168__)
    // 62.5KHz PWM for the ATMega168 -> only on Arduino pins 9 and 10

    // set prescaler to 1
    // (sbi means "set bit register", cbi means "clear bit register")
    cbi(TCCR1B, CS12);
    cbi(TCCR1B, CS11);
    sbi(TCCR1B, CS10);

    // set fast PWM
    cbi(TCCR1B, WGM13);
    sbi(TCCR1B, WGM12);
    // with fast PWM, the frequency is (CLK/256*prescaler) = 16MHz/256 = 62.5KHz
    // with slow PWM, it is half that speed (31KHz)
  #else
    // 22KHz for the ATMega8 (this is a low frequency)
    TCCR2 = ((TCCR2 & ~0x07) | 0x01); //<ERROR POINTS HERE!
    TCCR1B = ((TCCR1B & ~0x07) | 0x01);
  #endif
}

```

when verify, generates an error:

```
In function 'void setup()':
pwm-control-1:185: error: 'TCCR2' was not declared in this scope
TCCR2 = ((TCCR2 & ~0x07) | 0x01);
^
exit status 1
'TCCR2' was not declared in this scope

```

So far i know this code generates pwm at pin 9 or 10, and designed for ATmega168 or ATmega8. The code came with a .pde extension and I opened it on 'Arduino: 1.8.3' and saved as an .ino file.

Can any one please tell me how to convert this code to work with 'ATmega328P-PU' and for the latest Arduino IDE. And also if there anything else to consider running with this code

I'm not an expert in pwm and timer/controls in micros... just started to learn..

Note: I've only shown the necessary part of the code

# Answer
Looks like this code is pretty old. It's assuming that any Arduino that isn't using an ATmega168 is using an ATmega8. In reality, the ATmega8 hasn't been used on any Arduino boards in the last ten years or so -- it's pretty much obsolete.

The easiest fix will be to remove the non-'168 branch (between `#else` and `#endif`), and make the '168 branch default (remove the `#if` line). This will probably still fail on ATmega32U4 boards, but at least it'll now work on ATmega328 hardware.
> 2 votes

# Answer
The problem is because TCCR2 is not declared, as there is no register with that name. Maybe you wanted to configure the timer 2, i.e. you meant TCCR2A or TCCR2B instead of TCCR2.

EDIT: analyzing your code, you should definitely write TCCR2B.
> 0 votes

# Answer
Check the datasheet to see if there is a tccrb. Maybe for your device, it is tccra, tccrb, or teerc, ....
> 0 votes

---
Tags: pwm
---


# Question
Title: How do I fix this error? It says "warning: invalid conversion from 'long int*' to 'long int' [-fpermissive]
I am working on an assignment that converts a reading of force into pounds and then finds the maximum and average of all the values received

This is my code:

```
void setup()
{

 // put your setup code here, to run once:

 Serial.begin(9600);

  // declare the outputs and inputs
  pinMode( 0 , INPUT);

  //figure out what pin the reading is going to be input to

  fsrReading = analogRead( 0 ) ;
  //the # is the same pin used to get input

  //or use analogRead ( # ), it depends if the pin input is on the analog side of the arduino

  // should this be under the while loop or here?

  //list functions here
  long ForceInPounds(long);
  long FindMax(long);
  long FindAvg(long);

  //declaring variables of functions
  FM = FindMax(new long);
  FA = FindAvg(new long);

        Serial.println("The max value is:");
        Serial.println(FM); //calls FindMax function

        Serial.println("The average value is:");
        Serial.println(FA); //calls FindAvg function

  }

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

 int counter1= 0;

  while (counter1< 100)
  //runs test 100 times

  //should I just make this a function? instead of embedding it in the void loop

 {
      Serial.print("Analog reading = ");

      Serial.println(fsrReading);

      //declaring variable of function used in this segment
      FiP = ForceInPounds(new long);

      Serial.print("Force in Newtons:");
      Serial.println(FiP); //calls ForceinPounds function

      counter1 ++;
  }

}

//FUNCTIONS

long ForceInPounds(const long)
// converts recorded voltage to resistance to conductance to force to pounds
{
 fsrReading = fsrVoltage;

 if (fsrVoltage== 0)
 {
   Serial.print("No pressure");
 }
 else
 {
   fsrResistance = 5000.0 - fsrVoltage;
   //convert voltage to resistance
   fsrResistance *= 10000.0;
   fsrResistance /= fsrVoltage;
   fsrConductance = 1000000.0 ;

   //convert resistance to conductance
   fsrConductance /= fsrResistance;
   if (fsrConductance <=1000.0)
   //convert resistance to conductance
   {
     fsrForce = fsrConductance/80.0;
   }
   else
   {
     fsrForce = fsrConductance - 1000.0;
     fsrForce /= 30.0;
   }
   fsrPounds = fsrForce/4.45;

   //convert force to pounds
 }

 return fsrPounds;
}

long FindMax(long)
{
  int counter2 = 0;

  while (counter2 < 100);
  {
    if ( fsrPounds > maximum)
    {
          maximum = fsrPounds;
          counter2++;
    }
    else
    {
          maximum = maximum;
          counter2++;
    }

  }
  return maximum;

}

long FindAvg (long)
{
  long start = 0;
  //variable to begin avg function
  long avg;
  int counter3 = 0;

  while (counter3 < 100);
  {
    start = start + fsrPounds ;
    counter3 ++;
  }

  avg = start/100;
  return avg;
}

```

What am I doing wrong? This is my first time working with Arduino. Thanks

# Answer
This is most likely not what you want to be doing

```
//declaring variables of functions
FM = FindMax(new long);
FA = FindAvg(new long);

```

And it is entirely incompatible with these definitions

```
//list functions here
long ForceInPounds(long);
long FindMax(long);
long FindAvg(long);

```

With the result that you pass a *pointer* to a `long` (ie, its address in memory), to a function which is instead expecting the *value* of a `long`.

However, it's going to be hard to propose a solution until you edit the body of the functions into your question.

There's probably no reason to use `new` here at all - let the functions allocate their own *temporary* variables on the stack, since they seem to return a value rather than a pointer. Most likely even if this worked, the `new long` you create would be abandoned - ie, a memory leak.
> 1 votes

# Answer
There are several fundamental problems with the code. It appears your understanding of function declaration, definition, and usage are not accurate.

This part:

```
  //list functions here
  long ForceInPounds(long);
  long FindMax(long);
  long FindAvg(long);

```

Is unneccesary.

`setup()` is not the place to declare function variables:

```
  //declaring variables of functions
  FM = FindMax(new long);
  FA = FindAvg(new long);

```

If your functions use variables internally, the place to declare them is within the function definition.

In your FUNCTIONS section, you start off defining this function:

```
long ForceInPounds(const long)

```

The first `long` declares that the function will return a `long`, and the `(const long)` would normally declare what variable types your function accepts as parameters, as well as the name(s) of said parameters. You have only provided a type `long`, and a modifier `const`, but no name. It doesn't make sense to pass in a `const` variable anyway, as the `const` indicates the content of the variable will never change from the initial value. In your code, not only is the variable not named, it is not given an initial value.

Within that `ForceInPounds()` function, you start with:

```
  fsrReading = fsrVoltage;

```

which overwrites your initial `fsrReading = analogRead(0);` with an undefined value, as you have neither declared a type for `fsrVoltage`, nor given it an initial value.

Also, you call `analogRead(0)` once in setup, so it only captures the value once. The `fsrReading` variable is not continually updated with the analog reading. You have to keep calling `analogRead(0)` and storing it in a variable each time through your loop.

There are other problems with the code, but these are a few of the fundamental problems. There is no simple/quick fix to your code.

If you don't come from a C or C++ background, you may want to read a quick overview of them, at a minimum. Start with some of the Arduino example sketches and get a good understanding of how functions are defined and how they work.
> 1 votes

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


# Question
Title: Unplanned behavior with two power sources
I'm trying to control this servo, and whenever I leave the Uno connected, via USB, to the PC, most of the time the servo barely moves, and sometimes jitters.

simulate this circuit – Schematic created using CircuitLab

I connected the oscilloscope to try to understand / solve my problem, and I see that the signal I send is the same whether or not the USB is connected. I measured the voltage over the 5V/GND and it's constant at 5V and doesn't dip/spikes. I tried with a pull-down resistor on the signal pin (don't know if it's a good idea) and it doesn't change anything.

If I unplug the battery, but keep the USB connected, the servo stays immobile, but I figure that's because the Arduino can't feed a servo, hence why I wanted to use an external power for it. The second power source is a PowerBoost 1000C with a LiPo battery.

As soon as I unplug the USB port, the servo just starts moving properly, so I figured it must be interference of some kind. I saw the accepted answer to this question and it has me doubt whether I should use a battery while it's plugged in, but surely there is a way. Would I kind of need to connect the GND of my circuit to the GND wire of the USB before it actually enters the Arduino?

I didn't post the code as it's basically just the swipe demo from the website, and because it works when on battery only.

Regards

# Answer
Beginner error: As stated in the diagram, I connected the external source of power to the 5V pin, while it should have been connected to the Vin pin. /ashame
> 1 votes

---
Tags: arduino-uno, power, servo
---


# Question
Title: Transfer serial data to struct variable in Arduino
I have declared a struct with some variables that right now are fixed, but one of the variables on the struct needs to be what the Arduino's serial port reads.

```
struct testing_var
{
    const char *name;
    byte key[32];
    byte pt[16];
};

static testing_var const test1 = {
    .name        = "Speck-128-ECB",
    .key         = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                    0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
    .pt   = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                    0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
};

```

As you can see for how I have declared it, I'm trying to get a plaintext from the serial port and the Arduino should encrypt that. I have a function that does this encryption, but I can't quite figure out how to pass what the serial port reads to the struct.

```
void loop() {

  if (Serial.available()>0) {
    var1 = Serial.read();
}

```

I need to pass this *var1* as the variable *pt* in the struct. Any clues? I'm maybe missing something very obvious, but I don't usually work with structs.

**EDIT:** I'm trying to assign the value read by the serial port to the struct by creating another function that goes like this:

```
void setPlain(struct PlainText *myPlain, const char* thePlain){
    myPlain -> plaintext = the Plain;
   }

```

Then, in the *loop*, I use:

```
  if (Serial.available()>0) {
    var1 = Serial.read();
    setPlain(&PlainText, var1)
}

```

I'm getting an error using this function, I guess that it has something to do with the type of variable I'm trying to assign, these values are in HEX, not in char. But I'm not really sure it that's it or what other workaround should I use.

# Answer
> 1 votes
You read the serial port one char at time, and assign it to *test1.pt\[i\]*, where i is an index varying from 0 to 15.

And `test1` cannot be `const`, because you are going to modify it with the serial data.

Here is a test code showing how to do it.

```
struct testing_var
{
    const char *name;
    byte key[32];
    byte pt[16];
};

//  test1 cannot be 'const'
static testing_var test1 = {
    .name        = "Speck-128-ECB",
    .key         = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                    0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
    .pt   = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                    0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
};

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

void loop() {
  Serial.println("Enter 16 chars:");
  //  Read 16 chars from Serial
  for (int i=0; i < 16;) {
    if (Serial.available()) {
      test1.pt[i++] = Serial.read();
    }
  }
  // Do something with the data, like print it.
  for (int i = 0; i < 16; i++) {
    Serial.print(char((test1.pt[i])));
  }
  Serial.println();
}

```

---
Tags: arduino-uno, struct
---


# Question
Title: Arduino crashing during serial print for no obvious reason
I've written some Arduino Code which kept crashing and i couldn't find out why. Then i reduced the code as much as i could in order to see the problem. The reduced code currently doesn't do anything extraordinary except printing some strings over the serial line.

**This is the reduced code:**

```
void setup()
{
  Serial.begin(9600);
  Serial.print("Begin\r\n");
  send_wifi_beacon();
}
void loop()
{
  delay(1000);
}
void send_wifi_beacon()
{
  send_wlan_chip_command("AT+CIFSR");
  Serial.print("notreached"); // this part is never reached
  send_data_over_network(); // can't remove this line otherwise the crash won't happen which is weird since this is never called
}
void read_response_from_serial()
{
  delay(2000);
  Serial.print("==-1\r\n"); // crashes here
}
void send_wlan_chip_command(char* command)
{
  Serial.print("Sending command to wifi module: ");
  Serial.print(command);
  read_response_from_serial();
  Serial.print("Command response: ");
}
// this function is never called, since the crash happens before the call, but it can't be removed otherwise the crash won't happen
// also it can't  be altered then, the crash also will not happen.
void send_data_over_network()
{
  char number[3] = "12";
  //char number[3] = "";
  char length_of_payload[20] = "0123456789012345678"; // 20 digits if assuming 64 bit integer is the maximum this code will ever run on
//  char length_of_payload[20] = "";
  char *command;

  command = malloc(26);
  command = "AT+CIPSSEND";
  strcat(command, number);
  strcat(command, ",");
  strcat(command, length_of_payload);
  send_wlan_chip_command(command);
  free(command);
}

```

**This is the according output:**

> Begin Sending command to wifi module: AT+CIFSR==Begin
> Sending command to wifi module: AT+CIFSR==Begin
> Sending command to wifi module: AT+CIFSR==Begin
> Sending command to wifi module: AT+CIFSR==Begin

Which means that the arduino keeps crashing and resetting. This goes on forever.

The weird thing is, if I change the following two lines to: (in the"send\_data\_over\_network" function as in example above)

```
char number[3] = "1"; // changed from => char number[3] = "";
char length_of_payload[20] = "123"; // changed from => char length_of_payload[20] = "0123456789012345678";

```

**The output now changes to :**

I call this behaviour weird since it shouldn't have any influence on the result because this function(send\_data\_over\_network) is never called in the crash example from before.

**Troubleshooting options i already tried:**

* Reinstalling Arduino IDE , i tried with mutliple versions 1.8 , 1.6, 1.4. 1.0
* Different Arduino Boards (Arduino Uno and Arduino Mega)
* Different Laptops (since i thought maybe it's related to power issues of my laptop)

Maybe it's something obvious and i just can't see it, but i already spent +16h debugging, so help would be really appreciated.

# Answer
> 1 votes
This code looks wrong:

```
  command = malloc(26);
  command = "AT+CIPSSEND";
  strcat(command, number);
  strcat(command, ",");
  strcat(command, length_of_payload);
  send_wlan_chip_command(command);

```

First you allocate 26 bytes, then a new string is created, which you strcat to it. This happens in memory that is not allocated (or overwrites other data).

Instead of

```
  command = "AT+CIPSSEND";

```

use

```
  strcpy(command, "AT+CIPSSEND");

```

Also check that 26 bytes is enough, change it to 128 bytes to be sure (check the correct amount you need later).

# Answer
> 1 votes
You are almost certainly running out of memory and have a stack collision with the heap. Dynamic memory allocation and de-allocation is not a good idea when you have less than 2K RAM to work with. If you use malloc() use it only to allocate buffer space and then reuse the buffers. Put your test code entirely in setup and see what happens. Also check the amount of RAM allocated at compile time it may be more than you think.

```
char *buf1;
char *buf2;

void setup() {
   buf1 = (char *) malloc(10);
   buf2 = (char *) malloc(10);
   .
   .
   // test code here
}

```

---
Tags: arduino-uno, serial, arduino-mega, atmega2560
---


# Question
Title: Using ESP8266 to send email. However "HELO" responds with "ERROR". Possible cause?
I am developing a sketch that uses an Uno and an ESP8266 to send email via smtp2go. However "HELO" responds with "ERROR". What might be the source of the problem?

To explore this, I created another sketch that simply sends commands to the ESP8266, and displays the results. The wifi connection seems fine, as does the SMTP Server connect to mail.smtp2go.com. However, the next command issued "HELO 10.1.0.35" provides a response of "ERROR".

The ESP8266 is mounted on an ESP-01 board, and set @ 9600 baud. have tested with different chip sets. I have also tried using Gmail \[smtp.gmail.com,465 \], but results are the same.

\[I know that an ESP8266 can be used stand-alone. However the final sketch requires 13 data pins.\]

Output from sketch:

```
"ESP8266_ATcmdtest", compiled on: Jun  8 2017 at 17:58:18
Running on: Arduino UNO: ATmega328P

__________[ Disable echo (Echo sends back received command before response) ]__________
__________[ ATE0 ]__________
Response buffer:
OK

__________[ Delete server ]__________
__________[ AT+CIPSERVER=0 ]__________
Response buffer:
no change
OK

__________[ Restart the module ]__________
__________[ AT+RST ]__________
Response buffer:
OK
0,CLOSED
WIFI DISCONNECT
bB׆QR⸮⸮⸮ȤRN⸮ɥRL⸮H⸮⸮N⸮⸮d#@⸮⸮
WIFI CONNECTED

__________[ Check Firmware type [Responds with: AT version:1.2.0.0(Jul  1 2016 20:04:45) ]__________
__________[ AT+GMR ]__________
Response buffer:
AT+GMR
AT version:1.2.0.0(Jul  1 2016 20:04:45)
SDK version:WIFI GOT IP

__________[ Lists available APs ]__________
__________[ AT+CWLAP ]__________
Response buffer:
AT+CWLAP

+CWLAP:(0,"KCTcircuit2",-47,"08:bd:43:ff:6a:0c",1,21,0)
+CWLAP:(3,"49KHC",-88,"70:f1:96:66:29:ef",1,11,0)
+CWLAP:(3,"KCTstudy",-49,"04:a1:51:bf:6b:30",5,-11,0)
+CWLAP:(3,"Linksys05761",-75,"b4:75:0
e:64:54:b1",11,21,0)
+CWLAP:(3,"Pccd_main",-91,"14:91:82:83:f8

__________[ Get local IP address, e.g., 192.168.4.1 ]__________
__________[ AT+CIFSR ]__________
Response buffer:
AT+CIFSR
+CIFSR:STAIP,"10.0.0.4"
+CIFSR:STAMAC,"5c:cf:7f:34:

__________[ Set Station mode ]__________
__________[ AT+CWMODE=1 ]__________
Response buffer:
AT+CWMODE=1
OK

__________[ Set current multiplex mode ]__________
__________[ AT+CIPMUX=1 ]__________
Response buffer:
AT+CIPMUX=1

OK

__________[ Connect to AP ]__________
__________[ AT+CWJAP="KCTstudy","[pw redacted]" ]__________
Response buffer:
AT+CWJAP="KCTstudy","[pw redacted]"
WIFI DISCONNECT
WIFI CONNECTED

__________[ Prints the SSID of Access Point ESP8266 is connected to. ]__________
__________[ AT+CWJAP? ]__________
Response buffer:
AT+CWJAP?
busy p...
WIFI GOT IP

OK

__________[ Get IP address of ESP8266 station, e.g., 10.0.0.4 ]__________
__________[ AT+CIPSTA? ]__________
Response buffer:
AT+CIPSTA?
+CIPSTA:ip:"10.0.0.4"
+CIPSTA:gateway:"10.0.0.1"

__________[ SMTPServer connect ]__________
__________[ AT+CIPSTART=0,"TCP","mail.smtp2go.com",2525 ]__________
Response buffer:
AT+CIPSTART=0,"TCP","mail.smtp2go.com",2525
0,CONNECT

OK

+IPD,0,70:220 mail.smtp2go.com ESMTP Exim 4.87 Fri, 09 Jun 2017 00:59:07 +0000

__________[ Get information about connection ]__________
Response format  is:
STATUS:stat [ 2: Got IP, 3: Connected, 4: Disconnected]
+CIPSTATUS:id,type,addr,port,tetype [type: TCP, addr: IP address]
OK
__________[ AT+CIPSTATUS ]__________
Response buffer:
AT+CIPSTATUS
STATUS:3
+CIPSTATUS:0,"TCP","173.255.233.87",25

__________[ HELO ]__________
__________[ HELO 10.0.0.8 ]__________
Response buffer:
HELO 10.0.0.4
ERROR

```

---

Sketch code

```
#include <SoftwareSerial.h>

// _______________________________
#define sendit(x) ( { \
    Serial.print(F("__________[ ")); \
    Serial.print(x); \
    Serial.println(F(" ]__________")); \
     esp8266.write(x); \
   esp8266.write("\r\n"); \
     delay(300); \
     Serial.println(F("Response buffer: ")); \
     for (int i=0; i <= 99; i++) { \
         memset(buffer, 0, sizeof(buffer)); \
         delay(10); \
       bcount = esp8266.readBytes(buffer, sizeof(buffer)); \
           if (bcount == 0)  i = 100; \
           else { \
    if (bcount > 1) Serial.println(buffer); \
    delay(300); \
      } \
    } \
  } )

// _______________________________
#define desc(x) ( { \
    Serial.println(); \
    Serial.print(F("__________[ ")); \
    Serial.print(F(x)); \
    Serial.println(F(" ]__________")); \
  } )

// _______________________________
SoftwareSerial esp8266(11, 12); // RX, TX
char buffer[200];
String SerialReadBuffer = "";
char SerialByteIn; // Temporary variable
boolean SerialEnd = false;
int bcount;

// _______________________________
void setup()
{
    Initialise();
}

// _______________________________
void loop()
{
}

// ____________________________________________________________________________________________________
void Initialise()
{
    SerialReadBuffer.reserve(64);
    esp8266.begin(9600);
        // esp8266.begin(115200);
    Serial.begin(9600);
    CommandList2();
}

// ____________________________________________________________________________________________________
void CommandList2()
{
    desc("Disable echo (Echo sends back received command before response)");
    sendit("ATE0");
    desc("Delete server");
    sendit("AT+CIPSERVER=0");
    desc("Restart the module");
    sendit("AT+RST");
    desc("Check Firmware type [Responds with: AT version:1.2.0.0(Jul  1 2016 20:04:45)");
    sendit("AT+GMR");
    desc("Lists available APs");
    sendit("AT+CWLAP");
    desc("Get local IP address, e.g., 192.168.4.1");
    sendit("AT+CIFSR");
    desc("Set Station mode");
    sendit("AT+CWMODE=1");
    desc("Set current multiplex mode");
    sendit("AT+CIPMUX=1");
    desc("Connect to AP");
    sendit("AT+CWJAP=\"KCTstudy\",\"[pw redacted]\"");
    desc("Prints the SSID of Access Point ESP8266 is connected to.");
    sendit("AT+CWJAP?");
    desc("Get IP address of ESP8266 station, e.g., 10.0.0.4");
    sendit("AT+CIPSTA?");
    desc("SMTPServer connect");
    sendit("AT+CIPSTART=0,\"TCP\",\"mail.smtp2go.com\",25");
    desc("Get information about connection");
    Serial.println(F("Response format  is: "));
    Serial.println(F("STATUS:stat [ 2: Got IP, 3: Connected, 4: Disconnected]"));
    Serial.println(F("+CIPSTATUS:id,type,addr,port,tetype [type: TCP, addr: IP address]"));
    Serial.println(F("OK"));
    sendit("AT+CIPSTATUS");
    //
    // Problems start here
    //
    desc("HELO");
    sendit("HELO 10.0.0.4");
    Serial.println(F("__________________"));
}

```

# Answer
> 2 votes
You're sending the word "HELO" to the ESP8266 and the ESP8266 is, quite rightly, saying "What?!?! I don't know the command HELO!"

You have opened a connection in *multiple connection* mode with ID 0. You then have to *send* data through that connection. For instance:

```
AT+CIPSTART=0,"TCP\","mail.smtp2go.com",2525
OK
AT+CIPSEND=0,15
> HELO 10.0.0.4<CR><LF>
SEND OK

```

Using a protocol like SMTP in this mode is not easy. Better would be to use "unvarnished" mode:

```
AT+CIPSTART="TCP","mail.smtp2go.com",2525
OK
Linked
AT+CIPMODE=1
OK
AT+CIPSEND
> HELO 10.0.0.4<CR><LF>
250 mail.smtp2go.com Hello 10.0.0.4 [23.114.28.226]
MAIL FROM: "Foo Bar" <foo@bar.com>
250 OK
... etc ...
QUIT
221 mail.smtp2go.com closing connection

```

Note that just sending commands and blindly printing the responses isn't really the best way to go about it. You should be actively interpreting the responses that you get back and making decisions based upon them. Especially when you're in SEND mode. The SMTP protocol is two-way. You need to know what the responses are saying and what that means for your SMTP session.

# Answer
> 0 votes
Before sending "HELO 10.0.0.4" ... you should send a CIPsend command with the length of your sentence + 2

Here is the right command sequence:

```
AT+CIPSEND=4,15
HELO 10.0.0.4

```

Best regards

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


title: Changing Text Arduino inkShield

text:
# Question
Title: Changing Text Arduino inkShield
I have just received inkshield purchased from Nerd Creation Labs, I stacked inkshield on my Arduino Mega and uploaded THIS CODE provided by the creator of inkshield,and it works pretty well. I can print text ;)

Questions :

1: The code given above can only print text in a single Font. Can i add multiple Fonts in a single code.?

2: How can i change the Font to something like Times New Roman, Arial,calibri or more stylish Fonts like snell RoundHand and Zapfino.?

Please help

Thank you

# Answer
> 1 votes
The fonts are the little bitmaps starting at line 50. Each 16 bit value is 1 column of the letter to be printed. There are 10 columns of pixels per character (the `rowsPerChar` value). The least significant bit is the bottom row.

So to change the font all you need to do is change those bitmaps.

# Answer
> 0 votes
> 1: The code given above can only print text in a single Font. Can i add multiple Fonts in a single code.?

Sure you can.

> 2: How can i change the Font to something like Times New Roman, Arial,calibri or more stylish Fonts like snell RoundHand and Zapfino.?

The top 700-odd lines of the code are the font. You just need to find a way of creating the same kind of data from your own chosen font.

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


title: Alternative code for pinMode()?

text:
# Question
Title: Alternative code for pinMode()?
In my code I need to set five pins to output mode. I have the pinMode() statements in my setup.

I am trying to make my Arduino code run a bit faster, and I came across a tutorial which swaps digitalWrite() for PORTB &= \_BV(PB6) (high), and makes it run ~25 times faster.

I'm wondering if there's a similar type of substitution I can do for pinMode(), that will make it run faster as well? Or is pinMode() already a fast command, so I shouldn't worry about it?

Thanks

# Answer
It isn't worth it for something done once, if you only do it in `setup`. However if you need to toggle the mode frequently yes it can be done. You sadly haven't said which pins, but assuming they are D2 to D6 (digital pins 2 to 6) *on a Mega* you can do this to set **output** mode:

```
  DDRE |= bit(PE3) | bit(PE4) | bit(PE5); // D5, D2, D3
  DDRG |= bit(PG5); // D4
  DDRH |= bit(PH3); // D6

```

For **input** mode you have to "and" in the ones-complement of the bits like this:

```
  DDRE &= ~(bit(PE3) | bit(PE4) | bit(PE5)); // D5, D2, D3
  DDRG &= ~(bit(PG5)); // D4
  DDRH &= ~(bit(PH3)); // D6

```

The exact register names are in the datasheet, and the mappings to the pins on your board are in the schematic (available from the Arduino site). The relevant part is this:

The bit numbers are in grey on the left (eg. PE4) and the board pin numbers are in green on the right (eg. 2 is digital pin 2).

The `bit` macro works similarly to the `_BV` one you mentioned in your question. It shifts `1` left the required number of bit positions to be in the right place.

---

A somewhat simpler and more portable solution is to use the digitalWriteFast library which you can download from:

https://github.com/NicksonYap/digitalWriteFast

This uses various compiler tricks to detect if you are using a constant for `pinMode` and `digitalWrite` and converts them into the appropriate register manipulation. You just install the library and add `Fast` to the function names, eg.

```
pinModeFast (2, OUTPUT);
digitalWriteFast (2, HIGH);

```
> 3 votes

# Answer
The Arduino reference manual has all you need to know:

The register you need is the `DDRx` register (Data DiRection X). Set a bit to 1 for output and 0 for input.
> 1 votes

# Answer
yeah. the corresponding registers are DDRx.

with a little bit of coding, you can easily convert pinMode() to your own, say, mypinMode() that operates on the DDRx directly.

the datasheet is your best friend, as always.
> 1 votes

---
Tags: arduino-mega
---


title: Why is CLK_FLASH separate from CLK_CPU?

text:
# Question
Title: Why is CLK_FLASH separate from CLK_CPU?
The ATmega328P has a separate clock signal for Flash and EEPROM (CLKFLASH) than it has for the RAM (CLKCPU). Why is this?

# Answer
It's to do with programming the chip. When you are programming the chip using an external programmer you need the flash and EEPROM to be running. However you don't want the CPU to be running since you are doing things with the flash that it would normally access. By having the CPU (and RAM) on a separate clock you can clock the flash without clocking the CPU and all is well.
> 2 votes

---
Tags: atmega328
---


# Question
Title: Combining 2 IF statements, getting nowhere and pulling hair out! ;)
I\`m new here so just wanted to say hi!

I have been messing about with Arduino now for about 2 weeks, picking and trying different sketches for a greenhouse project I need.

Trying all sorts with LCD, temperature etc.

But what I actualy wanted was just a simple multiple timer say setting for every hour 9-6 activate for 2 mins to turn on a misting system for my plants, and that is now what I present in the following sketch, simple enough and it works, I have just removed some of the timings to keep the code compact on here.

Now the tricky bit, I want the misting system to come on in those hours chosen, but only if the Humidity is below a certain thresh hold, thats where I\`m running into issues.

If anyone can look over the code and advise me where to put "if(h \< humLowTrigger){"

I have tried before the times, included it in each line of the times and after the times and still not working.

So all help and knowledge greatly appreciated.

Cheers for now Alan

```
#include <Wire.h>
#include "RTClib.h"
#include "DHT.h"

#define humLowTrigger 70
#define DHTPIN 7
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

RTC_DS1307 rtc;

void setup () {

Serial.begin(9600);
dht.begin();
Wire.begin();
rtc.begin();

pinMode( A2, OUTPUT);
digitalWrite(A2, LOW);
}

void loop () {

float h = dht.readHumidity();
float t = dht.readTemperature();

DateTime now = rtc.now();

if (now.hour() == 15 && now.minute() == 5) {
digitalWrite(A2, HIGH);
}
if (now.hour() == 15 && now.minute() == 8) {
digitalWrite(A2, LOW);
}
if (now.hour() == 15 && now.minute() == 10) {
digitalWrite(A2, HIGH);
}
if (now.hour() == 15 && now.minute() == 12) {
digitalWrite(A2, LOW);
}

Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %");
Serial.println();
Serial.println();
delay(2000);

}

```

# Answer
If you want to do something when two or more conditions meets , use an *and* operator (&&), like this:

```
if (h < humLowTrigger && now.hour() == 15 && now.minute() == 5) {
... do something ...
}

```

If you have a lot of conditional statements, you can simplify:

```
if (h < humLowTrigger) {
   if (... other conditions 1 ...) {
     do something 1
     }
   ...
  if (... other condition n ...) {
     do something n.
     }
}

```

In your specific case:

```
if(h < humLowTrigger) {
  if (now.hour() == 15 && now.minute() == 5) {
    digitalWrite(A2, HIGH);
  }
  if (now.hour() == 15 && now.minute() == 8) {
    digitalWrite(A2, LOW);
  }
  if (now.hour() == 15 && now.minute() == 10) {
    digitalWrite(A2, HIGH);
  }
  if (now.hour() == 15 && now.minute() == 12) {
    digitalWrite(A2, LOW);
  }
}

```

**Better version**

But there is a problem with the previous code, beacuse the mister **must** turn off no matter what the humidity level is.

```
// Turn on only if humidity below threshold.
if (h < humLowTrigger && now.hour() == 15 && (now.minute() == 5 || now.minute() == 10)) {
    digitalWrite(A2, HIGH);
  }
}
// Turn off always.
if (now.hour() == 15 && (now.minute() == 8 || now.minute() == 12) {
    digitalWrite(A2, LOW);
   }

```
> 1 votes

# Answer
In addition to LookAlterno's answer (which I upvoted), the last part can be reduced to:

```
if ((h < humLowTrigger) && (now.hour() == 15)) {
  if (now.minute() == 5) {
    digitalWrite(A2, HIGH);
  }
  if (now.minute() == 8) {
    digitalWrite(A2, LOW);
  }
  if (now.minute() == 10) {
    digitalWrite(A2, HIGH);
  }
  if (now.minute() == 12) {
    digitalWrite(A2, LOW);
  }
}

```
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: SIM900 + GPS Module making http rest calls
I am wondering if its possible to program a board that is developed using SIM900 and GPS module to make http rest calls.

I found this library. My question is, will I need a microcontroller for this ?

# Answer
> My question is, will I need a microcontroller for this ?

**Yes.** There are certain things that you need a "man in the middle" to control. Without a microcontroller, how will you tell it what site to visit? How often to send the HTTP request? How to format the HTTP request? Is there any other thing you need this to do?

People often hope that they can hook up two **complex** devices that are almost setup to be slaves (like shields, sensors, and outputs) to a microprocessor. Unless the two were specifically designed to work together (or they use a standard, very specific protocol), your chances of building this without a microchip is like trying to build a skyscraper with popsicle sticks. It's possible, but there are cheaper and much easier/more efficient ways to doing that.

*Well, they're both SPI/I2C/UART/USB/Serial! Why not?* Well, although we're all humans and we use verbal communication as a protocol, do we all understand each other? Not really... For those protocols, they're designed to have a "master" and a "slave." A master would be powerful and have control over all the slaves. Hooking a GSM and GPS shield together is like hooking two slave devices together. It's not going to work out (unless you're aiming for blue smoke...)

**tl;dr:** you trying to mix two things that don't mix. Buy an Arduino Nano clone for $8 and have your circuit actually work.
> 1 votes

# Answer
I partially agree to Anonymous Penguin's answer.

But if you want go for a deep dive, actually SIM900 / SIM800 GSM modules also have a facility called Embedded AT. Just Google it using "SIM900 Embedded AT". They have a pdf here at the time of writing this.

According to this application note, SIM900 is actually ARM core and using Embedded AT you can utilize most of things you do in External MCU. So if you are thinking of some application, which can be developed into SIM900, Yes you can avoid using external MCU. You can give AT Commands from your application to SIM900 core using API. You even get 1 UART to interface GPS chip with SIM900. If you move to SIM800 family they have more UARTs.

PS: I haven't used it.
> 1 votes

---
Tags: tinygps
---


# Question
Title: Controlling an analog potentiometer using an Arduino
I want to be able to control an analog potentiometer. I'd like to be able to go from the minimum range to the maximum range possibly using an Arduino and a motor/servo. I want to be able to control vintage equipment, so the knobs on the pot must still work. I want to be able to rotate both by hand and by sending a (MIDI) signal.How would I go about doing this?

# Answer
The first problem we have is that replacing the original potentiometer might be wrong thing to do. Analog audio hardware is usually nonlinear, because the volume of the sound is actually a logarithmic function. So the potentiometers might be fine tuned specifically for particular device, and impossible to acquire today since it's vintage.

I suggest a different approach. Connect the knobs to rotary encoders, or cheap linear potentiometers. That way you will receive data about what the user is doing, and what setting does he want to change. They usually are small and you might even fit an extra el-cheapo 28BYJ485V stepper motor to move the knobs to provide feedback. (It can be modified doubling it's torque)

Move all the audio potentiometers inside the case of the device and connect them directly to a stepper motor or a servo to move them only with Arduino.
> 1 votes

---
Tags: servo, potentiometer
---


title: Sine wave PWM Arduino Micro

text:
# Question
Title: Sine wave PWM Arduino Micro
I'm trying to generate a sine wave on my Arduino micro. I used this code.

```
int Pin = 9;

void setup()
{
 Serial.begin(9600);
 pinMode(Pin, INPUT);
}

void loop()
{
 float something = millis()/10000.0;
 int value = 128.0 + 128 * sin( something * 2.0 * PI  );
 analogWrite(Pin,value);
}

```

I have a low pass filter at the output of the pin to smooth the wave. The problem is : I get a nice square wave with a duty cycle from 0 to 100%, but not a sine wave. Ideally, I'd like to set a frequency of 10 Hz. Can anyone tell me where I made a mistake ? Thanks a lot !!!

# Answer
it is how PWM works. digital pins can do only 1 and 0.
> 1 votes

# Answer
> Can anyone tell me where I made a mistake ?

put a lpf on the pwm output.
> 0 votes

---
Tags: pwm, wave
---


# Question
Title: Open Parent Class as Child Class (SD Fat Library)
I'm currently using the SDFat library and am passing a global `FatFile`

I if have a function that requires an `SdFile` type and I know that a given instance of `FatFile` is a valid `SdFile` what is the best way to reopen `FatFile F` as `SdFile J`?

Right now I'm doing:

```
SdFile ActiveFile;  //Global Active File
...
void SDRun (FatFile &RunFat)
{
  SdFile RunRoot;
  RunRoot.open("/", O_READ);
  ActiveFile.close();
  ActiveFile.open(&RunRoot,RunFat.dirIndex(),O_READ);
  ....

```

However, this only works when `RunFat` is in the root directory.

# Answer
If `RunFat` is an instance of `SdFile` you can just cast it:

```
SdFile& RunRoot = dynamic_cast<SdFile&>(RunFat);

```

`RunRoot` and `RunFat` are now the exact same file in the exact same state (no need to open it or anything) but seen as an `SdFile` not a `FatFile`.
> 1 votes

---
Tags: arduino-mega, sd, fat
---


# Question
Title: How much power can a proto board handle?
I have been working on a project where I will be powering an Arduino and some LED light strips (2 x 3 Meter strips w/ 30 LEDs per meter). I am powering all of it from a 5v 10amp power supply.

Currently I have split the power cable and have it running to the board and the LED's in separate runs.

As I move from a breadboard to a more permanent proto-board, it would be great to add a barrel connector onto the proto-board and just have a single plugin for power so I can easily disconnect it.

Will this cause any issues if all of the power comes from the proto-board? Thanks!

# Answer
> 1 votes
No, it's not practical do to that with protoboard of any form.

There are two reasons for this:

1. Barrel jacks are not rated for 10A - I think the most powerful I have seen is 3A.
2. To handle 10A over (for example) 6 inches of track you would require tracks roughly 8mm wide at 1oz copper. No protoboard provides such tracks.

Even if you're only using half the capacity of your power supply (5A) you still exceed a barrel jack, and would need traces about 3mm wide.

# Answer
> 1 votes
A common way to solve this is to solder a wire onto the tracks on the proto-board.

# Answer
> 0 votes
There is no problem to have your power source coming from your protoboard to supply your arduino since your protoboard can gives to your arduino one of these possibilities explained here.

---
Tags: esp8266, power, wires, neopixel, prototype
---


title: Inkjet Printer Robot Wheels

text:
# Question
Title: Inkjet Printer Robot Wheels
I'm newbie about Arduino. Can i build arduino robot wheels using Canon/Epson Cartridge inkjet printer?

The idea is like Drawing Robot

but i want to use cartridge printer instead of using a pen.

so after searching, and it look like ZUtAPocketPrinter

The Drawing Robot is using Trinket Pro And ZUtAPocketPrinter is using Arduino (don't know using Uno/Nano/etc)

Can I use Trinket Pro or what types of arduino that i can use (Uno, Nano)?

And what hardware, sensor that require to scan/measure size of the paper?

And if there is tutorial, please share the link.

# Answer
Usually a robot uses 2 identical motors for drive in order to change directions or go straight. Usually a printer will only have 1 motor to drive the paper and 1 motor to drive the print head. And usually they are not identical. Making it difficult to build a useful robot. Also, printers usually use stepping motors. Most people building their first (small) robot usually use continuous servo motors. This makes for an easy to build first (small) robot as seen in this picture:
> 1 votes

---
Tags: robotics
---


# Question
Title: No serial data from Adafruit GPS (on Arduino 101)
New Adafruit GPS connected to my Arduino 101 board.

When trying to use the RX/TX hardware serial (on digital pins 0 / 1), with a simple sketch (described by Adafruit) to output a serial response, I'm not seing anything in the serial monitor (9600 baud).

```
// this sketch will allow you to bypass the Atmega chip
// and connect the Ultimate GPS directly to the USB/Serial
// chip converter.

// Connect VIN to +5V
// Connect GND to Ground
// Connect GPS RX (data into GPS) to Digital 0
// Connect GPS TX (data out from GPS) to Digital 1

void setup() {}
void loop() {}

```

Wires connected as in the sketch, also tried swapping them out in case of faulty wire.

Went on to try TinyGPS++ default example code, across a variety of pins: 3,4 & 8,9 & 0,1.

```
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample code demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx). EDITED BELOW.
*/

static const int RXPin = 8, TXPin = 9;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

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

  Serial.println(F("FullExample.ino"));
  Serial.println(F("An extensive example of many interesting TinyGPS++ features"));
  Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
  Serial.println(F("Sats HDOP Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum"));
  Serial.println(F("          (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail"));
  Serial.println(F("---------------------------------------------------------------------------------------------------------------------------------------"));
}

void loop()
{
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

  printInt(gps.satellites.value(), gps.satellites.isValid(), 5);
  printInt(gps.hdop.value(), gps.hdop.isValid(), 5);
  printFloat(gps.location.lat(), gps.location.isValid(), 11, 6);
  printFloat(gps.location.lng(), gps.location.isValid(), 12, 6);
  printInt(gps.location.age(), gps.location.isValid(), 5);
  printDateTime(gps.date, gps.time);
  printFloat(gps.altitude.meters(), gps.altitude.isValid(), 7, 2);
  printFloat(gps.course.deg(), gps.course.isValid(), 7, 2);
  printFloat(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
  printStr(gps.course.isValid() ? TinyGPSPlus::cardinal(gps.course.value()) : "*** ", 6);

  unsigned long distanceKmToLondon =
    (unsigned long)TinyGPSPlus::distanceBetween(
      gps.location.lat(),
      gps.location.lng(),
      LONDON_LAT,
      LONDON_LON) / 1000;
  printInt(distanceKmToLondon, gps.location.isValid(), 9);

  double courseToLondon =
    TinyGPSPlus::courseTo(
      gps.location.lat(),
      gps.location.lng(),
      LONDON_LAT,
      LONDON_LON);

  printFloat(courseToLondon, gps.location.isValid(), 7, 2);

  const char *cardinalToLondon = TinyGPSPlus::cardinal(courseToLondon);

  printStr(gps.location.isValid() ? cardinalToLondon : "*** ", 6);

  printInt(gps.charsProcessed(), true, 6);
  printInt(gps.sentencesWithFix(), true, 10);
  printInt(gps.failedChecksum(), true, 9);
  Serial.println();

  smartDelay(1000);

  if (millis() > 5000 && gps.charsProcessed() < 10)
    Serial.println(F("No GPS data received: check wiring"));
}

// This custom version of delay() ensures that the gps object
// is being "fed".
static void smartDelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

static void printFloat(float val, bool valid, int len, int prec)
{
  if (!valid)
  {
    while (len-- > 1)
      Serial.print('*');
    Serial.print(' ');
  }
  else
  {
    Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1); // . and -
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
      Serial.print(' ');
  }
  smartDelay(0);
}

static void printInt(unsigned long val, bool valid, int len)
{
  char sz[32] = "*****************";
  if (valid)
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  smartDelay(0);
}

static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
{
  if (!d.isValid())
  {
    Serial.print(F("********** "));
  }
  else
  {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d ", d.month(), d.day(), d.year());
    Serial.print(sz);
  }

  if (!t.isValid())
  {
    Serial.print(F("******** "));
  }
  else
  {
    char sz[32];
    sprintf(sz, "%02d:%02d:%02d ", t.hour(), t.minute(), t.second());
    Serial.print(sz);
  }

  printInt(d.age(), d.isValid(), 5);
  smartDelay(0);
}

static void printStr(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
  smartDelay(0);
}

```

Serial is spitting out this for every update:

> No GPS data received: check wiring

GPS is on, and can see based on the fix LED that satellite fix has occurred in both tests – no difference in output. Wires checked.

Maybe suboptimal pin solder job, but can't see that it should give no signal?

EDIT: After suggestions, re-soldered pinheader – still nothing in the serial prompt on hardware serial (pin 0,1), software serial (pin 3,4) and TinyGPS++ throws the same error (pin 3-4 + 8-9). Double-checked RX/TX order.

A colleague found an old Ublox Neo 6-M GPS, I plugged it in and repeated the above with the same empty serial results, not sure what to make of this..

# Answer
Accidentally fixed it when booting up the board tonight – not sure what changed but the serial prompt is on fire.

Wires: 5V - VIN, GND – GND, TX – 8, RX – 9

**Code:**

```
#include <SoftwareSerial.h>

// setup gps serial
int gpsTxPin = 8;
int gpsRxPin = 9;
SoftwareSerial gpsSerial(gpsTxPin, gpsRxPin);

void setup()
{
  Serial.begin(9600);  //set monitor to 9600

  gpsSerial.begin(9600); //adjust for GPS unit

  Serial.println("Ready!");
}

void loop()
{
  while(gpsSerial.available())
  {
    char c = gpsSerial.read();
    Serial.print(c);
  }
}

```

**Excerpt from serial monitor:**

```
...

$GPVTG,248.75,T,,M,0.19,N,0.35,K,A*3F
$GPGGA,231351.000,,,,,0,05,,,M,,M,,*7A
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSV,2,1,07,13,65,290,32,30,54,066,36,20,48,286,33,15,31,288,31*75

...

```
> 1 votes

---
Tags: gps
---


# Question
Title: Is it possible to configure FRAM memory for use as stack and heap?
I'm using the Adafruit I2C FRAM breakout board with my Nano and it works as advertised, but every time I write a variable to this thing I have to use library function calls with addressing. This makes it run slower than I want it to, especially since I'm using the memory to keep camera pixel information and I need to process it quickly.

As user Majenko put it:

> A write of a single byte requires 4 bytes in a transaction. That's 4 bytes, 1 start, 4 ack and 1 stop bit. So (4x8)+1+4+1 = 38 bits.
>
> A read of a single byte, with "repeated start", requires 5 bytes per transaction, with 2 start, 4 acks, 1 nack and 1 stop. That's (5\*8)+2+4+1+1 = 48 bits.
>
> So for a read and write it's 38+48 = 86 bits.
>
> Therefore you'd require 86\*512 I2C clock cycles to transfer all 512 bytes in both directions - that's 44032 clock cycles.
>
> At 400,000 bits per second it is 44032/400000 = 0.11 seconds, or 110ms of the time spend transferring data, not counting the time it takes to actually process and prepare the data, fill registers, look for status flags, etc.
>
> If it is taking half a second then at 400,000 bits per second you have 44032 / (400000/2) * 100 = 22% of the time it's actually transmitting or receiving data over I2C.

It's much faster to write entire arrays at a time, but I need to write the data int-by-int as the data is encountered, since my whole reason for using the breakout board was to avoid needing local buffer space.

So is it possible to somehow configure this so that my I2C bus writes to the FRAM memory autonomously just like it does with the stack/heap in the onboard SRAM memory? Because then I could just declare my arrays as normal and let the processor take care of it, and then I would be so happy.

# Answer
> 2 votes
**No, you can't use SPI or I2C memories to store stack or heap data in AVR microcontrollers**, as the AVR MCUs do not allow to map memories connected to the SPI or I2C buses. In other words, there is no way to tell the MCU that you connected a SPI or I2C memory, and how to use it, automatically. Therefore you can only use such memories to manually store/read data, by manually issuing all the correct command sequences, which will be very slow (as you wrote you are already doing by calling some libary functions).

Instead, you can use an external PARALLEL memory, connected to the external memory bus, which is present on SOME AVR microcontrollers (unfortunately, the ATMEGA328 has no external memory bus). Still you'll get a much slower performance with respect to the internal memory.

Finally, Arduino is not a good platform to process (or store/read) pixel data from a camera, due to severe computing power and memory limits. Even if there are more powerful Arduino (or Arduino-compatible) boards, which feature much more powerful processors (e.g. Cortex M3 or M4), you would probably need to program them using a very optimized C (and not C++!) code, or even ASM. But at this point, there would no reasons to use an Arduino-compatible platform, instead of an another one, possibly much more powerful or even cheaper.

# Answer
> 1 votes
Yes it is possible to have c variables use external RAM. The Atmel AVR FAQ discusses this. It's also possible to have the heap and stack (not recommended but possible), use external RAM.

Bear in mind that having this dealt with autonomously is still going to take roughly the same amount of time as it's going to have to execute similar functions to the ones you list above, albeit without having to code the transactions.

Have you considered a mega, and cache 1-6k of data then transfer that all at once. Using SPI would be faster, even more so with 1-6k. You can have an SPI LCD and RAM off the same pins, they just need an additional digital pin for the second device.

# Answer
> 0 votes
I don't have experience with FRAM, but below are some results with SRAM: 23LC1024 (128 KB SRAM with SPI). Tests have been performed with an Arduino Uno.

(I had to use an answer instead of a comment because of the (screenshot) table alignment.

As you can see, write/read of a page (32 bytes) is faster than other types, but it depends on the amount of bytes you have to write to use pages.

(Because I want to use reasonable complex structures, I decided to go for a microcontroller with more RAM because stack and heap space cannot be used from external SRAM).

---
Tags: arduino-nano, memory-usage, sram
---


title: Multiple timed functions (timing off)

text:
# Question
Title: Multiple timed functions (timing off)
Desired program:

I have 3 momentary push buttons and a 4-channel relay board with my Arduino Uno. The relays are connected to 2 sinks, a shower, and a pump. Each push button should turn the pump and its respective fixture on for 10 seconds. I used a time buffer to debounce the push buttons.

Problem:

The time in which the function stays on is inconsistent. Sometimes 10 seconds, sometimes 3 seconds. Additionally all the relays turn off at the same time even if they were started at different times. they should all be individually timed and the pump should stay on as long as any of the three other relays are on.

Wiring Diagram:

Code:

```
//initialize and declare variables
// Pins 10,11,12,13 will be connected to their respected relays
const int pump = 13;
const int relay2 = 12;
const int relay3 = 11;
const int relay4 = 10;

//initialize pins 2,3,4 to be connected to the momentary push buttons
const int buttonPin1 = 2;
const int buttonPin2 = 3;
const int buttonPin3 = 4;

//these variables track the state of the buttons, low if not pressed, high if pressed
int buttonState1 = LOW;
int buttonState2 = LOW;
int buttonState3 = LOW;

//Initialize pin states for valve check
int relay2State;
int relay3State;
int relay4State;

long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 100; // the debounce time; increase if the output flickers
unsigned long previousMillis = 0;
unsigned long previousMillis2 = 0;
unsigned long previousMillis3 = 0;
unsigned long runTime = 10000;

void setup() {
  //set pins connected to the relays as outputs.
  pinMode(pump, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);

  //set push buttons as inputs
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);

  //initialize the starting state of the relay pins
  digitalWrite(pump, HIGH);
  digitalWrite(relay2, HIGH);
  digitalWrite(relay3, HIGH);
  digitalWrite(relay4, HIGH);
} // close void setup

void loop() {
  unsigned long currentMillis = millis();
  unsigned long currentMillis2 = millis();
  unsigned long currentMillis3 = millis();
  //sample the state of the buttons
  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);
  buttonState3 = digitalRead(buttonPin3);
  //check to see if any valves are open
  relay2State = digitalRead(relay2);
  relay3State = digitalRead(relay3);
  relay4State = digitalRead(relay4);
  //filter out any noise by setting a time buffer
  if ((millis() - lastDebounceTime) > debounceDelay) {
    //sample the state of the buttons
    buttonState1 = digitalRead(buttonPin1);
    buttonState2 = digitalRead(buttonPin2);
    buttonState3 = digitalRead(buttonPin3);
    //check to see if any valves are open
    relay2State = digitalRead(relay2);
    relay3State = digitalRead(relay3);
    relay4State = digitalRead(relay4);
  }

  // if button1 has been pressed, let's toggle the pump and relay2 from off
  //to on for 10 seconds
  if (buttonState1 == HIGH) {
    digitalWrite(relay2, LOW); // turn relay2
    lastDebounceTime = millis(); // set the current time
  }
  if (currentMillis - previousMillis > runTime) {
    digitalWrite(relay2, HIGH); // turn relay2
    previousMillis = currentMillis;
  }
  //if button2 has been pressed, lets toggle the pump and relay3 from off
  //to on for 10 seconds
  if (buttonState2 == HIGH) {
    digitalWrite(relay3, LOW); // turn relay3 on
  }
  if (currentMillis2 - previousMillis2 > runTime) {
    previousMillis2 = currentMillis2;
    digitalWrite(relay3, HIGH); // turn relay3 off
  }
  // if button3 has been pressed, lets toggle the pump and relay4 from off to
  //on for 10 seconds
  if (buttonState3 == HIGH) {
    digitalWrite(relay4, LOW); // turn relay4 on
    lastDebounceTime = millis(); // set the current time
  }
  if (currentMillis3 - previousMillis3 > runTime) {
    previousMillis3 = currentMillis3;
    digitalWrite(relay4, HIGH); // turn relay4 off
  }
  // if any valve is open, turn the pump on
  if(relay2State == LOW || relay3State == LOW || relay4State == LOW) {
    digitalWrite(pump, LOW);
  } else {
    digitalWrite(pump, HIGH);
  }
} // close void loop

```

Any help would be greatly appreciated. I think I'm stuck in the time buffer for the debounce and my time checks aren't updating right.

# Answer
In a program like this it rapidly becomes quite confusing with the variable names all being so similar. Because of this, this is a good candidate for creating a `class` to do the job for you. This is because you have sets of functionality and variables that are duplicated to do the same job with different settings (IO pins).

It would be a trivial matter to create a `class` that turns on an output for a specified amount of time:

```
class TimedOutput {
    private:
        uint8_t _pin;
        uint32_t _started;
        uint32_t _runtime;
        bool _running;

    public:
        TimedOutput(uint8_t pin, uint32_t runtime) {
            _pin = pin;
            _runtime = runtime;
            _started = 0;
            _running = false;
        }

        void begin() {
            pinMode(_pin, OUTPUT);
            digitalWrite(_pin, LOW);
        }

        void start() {
            digitalWrite(_pin, HIGH);
            _running = true;
            _started = millis();
        }

        void run() {
            if (!_running) return;
            if (millis() - _started >= _runtime) {
                digitalWrite(_pin, LOW);
                _running = false;
            }
        }
};

// Create the object
TimedOutput shower(10, 10000); // Output on pin 10 for 10 seconds
TimedOutput sink(11, 3000);    // Output on pin 11 for 3 seconds

void setup() {
    // Configure the pin
    shower.begin();
    sink.begin();
    pinMode(2, INPUT_PULLUP); // Button
    pinMode(3, INPUT_PULLUP); // Button
}

void loop() {
    // Start it if the button is pressed:
    if (digitalRead(2) == LOW) {
        shower.start();
    }

    if (digitalRead(3) == LOW) {
        sink.start();
    }

    // Do the checking for if it needs to stop:
    shower.run();
    sink.run();
}

```
> 3 votes

# Answer
Take a modular approach to it.

For example, break the functionality intwo two pieces.

Readbutton1() returns 1 if and only if button 1 has been pressed and it passed debouncing. There are tons of ways to do that.

Energizerelay1() is called to energize relay number 1 for 10 seconds. Again, there are tons of ways to do that.

Then you can integrate them all together in your loop.

Fairly easy. The key to any programming is to break down a task into individual modules and then reintegrate those modules together to perform the desired the task.

Coding those individual modules is often simple.
> 0 votes

---
Tags: programming
---


# Question
Title: Why don't these sketches produce a similar output?
I compiled the following two sketches with the compiler used by the Arduino IDE and ran them on an Arduino UNO (smd edition). I'm using:

* Arduino IDE v. 1.8.0
* Arduino AVR Boards v. 1.6.20

1.

```
void setup() {

  Serial.begin(115200);
  unsigned long a, b;
  //unsigned long c, d;

  a = micros();
  for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
  b = micros();
  Serial.println(b - a);

  //c = micros();
  //for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
  //d = micros();
  //Serial.println(d - c);

}

void loop () {}

```

2.

```
void setup() {

  Serial.begin(115200);
  unsigned long a, b;
  unsigned long c, d;

  a = micros();
  for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
  b = micros();
  Serial.println(b - a);

  c = micros();
  for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
  d = micros();
  Serial.println(d - c);

}

void loop () {}

```

These were the outputs on the serial monitor:

1. `2452320`
2. `3332640
 3332704`

Why did each of the two `for` loops in the second sketch take roughly 33% more time to execute than the loop in the first one?

# Answer
The different time implies different (number of) instructions being executed.  ~~This is most probably due to the crappy GCC compiler optimizations.~~

~~In the former sketch, probably the compiler manages to use only registers, which are very fast. In the second one, the compiler THINKS it needs 8 more bytes, and there are no registers left, so it uses the stack (internal RAM) to store some variables, which is slower. (still, the optimizer should realize that in fact it don't need more bytes, because a and b are not used after the first println()). To access to a SRAM location, you need a LOAD/STORE operation, which takes a longer time, with respect to an operation between registers (beside having to load the memory address to X, Y o Z). Probably, the compiler is even crappier, because, instead of putting the rarely-used variables a,b,c,d on the stack, it puts i (which is always incremented) or other variables used in digitalRead().
Still, to explain where is the trouble (i.e. where compiler fails in optimizing the register allocation/usage), you should disassemble the object code. Use for instance Atmel Studio, which still uses GCC, but has a good debugger, disassembler and cycle-exact analysis.
~~

~~Still, this is very strange, perhaps optimizations were not enabled the platform.txt of your arduino?~~

EDIT: Using Arduino 1.8.0, I tested the two sketches and analyzed the lss (generated using avr-objdump). The compiler optimizes a lot more the first code. Instead of making a CALL to digitalRead() (as it happens in the second sketch) it probably recognizes that such function is called only once on the code. Therefore it makes a rjmp to it. At the end of that function, there won't be a RET but a branch to the point where i is computerd and checked (actually i is not incremented, actually gets decremented and checked against 0).

In other words, even if the two codes are equal (except that the second sketch runs the same code twice), they are compiled (optimized) differently.
> 1 votes

---
Tags: programming, compile, time
---


# Question
Title: Problem with simple sound detection circuit using a microphone
I am very new to this community. My first project with Arduino was using a LDR (light dependent resistor) in a circuit like this:

The input I got was as expected between 0 - 1023.

I then tried a similar project this time using a sound sensor like this:

My circuit is as follows:

1. A0 on mic to A0 on Arduino
2. GND to GND
3. +ve to 5V
4. LED along with resistor to digital pin 9 on Arduino

My program is as follows:

```
const int analogInPin = A0;
int sensorValue = 0;

void setup() {
  pinMode(analogInPin, INPUT);
  pinMode(9, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  sensorValue = analogRead(analogInPin);
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\n");
  if(sensorValue > 900)
    digitalWrite(9,HIGH);
  else
  digitalWrite(9,LOW);
}

```

The problem is the serial monitor gives a weird reading, randomly giving 1023 and 0 after regular intervals.

```
sensor = 124
sensor = 0
sensor = 1023
sensor = 39
sensor = 352
sensor = 1023
sensor = 142
sensor = 0
sensor = 1023
sensor = 44
sensor = 338
sensor = 1023
sensor = 163
sensor = 0
...
...

```

I can't figure out the problem myself so I came here.

# Answer
> 2 votes
I plotted the values you got in a spreadsheet:

You must admit that looks a bit like a sound wave! If you want to know if it is a soft sound or a loud sound you really need to see the maximum values (1023 in your case). If the maximum was 512 then clearly the incoming sound isn't as loud.

An alternative, if you just want loudness would be to filter the incoming signal, eg.

simulate this circuit – Schematic created using CircuitLab

This would smooth the incoming voltage so that consecutive readings would be in a narrower range.

---

Warning: Judging by the graph, you may be getting negative input into A0. The Arduino pins are not designed for negative voltage. You may want to use a diode to eliminate the negative component.

# Answer
> 1 votes
Based on your code, it looks like you are trying to use the analog signal to obtain a digital output (turn an LED on or off). The sound sensor board does this for you and has a digital output pin called "D0".

Heres a simple sketch using the serial monitor to show you what the sensor "D0" pin is putting out. Connect ground and 5 volts as you did before, and connect sensor D0 to Arduino pin 3.

```
const byte DigitalInputPin = 3;

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

void loop(){
  Serial.print("Digital Pin = " );
  Serial.println(digitalRead(DigitalInputPin));
  delay(50);
}

```

You don't have to connect the sensor to an Arduino to adjust it or test it. There are 2 LEDs on the sensor circuit board. The one closest to the potentiometer will turn on when the D0 pin is high and off when it's low. You use the potentiometer to set the "trigger point" based on the level of sound you want to make the output go high.

---
Tags: arduino-uno, programming, analogread
---


title: Do I need an Arduino for BLE?

text:
# Question
Title: Do I need an Arduino for BLE?
I have built a prototype that uses RedBear Lab's Blend micro board (http://redbearlab.com/blendmicro/). The board combines Arduino and a BLE chip (Nordic nRF8001). The application is fairly simple

1. iPhone finds and connects to BLE chip
2. When user presses a button on iPhone a message is sent to the Blend Micro board
3. Based on the message (3 choices) the Arduino reads analog input from one of the pins
4. The reading is passed back to the phone via BLE

Everything works well. My question is

1. If I were to evolve this into something that can be taken closer to production, do I need the arduino? Seems like the Arduino is only adding a small amount of value in interpreting the message from phone and transmitting the reading
2. If I don't need Arduino, how do I program the BLE chip (Nordic nRF8001) directly? I have seen some kits on the internet and they all seem much more complex than programming Arduino.

I am a newbie to H/W - deep background in S/W engineering - but definitely motivated and interesting in making my project a reality. Advice and guidance are appreicated.

# Answer
The nRF8001 can not run custom code, so you need an external microcontroller to use it. However, the nrf5 series (for example nrf51822) has a microcontroller and can run custom code.

Nrf5 is Arduino compatible thanks to sandeepmistry's nrf5 arduino core.

You will need a programmer though, since the nrf51822 uses swd programming. References to recommended programmers are available here.
> 1 votes

---
Tags: arduino-uno, bluetooth
---


title: HD44780 Extended non-display DDRAM?

text:
# Question
Title: HD44780 Extended non-display DDRAM?
According to page 10 of this PDF https://www.sparkfun.com/datasheets/LCD/HD44780.pdf

The HD44780 has enough DDRAM to operate an 80 character display. A 16x2 display has 32 characters meaning we have 48 characters of free DDRAM. Is there anything in the Arduino's LiquidCrystal library which allows direct access to this DDRAM space? The HD44780 datasheet says it can be used as generalised RAM.

# Answer
> 1 votes
I haven't used that particular library but I have used the ddram and cgram as memory / buffets. So the feasibility is never in question.

The downside with this approach is speed and real estate. Those devices are slow by mcu standard. You then have to provision for the rw pin and the data pins - both read and writes. That's what you should check for in the library.

But it is workable for sure.

---
Tags: lcd, display
---


# Question
Title: ADXL345 hangs the micro-controller as vibrations increase
I am using ADXL345 accelerometer with Adafruit\_ADXL345 library for vibration measurement.

I am reading acceleration at X, Y, Z-axis of a sensor placed on a vibrating platform.And serially sending it to PC at a baud rate of 115200.

When vibration is low sensor shows vibrations but as i increase the vibrations serial transmission seems to be halted. As shown in figure:(x-axis=Samples y-axis=Values )

I thought it may be due to loose connections so I soldered its terminals but it behaved the same way at higher vibrations. Here is the code that I’m using.

```
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345_U.h>
/* Assign a unique ID to this sensor at the same time */

Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12);
int i=0;
struct measure
{
    int timestamp;
    float x;  // ACC in x direction
    float y;  //ACC in y direction
    float z;  //ACC in z direction
};
sensors_event_t event;
struct measure measurements;

int timestamp = 0;

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

  Serial.println("Accelerometer Test"); Serial.println("");

  /* Initialise the sensor */
  if(!accel.begin())
  {
    /* There was a problem detecting the ADXL345 ... check your connections */
    Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
    while(1);
  }
  accel.setDataRate(ADXL345_DATARATE_3200_HZ);
  accel.setRange(ADXL345_RANGE_16_G);
     pinMode(LED_BUILTIN, OUTPUT);
  delay(2000);
}

void loop(){

 accel.getEvent(&event);
   measurements.timestamp = timestamp++;
   measurements.x  = event.acceleration.x;
   measurements.y  = event.acceleration.y;
   measurements.z  = event.acceleration.z;

if(measurements.timestamp%2==0)
  digitalWrite(LED_BUILTIN, HIGH);
  else
    digitalWrite(LED_BUILTIN, LOW);

  /* Sending the array with data through serial*/

  Serial.print(measurements.timestamp);
 Serial.print(",");
 Serial.print(measurements.x+0.06);
 Serial.print(",");
 Serial.print(measurements.y+0.7);
 Serial.print(",");
 Serial.println(measurements.z-10.10);
}

```

Where does problem lie? How to resolve this issue?

Circuit Connections:

# Answer
> 1 votes
There is a known issue with the default "Wire" library, where if a certain transition is missed, the code goes into an infinite loop (rather than timing out). You possibly are reaching that situation. A possible reason is your printing of numbers at quite a high baud rate. The printing could be taking up so much time (itself causing serial interrupts as the serial buffer empties) that the I2C code doesn't execute in time the I2C interrupt.

You could try dropping the printing baud rate (something I wouldn't normally recommend) which means the serial interrupts would occur less frequently.

There is a library by DSS Circuits that has a time-out for I2C which may work around this issue to an extent:

http://dsscircuits.com/articles/arduino-i2c-master-library

Another thing you could try would be to summarize the data (eg. sample for 500 ms and then send the average), which would reduce the amount of serial comms.

---

Also you might try lower values for the pull-up resistors, like 4.7k.

---

So, my recommendations are:

* Drop the baud rate (eg. to 9600 baud) and see if the hanging goes away
* Summarize data rather than sending each reading
* Try 4.7k pull-up resistors

If you have a logic analyzer you could look at the I2C signals and see if you can work out if the data is being transmitted as expected when the vibrations occur.

Saleae sell logic analyzers, the cheapest being $US 109. I use their (more expensive) analyzers extensively for debugging this sort of thing.

---
Tags: accelerometer
---


# Question
Title: How do I program the Arduino Primo Core using the Arduino Primo?
the Arduino Primo Core website (https://store.arduino.cc/usa/arduino-primo-core) says that I can program the Arduino Primo Core using an Arduino Primo.

I have no idea how to do this!

Can you do it through the Arduino IDE? Which pins on the Arduino Primo Core should I connect to which pins on the Arduino Primo?

Thanks for your help!

# Answer
instructions were on arduino.org. it is turned off now, but you can find them in Web Archive (without downloads) Arduino.org pages in web archive
> 1 votes

# Answer
Juraj's answer answered my question, however I've gone back since and found the link to be broken. Fortunately I saved the file so I'll summarise here for others:

1. Download the nRF52 platform using the Boards Manager:

2. Connect the Arduino Primo Core to the Arduino Primo using a SWD connector (J2 on Arduino Primo Core and J9 on the Arduino Primo):

3. Plug the Arduino Primo into the PC using a USB data cable.
4. Select "Arduino Primo Core" from the `Tools > Board` menu:

5. Select the corresponding port of the Arduino Primo from the `Tools > Port` menu:

6. Select the `Blink` sketch from the `File > Examples > 1. Basics` menu.
7. Upload the sketch. If the light blinks on the Arduino Primo Core it has worked!
> 0 votes

---
Tags: uploading
---