title: Number of elements in an array char

text:
# Question
Title: Number of elements in an array char
What kind of function can I use to know how many elements are in an array char?

sizeof() gives the number of 'spaces' available so it doesn't work for me.

# Answer
You want `strlen`.

```
char foo [100] = "bar";
Serial.println (strlen (foo));   // --> prints 3

```
> 11 votes

# Answer
I know you have your answer from @NickGammon, but I'd just like to add a bit more in-depth information about how all this works.

`sizeof()` is not a function in the normal sense of the word. It is an operator which gives you the number of bytes of memory allocated to whatever you pass to it. If you pass it an array then it returns the number of bytes that array has available to it. If you pass it a pointer to an array then it returns the size of that pointer, not the size of the array. If you pass it an integer variable it returns the number of bytes used by that integer variable (2 on an 8-bit system like AVR, 4 on a 32-bit system like the Due).

So some examples:

```
char array[50] = "hello";
// sizeof(array) = 50.
char *array_p = array;
// sizeof(array_p) = 2 or 4 depending on architecture.
char single = 'a';
// sizeof(single) = 1.
char string[] = "hello";
// sizeof(string) = 6 (5 letters plus \0) - it allocates the memory at compile time to fit the string

```

Now `strlen()`. How exactly does that differ from `sizeof()`? Simply put, `strlen()` counts the number of characters in a character array up until it reaches the character `\0` which is the "NULL" terminating character of a C string. Let's take the examples before but use strlen instead:

```
char array[50] = "hello";
// strlen(array) = 5.
char *array_p = array;
// strlen(array_p) = 5.
char single = 'a';
// strlen(single) = ERROR!  strlen() doesn't operate on single characters.
char string[] = "hello";
// strlen(string) = 5.

```

You notice it always returns the number of characters in the string up to, but not including, the trailing `\0` character.

In its simplest form the `strlen()` function might look like this:

```
int strlen(const char *data) {
    int c = 0;
    const char *p = data;
    while (*p) {
        c++;
        p++;
    }
    return c;
}

```

Basically it starts at the first character in the string (`*p = data`), examines if it's a `\0` or not (`while (*p)`), increments the count of characters (`c++`) and moves on to the next character in the string (`p++`).

If you want to iterate through your string in your program you could call `strlen()` first to get the number of characters in the string then use that value in a loop. That is a bit wasteful, since `strlen()` first iterates through the string, so you end up iterating through it twice. It is far more efficient to learn how best to step through each character in the string until you find the terminating character, such as how the `strlen()` function uses the *pointer* to move through memory. You can also see just how vital it is that you ensure the `\0` character exists at the end of the string, otherwise how will functions like `strlen()` know when to stop? They can't know how long the string is (`sizeof()` will return the size of the pointer it is passed, not the size of the array), so they have to have some kind of manual marker, and the convention in C is to use `\0`.

Note that Arduino's `print()` functions actually do it very inefficiently. If you do something like:

```
char message[] = "Hello";
Serial.println(message);

```

It will actually do quite a lot of work it doesn't *really* need to. Taken step by step it:

1. calls println(message)
2. which calls write(message)
3. which gets the string length with strlen(message)
4. and calls write(message, length)
5. which then loops from 0 to length-1 sending each character of message to write() in turn.
6. finally prints the `\r\n` for the new-line.

So it actually ends nested around 4 functions deep, and iterates the entire string twice. A classic example of how to waste processing time. By iterating through the string once looking for the `\0` character in the `write(message)` function (step 2) it would operate at least twice as fast. Good old Arduino...
> 3 votes

---
Tags: arduino-ide, c, strlen
---


title: LiquidCrystal_i2c and Pin 2

text:
# Question
Title: LiquidCrystal_i2c and Pin 2
I'm trying to read temperature and humidity from a DHT11 sensor and write values to a 20x4 LCD. I hit a behaviour I don't understand. When I use the DHT tester program that come with the DHT library, everything works well. I get the DHT information on the Serial console. This DHT tester program use the pin 2 to read the data from the DHT.

I wrote the following code who works perfectly:

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>  // F Malpartida's NewLiquidCrystal library
#include <DHT.h>

#define DHTTYPE DHT11
#define DHTPIN 13      // Digital

DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C    lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

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

  dht.begin();
  lcd.begin(20,4);
  lcd.setBacklight(0);
  lcd.clear();
  lcd.print("Hello! ");

  Serial.println("Init finished!");
}

void loop() {
  delay(2000);

  float DHT_hum = dht.readHumidity();
  float DHT_temp_c = dht.readTemperature(false);
  float DHT_temp_f = dht.readTemperature(true);

  if (isnan(DHT_hum) || isnan(DHT_temp_c) || isnan(DHT_temp_f)) {
    Serial.println("Failed to read from DHT sensor!!");
    lcd.clear();
    lcd.print("fail! ");
    return;
  }

  float heat_index = dht.computeHeatIndex(DHT_temp_f, DHT_hum);

  Serial.print("Humidity: ");
  Serial.print(DHT_hum);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(DHT_temp_c);
  Serial.print(" *C ");
  Serial.print(DHT_temp_f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(heat_index);
  Serial.println(" *F");

  lcd.clear();
  lcd.print("Humi: ");
  lcd.print(DHT_hum);
  lcd.print("%");
  lcd.setCursor(0, 1);
  lcd.print("Temp: ");
  lcd.print(DHT_temp_c);
  lcd.print("C");
  lcd.setCursor(14, 0);
  lcd.print("HI: ");
  lcd.setCursor(14, 1);
  lcd.print(dht.convertFtoC(heat_index));
  lcd.print("C");

}

```

As you can see, I use pin 13 for the DHT11 (DHTPIN). If I set to it to "2" then my program is no longer working (having the pin connected or not doesn't change the result). The serial display

```
Serial OK!
Init finished!
Failed to read from DHT sensor!!

```

and that's all, it even doesn't loop to display "Failed to read from DHT sensor!!" again. LCD text doesn't change too. Like if the program is totally exiting after "Serial.println("Failed to read from DHT sensor!!");"

I'm lost... The LCD lib I use is the very common one from fm https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home

# Answer
> 0 votes
I'm self answering.. On my Arduino Leonardo, the SDA and SCL pin used for the I2C connexion to the LCD panel, are the same pin than the Digital pin 2 and 3. So using SDA/SCL remove ability to use pin 2 & 3.

# Answer
> 0 votes
```
LiquidCrystal_I2C    lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

```

~~Are you not using pin 2 in the LiquidCrystal\_I2C constructor? So you can't also use it for the DHT sensor.~~

---

I withdraw that suggestion.

---

Can you please try saving some RAM?

Use the F macro with your prints, eg.

```
  Serial.print(F("Humidity: "));
  Serial.print(DHT_hum);
  Serial.print(F(" %\t"));
  Serial.print(F("Temperature: "));

```

Ditto with the `lcd.print()` calls.

---
Tags: lcd
---


title: Blutooth shield LED control

text:
# Question
Title: Blutooth shield LED control
I am trying to control a led ON/OFF using Arduino UNO and a Bluetooth shield

I have this

which is based on hc-05. The tutorials I found about hc-05 are not working for me. I have the hc-05 embedded in the shield and I did not find any tutorials for this shield.

Here is my code (it is working when I use the USB serial ctrl + shift + m).

```
void setup () {
pinMode( 13, OUTPUT );
digitalWrite(13,LOW);

Serial.begin( 9600 );
Serial.println( "Ready" );
}

void loop() {
if ( Serial.available() > 0) {
    int inByte = Serial.read();

    switch ( inByte ) {

        case '0':
            digitalWrite( 13, LOW );
        break;

        case '1':
            digitalWrite( 13, HIGH );
        break;

    }
 }
}

```

I connected my android phone to the shield successfully using blurterm2. When I send 1 or 0 nothing happens. What am I missing?

# Answer
> 1 votes
Have you tried the turning just running a simple program to check if the led still works, such as

```
void setup () {
pinMode( 13, OUTPUT );
}
void loop() {
 digitalWrite( 13, HIGH );
 delay(1000);
 digitalWrite(13,LOW);
 delay(1000);
}

```

# Answer
> 1 votes
From your code I cannot see anything that actually initializes the shield and tells it what pins to use and how to use them. This github (https://github.com/jdunmire/HC05) has a library for the HC-05 shield and it appears to have instructions for setting baud rate and all of that good stuff.

Also, their read-me mentions that, if properly configured, you should see traffic to and from the shield in your serial monitor. Are you seeing any traffic?

NOTE: This tutorial (http://www.instructables.com/id/Arduino-AND-Bluetooth-HC-05-Connecting-easily/?ALLSTEPS) seems to have step by step instructions to do exactly what you are asking.

# Answer
> 0 votes
You should use a **different baud rate** if your hc-05 does not work with the code. The default is 9600. Use this baud rate and if not, try to find out the baud rate using AT commands, you will get several tutorials on this.

# Answer
> 0 votes
Here is your problem:

```
if ( Serial.available() > 0) {
int inByte = Serial.read();

```

You are not listening to the bluetooth-hardware, but to the build-in serial port of the Arduino.

I had a look at the url you can see on the board, but i could not find any example code. If you are lucky your bluetooth should might be compatible with the freetronics bluetooth shield, which has some example code on the bottom of this page to get you started:

```
#include <SoftwareSerial.h>

SoftwareSerial bt(2,3); // RX, TX

int thisByte = 33;

void setup() {
  bt.begin(9600);
  bt.println("ASCII Table ~ Character Map");
}

void loop() {
  bt.write(thisByte);

  bt.print(", dec: ");
  bt.print(thisByte);
  bt.print(", hex: ");
  bt.print(thisByte, HEX);
  bt.print(", oct: ");
  bt.print(thisByte, OCT);
  bt.print(", bin: ");
  bt.println(thisByte, BIN);

  if(thisByte == 126) {
    thisByte = 32;
  }
  thisByte++;
}

```

This only sends, and "bt" is your bluetooth hardware here. It behaves like the Serial hardware for the most part.

Note: based on your picture, you might have to change the RX/TX pins on your board to 2,3 - currently they are set to 2,4.

---
Tags: arduino-uno, serial, led, bluetooth
---


# Question
Title: Separate ATmega 2560 - turn on a single LED - troubleshooting
I have got my own PCB with "some stuff" on it and first I want to make it run a simple "turn on LED".

My setup:

* Atmega 2560
* LED connected to PE4 (D2 in Arduino language) =\> PE4 - LED - 1K resistor - 5V
* ceramic resonator (CSTCE16M0V53-R0 16MHZ) connected to XTAL1 + XTAL2 with 1MOhm resistor in between
* all VINs are pulled to GND with capacitors

Upload is working through ICSP (MISO, MOSI, SCK, RESET, 5V, GND) with an USBasp

Here is my **Arduino sketch**, which I upload through the Arduino software:

```
void setup() {
  pinMode(2, OUTPUT);
}

void loop() {
  digitalWrite(2, LOW);
}

```

I checked the fuses on the Atmega as well:

```
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D8
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (H:FD, E:D8, L:FF)

```

avrdude uploads successfully: *(output truncated!)*

```
avrdude: auto set sck period (because given equals null)
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.01s
avrdude: Device signature = 0x1e9801
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: auto set sck period (because given equals null)
avrdude: writing flash (1518 bytes):
Writing | ################################################## | 100% 5.47s
avrdude: 1518 bytes of flash written
avrdude: reading on-chip flash data:
Reading | ################################################## | 100% 3.45s
avrdude: verifying ...
avrdude: 1518 bytes of flash verified

avrdude done.  Thank you.

```

Problem: the LED doesn't work. It is OFF all the time.

Any ideas why it is not working?

# Answer
You are saying that the LED lights if you write LOW to it.

> I need to pull the output pin to LOW to make the LED work

That's exactly what you expect.

Since the other end of the LED is wired to +5 V, then you need to drive the pin low to have a voltage difference over the LED, and for it to light.

---

> I double checked the Atmega and it is a ATmega2560V, which is rated for 8Mhz. Any chance to fix this with the existing PCB? Change the Fuses to use the internal clock?

Yes, I suggest you do that.

Look at Engbedded Atmel AVR® Fuse Calculator to see what to set them to. I suggest the internal 8 MHz oscillator.
> 0 votes

---
Tags: programming, led, uploading, sketch
---


# Question
Title: Compatibility between Arduino and Arduino clones
In a project I am using a Seeeduino v3.0 as an Arduino clone. On the seeeduino website it says that

> It is based on the Duemilanove schematic, 100% compatible to its existing program, shield and IDEs.

In fact I never had any problems with shields or the IDE.

My question is now: Is the seeeduino and other clones really 100% compatible? The seeeduino board was considerable cheaper then an arduino.

# Answer
> 16 votes
Over the years I have used original Arduino boards as well as a multitude of clones of varying provenance, from the excellent InduinoX that is listed on the Arduino site as an official compatible board, to the very well-made Chinese Meduino Nano Enhancement (3.3 / 5 Volt switchable), to dirt-cheap clones from eBay that are sometimes better constructed than the official boards.

There is nothing unique or sophisticated about the Arduino board: It's basically just the microcontroller (atMEGA328, atMEGA1280, SAM3X8E or others) and its minimal support hardware. Not much that can go wrong with that little, really.

The two common elements that ensure compatibility across these boards are:

1. The Arduino bootloader
2. Support for the board within the official Arduino software distribution

The bootloader can be replaced with a better or more up-to-date version if one is available for the microcontroller on your board.

The support files can either be found online, or minor edits to the nearest similar board's files can provide the requisite support for the Arduino environment.

In short: *Yes, clones typically work just as well as the original Arduino, and clones with enhanced features often work far better while retaining compatibility (e.g. InduinoX)*

# Answer
> 5 votes
If you closely look at the Arduino circuit diagram, You'll notice that it is little more than power supply, a USB-serial interface and the microcontroller itself.

The 'hard' part for compatibility is getting the board layout right (which connector goes where on the circuit board), and to load a compatible bootloader in the chip (which is free/open software, so why bother making your own?).

I've used several el-cheapo Arduino clones and apart from apparent physical construction (one feels a bit flimsy), they all work just like the 'real thing'. I guess the major difference between original and clone is the quality of the board, the used components and quality of assembly.

# Answer
> 3 votes
Check twice !

Most clones are exact clones with copies of the flaws that original Arduino board had. Like for example Arduino Nano not having proper RESET and TEST pin connection of FT232RL USB-serial bridge. This flaw may lead to FT232RL not responding to PC and was eventually fixed in later revisions of Arduino Nano board. Some clones were not updated.

Another "not exactly Arduino clones" example are numerous boards with CP2102 USB to serial bridge instead of FT232RL. This may pass unnoticed, but may give frustration when one clone board connects and works with your PC, but another generates system complains on missing drivers.

So again - be prepared !

# Answer
> 1 votes
I have found that most clones will do what you expect them to do, but as x4mer states in his answer, be prepared.

The most annoying issue, and even then it *is* quite minor, is that a lot of Chinese clones do not use an ATMega for the USB and instead use a **CH340G**. These chips, while fine when connecting to a PC running Windows 7, have great difficulties with the drivers on OS X, and end up just not being recognised. It is possible to find a driver for the CH340G, but when I installed it, it immediately crashed the MacBook, upon plugging in the cloned UNO..!

I had to buy three or four clones on eBay until I got an Uno with an *actual* 16u2 implementing the USB interface, which would actually be recognised by the MacBook Pro, and would allow me to code using the Arduino IDE running on OS X.

Before that, I had to use a Wintel laptop.

---
Tags: clones
---


# Question
Title: Read an analog signal without changing it? Or should I start over?
Hi! I'm still working on my kettle project. I want to obtain the kettle temp from the existing thermometer. I'm able to do this, but much like trying to look at an electron my circuits all reduce the voltage going to the kettle control board. This means the kettle's microcontroller (SN8P2722 SONiX) acts as if the kettle is cooler than it really is.

I don't think there is an *easy* way to program this microcontroller (if there is I'd love to know) -- I suspect the bad temp data will lead to overheating and hot water all over my kitchen.

Is there any way to passively obtain the voltage? I've been looking into the way that voltmeters work. Is this the right idea? is there a breakout board for this?

I really wanted to have the existing buttons still work as they always have. I've done this with power. I can press it remotely or on the kettle and I can tell of the kettle is on or off both on the control panel and remotely.

I can press all the other buttons remotely but I can't tell if it's working without knowing the kettle temp.

Maybe I should try to replace the entire control board? What would be easier? I'm something of a beginner.

# Answer
> 3 votes
A JFET op amp such as the TL071 has an input impedance in the hundreds of gigaohms or higher. Using one to buffer the voltage should allow you to sample it without much interference to the existing circuit.

---
Tags: analogread, project-critique
---


title: Arduino code cannot continute process

text:
# Question
Title: Arduino code cannot continute process
Two days ago, my code is working fine on the arduino board. But yesterday, and today I tried so many time to upload the arduino code, which contains 1000 lines of code. It was successfully uploaded the code into arduino. But it only upload half code into arduino when I saw the serial monitor results (I use serial println(); test where the code is located. ) I am so confusing, why the code is working fine two days ago. but later, only half code being used. Please help.

Here is the memory I left when I uploaded it.

Sketch uses 48,314 bytes (19%) of program storage space. Maximum is 253,952 bytes. Global variables use 2,603 bytes (31%) of dynamic memory, leaving 5,589 bytes for local variables. Maximum is 8,192 bytes.

```
Here is the code it stuck :
   Get Parameters
//
//  This function reads the information from the SD card for a given monitoring
//  site.
//

```

//

```
int getParameters(){
  String lowerLimit, upperLimit;

   char buffer[36];
  char newChar;
  int index, index1, index2, index3, line, theLength, numSensors;
  myFile.setTimeout(2000);
  line = 0;
  while (myFile.available()) {
    index = 0;
    do{
      newChar = myFile.read();
      buffer[index] = newChar;
      index += 1;
    }
    while(newChar != 10);
    buffer[index] = 0;
    theLines[line] = buffer;
    Serial.print(theLines[line]);
    //here the result is something like this
    //theLines[0] , class 111
    //theLines[1] , 192.168.1.10
    //theLines[2] , Mac Address

    line += 1;
  }

//so it is working fine above the code. But here is the problem stuck.
//the code cannot go through the rest of the code below. Nothing happened!!!
  for (int line = 0; line < 10; line++){
    Serial.print(theLines[line]);

  }

```

# Answer
> 0 votes
A portion of your code is shown below.

```
  myFile.setTimeout(2000);
  ....
  while (myFile.available()) {
    index = 0;
    do {
      newChar = myFile.read();
      buffer[index] = newChar;
      index += 1;
    } while(newChar != 10);
   ....
  }

```

Apparently your code is accepting and printing several lines of option setting text and then hangs up in the code extract shown above.

Suppose, for example, one extra character appears after the supposedly-last linefeed character. Your `while (myFile.available())` loop will run again. It will store the extra character, then try to read another character. If another character isn't available, `newChar = myFile.read();` will return a -1 that your code will store. That will happen repeatedly, clobbering RAM.

To see if this is what's happening, you could change `while(newChar != 10);` to (eg) `while(newChar != 10 && index<36);`. If the code then stops hanging up, look into where the extra character is coming from.

---
Tags: arduino-mega
---


# Question
Title: How does one design for the power on transient conditions?
Following on from the question Reset an Arduino UNO by an command (software) and the excellent answer provided by mpflaga, the comment addressing option (1) suggests that there are design considerations for connecting an output pin to the RESET pin.

> Option 1. or a variant can be a clean enough way to do this as long as power on transient conditions are designed for. \- Russell McMahon

or more ominuously

> From everything I've read, the first option is not recommended. - sachleen

Could someone tell me exactly what those considerations are? Is it that it is not as simple as connecting the two with a jumper cable - is additional circuitry (i.e. an RC timer) required, or is there a software solution?

I find the latter option unlikely as the device is rebooting, so unless the software fix is to ignore hardware interrupts (since a RESET is simply that, and the state of the output pins is unlikely to be known, or stable at reboot) for a few mS after reboot, I presume that a hardware fix is required.

# Answer
> 7 votes
Atmel specifically recommend against driving /RESET low from an output pin, because the first thing that the reset process does is set all pins to high impedance, thus cancelling the reset pulse before the recommended reset pulse length has elapsed.

The recommended use of the watchdog timer does not suffer from these limitations. It is *designed* to reset the board (or there would be no purpose to having it) and it does a proper reset (unlike jumping to address 0x0000).

---

### Reference

Atmel knowledge base - Software Reset

> If you want to perform a software reset of your AVR you should use the internal Watchdog. Simply enable it and let it time out. When the Watchdog triggers it resets the program counter back to 0, clears all the registers and performs all the other tasks. This operation gives the same result as pulling the RESET line low.
>
> You should not try to:
>
> * Use another pin of the AVR to pull the external RESET line. The pins of the AVR are tristated halfway through the minimum reset time, this releases the RESET line and hence nothing happens.
> * Jump to program location 0. Jumping to program location 0 does not clear all the registers and hence you do not have a "clean" reset.

---

Their suggested code to reset the processor:

```
#include <avr/io.h>
#include <avr/wdt.h>

#define Reset_AVR() wdt_enable(WDTO_30MS); while(1) {}

int main(void)
{
Reset_AVR();
}

```

---
Tags: arduino-uno, reset
---


# Question
Title: Arduino Mega PWM pins stop working for LEDs once servo is attached?
I can get LEDs to fade properly using PWM on pins 44-46 on the Mega2560 when I don't have a servo attached, but once I "attach" the servo in the code, then PWM pins 44-46 don't work for PWM. They can still work with digitalWrite, but not with analogWrite.

This is the code:

```
#include <Servo.h>
Servo myservo;
int led = 46;

void setup()  {
  myservo.attach(3);
  pinMode(led, OUTPUT);
  analogWrite(led, 60);
}

void loop()  {}

```

If I comment out the "myservo.attach(3);" line, then PWM works for the LED pin. Otherwise the LED stays off. Why would PWM on pins 44-46 stop working once the servo is attached?

# Answer
> 3 votes
Looks like the mega has some clever servo handling features. Servo control always uses a timer of some sort and can conflict with the pwm timer. The first 12 servos knock out pins 44,45,46 ...

> For Arduino Mega it is a bit more difficult. The timer needed depends on the number of servos. Each timer can handle 12 servos. For the first 12 servos timer 5 will be used (losing PWM on Pin 44,45,46). For 24 Servos timer 5 and 1 will be used (losing PWM on Pin 11,12,44,45,46).. For 36 servos timer 5, 1 and 3 will be used (losing PWM on Pin 2,3,5,11,12,44,45,46).. For 48 servos all 16bit timers 5,1,3 and 4 will be used (losing all PWM pins).

---
Tags: arduino-mega, pwm, servo
---


# Question
Title: Implementing DES or AES Encryption with DateTime Synchronization on Uno
We are trying to implement AES or DES encryption using an Arduino Uno.

We have a keypad module attached that will be used to input integers. A String should be generated based on the entered data and encrypted using AES or DES.

We have tried several online libraries with no success due to the constraints put on the "plain text" size.

An example pseudo-code for the above:

```
string key = "This is a key";
string plain = "This is the keypad input" + keypadInput + "and some other random stuff"; <- This should have any size.

var cipher = AES.encode(plain, key);
print(cipher);

var decoded = AES.decode(cipher, key);
print(decoded);

```

Could someone please point to the right direction on how to do this?

# Answer
> We have no experience with the byte\[\] objects and whatnot.

Might be time to do a few tutorials. You won't get far programming if you don't learn how to use arrays.

The **string** class is part of the STL (Standard Template Library) which does not come pre-installed on the Arduino (however you can download it if you want to).

The Standard Template Library (STL) for AVR with C++ streams

---

Briefly, however you could do something like this:

```
char key [20] = "This is a key";
char keypadInput [16];  // whatever they entered

char plain[80];

strcpy (plain, "This is the keypad input");
strcat (plain, keypadInput);
strcat (plain, "and some other random stuff");

```

The example code doesn't have any size checking. You would want to make sure that you don't put more than 79 characters into "plain" (to allow for the terminating 0x00 character). For example, look up **strncat**.

---

> Can you please elaborate on how DES or AES as described in the question can be implemented?

Have you done much research? Have you Googled `Arduino AES encryption` like I just did? I got this as the first hit:

Topic: new AES library - Arduino Forum

> I've written an AES (Advanced Encryption Standard) library for Arduino. It supports 128, 192 and 256 bit key sizes. Code space overhead is about 4KB I think, each instance requires 240 bytes RAM for subkeys. Fairly tightly coded and checked against official test vectors for ECB mode. Also CBC mode supported.

---

> It seems that if value of plain is larger than 16 characters the library will encrypt the first 16 characters only... Is this an Arduino Uno limitation?

I don't want to seem unhelpful, but you really should do some research before asking these questions. From Wikipedia - Advanced Encryption Standard (AES):

> AES is a variant of Rijndael which has a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits.

A "fixed block size of 128 bits" means you encrypt 128 bits at a time, that is, `128/8 = 16 bytes`.

So no, it is not an Arduino Uno limitation, it is the way AES works.

---

Also see Wikipedia - DES.

> In the case of DES, the block size is 64 bits.

So DES does 8 bytes at a time.

---

What you can do with a password is to **hash** it, for example: Secure Hash Algorithm or MD5 (amongst others). These algorithms take a variable length string and return a fixed "hash". In the case of MD5 the output is a 128-bit field.

You could then encrypt that 128-bit hash, if you want to keep it a secret.

---

> Would encrypting the 16 bytes and then append the next 16 bytes and so on result to the same output as if the whole plain text was encrypted in the first place in one go?

The suggestion by @BrettAM was, if you want to encrypt more than 16 bytes, do them 16 bytes at a time, padding if necessary the final block.

eg.

```
AAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBB CCCCCCCCCC000000
      encrypt        encrypt          encrypt
LLLLLLLLLLLLLLLL MMMMMMMMMMMMMMMM NNNNNNNNNNNNNNNN
      decrypt        decrypt          decrypt
AAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBB CCCCCCCCCC000000

```

In this example the final block was padded with zeros. Now the receiving end decrypts in 16-byte blocks.
> 4 votes

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


title: Empty char variable

text:
# Question
Title: Empty char variable
How do I empty all the values inside a variable `char array[256];`?

I tried a for loop assigning an empty value at each iteration, but it doesn't compile.

# Answer
```
char array[256];

...

int i;
for( i=0; i<256;i++ ) {
    array[i] = 0x00;
}

```
> 1 votes

# Answer
There is a single-line command you can use:

```
memset(array, 0, 256);

```
> 2 votes

---
Tags: programming, arduino-ide, c, sketch
---


title: Two motors in one set of pins/plugs

text:
# Question
Title: Two motors in one set of pins/plugs
I have been putting together a small robot using an Arduino Motor Shield R3. The shield has two sockets for motors, however the wheel carriage I bought has four motors. I tried putting both right side motors in one socket set, and the left side motors in the other socket set.

When I turn on the Arduino, the left side motors turn together according to how I coded the board, however the right side behaves differently.

One of the motors does not start. If I push it a little it will start turning. Though not always. When I plugged in the misbehaving motor by itself, it runs correctly.

I am wondering about cause of the problem here. Is it likely the second motor on the right side is faulty? Or am I trying to use up too much power and disrupting the current?

# Answer
> 1 votes
The drive capacity of the Motor Shield should match the motors – two of the motors. The shield was probably designed for a load of one motor, and you're giving two, so it is possible that neither of the motors on that side is getting enough current to get started. Here are somethings to check to get started:

1. Find the drive capacity of the Motor Shield and compare it to the motors (if you don't have specs for the motors you could measure the current they draw if you have an DMM). It might be wise to measure the current anyway, just in case you have a defective motor or shield.
2. If the capacity or the current draw is out of line, that's your problem. You can probably just add a power transistor to the circuit to drive the motors in this case.
3. Try it with just one motor on each output and see if they run normally. If they do, that would suggest a loading problem or a defective motor or shield. You can sort out which is which by swapping sides – if one motor runs and the other doesn't, swap them. If the problem follows the motor, then blame the motor, otherwise blame the shield.

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


# Question
Title: Console monitor on different wifi network
I have a Yun doing data logging. It runs nicely and when I am on the same wifi network I can use the Console Monitor to watch what it is doing in more detail. However, my arduino is deployed far from me so it generally isn't possible to get on the same wifi network to monitor the console.

Is there a way to monitor the console from a different wifi network?

# Answer
The Yun is just an ordinary network device. However, the tools you are provided with use a system called mDNS to find the Yun. That only works across the same local subnet that you are on.

If the Yun is on a different subnet then you will have to (assuming the routing between subnets is working fine) do it manually by knowing the IP address of your Yun. Use that IP address in place of "arduino.local" or whatever your Yun is called.
> 1 votes

---
Tags: arduino-yun
---


# Question
Title: Issue with time-dependant conditional I/O control flow (Arduino UNO)
We are working on a project to control the reaction of a system to a lever, whose position is monitored by two IR sensors at the ends of its travel, the Reward sensor and the Trigger sensor.

There are three modes of action:

Mode1: lever has to start at TriggerSensor, and a success is recorded if and when the lever is moved to RewardSensor

Mode2: lever starts at TriggerSensor and has to be held for 4 seconds. At the end of this interval a tone is played for 2 seconds, the reward interval. Within this 2 seconds, if the lever is moved to the RewardSensor, a success is recorded.

Mode3: same as Mode2, but the initial 4 second timeout is of random length.

We also want to use the following lines:

`digitalWrite(TriggerSensorOut, digitalRead(TriggerSensorIn)); //This is to record to our computer the states of the trigger sensor
 digitalWrite(RewardSensorOut, digitalRead(RewardSensorIn)); //This is to record to our computer the states of the reward sensor`

to constantly write the state of both sensors to our computer. However, this doesn't work as planned: there are delays between the execution of the mode functions (as described in full code below).Essentially, we are struggling to come up with a suitable way to time things correctly.

Please see full code below

```
// -----LIBRARIES

//#include <elapsedMillis.h>

// ----CONSTANTS (won't change)

const int TriggerSensorIn = 2;   //  Input from trigger sensor, LOW = broken
const int RewardSensorIn = 3;    //  Input from reward sensor, LOW = broken
const int ModeStateIn1 = 4;      //  Input 1 from switch to define paradigm mode
const int ModeStateIn2 = 5;      //  Input 2 from switch to define paradigm mode
const int RewardSignalOut = 12;   //  Output signal of reward, parallel taken off to counter module
const int ServoResetOut = 6;     //  Servo reset output signal
const int ToneOut = 10;          //  Audio stimulus
const int TriggerSensorOut = 7;  //  Output from trigger sensor for DAC board recording
const int RewardSensorOut = 8;   //  Output from reward sensor for DAC board recording

//------- VARIABLES (will change)

boolean backPressed = false;

int timeoutWindow = 4000;    // 4 second preliminary interval
int rewardWindow = 2000;    // 2 second reward interval

unsigned long currentMillis = 0;

//===============

void setup() {

  // initialise the digital pins as inputs and outputs

  pinMode(TriggerSensorIn, INPUT);
  pinMode(RewardSensorIn, INPUT);
  pinMode(ModeStateIn1, INPUT);
  pinMode(ModeStateIn2, INPUT);

  pinMode(RewardSignalOut, OUTPUT);
  pinMode(ServoResetOut, OUTPUT);
  pinMode(ToneOut, OUTPUT);
  pinMode(TriggerSensorOut, OUTPUT);
  pinMode(RewardSensorOut, OUTPUT);

}

//===============

void giveReward() {
  // This function is the protocol for recording a reward
  currentMillis=millis();
  digitalWrite(RewardSignalOut, HIGH);
  while (millis()>currentMillis+200) {
    digitalWrite(RewardSignalOut, LOW);
  }
}

//===============

void servoReset() {
  // This function is the protocol for resetting servos after a failed action
  currentMillis=millis();
  digitalWrite(ServoResetOut, HIGH);
  while (millis()>currentMillis+200) {
    digitalWrite(ServoResetOut, LOW);
  }
}

//===============

void mode1() {
  // This function is the protocol for controlling the system during mode 1, no time constraint on the action
  if (digitalRead(TriggerSensorIn == LOW)) {
    backPressed = true;

    if (backPressed == true && digitalRead(RewardSensorIn == LOW)) {
      giveReward();
      backPressed = false;
    }
  }
}

//===============

void mode2() {
  if (digitalRead(TriggerSensorIn == LOW)) {
    currentMillis=millis();
    while (digitalRead(TriggerSensorIn == LOW)) {
      while (millis() > currentMillis + timeoutWindow) {
        tone(ToneOut, 3000, 2000);
        {
          goto rewardSeeking2;
        }
      }
    }

rewardSeeking2:
    currentMillis=millis();  // reset timer
    if (millis() < (currentMillis + rewardWindow) && digitalRead(RewardSensorIn == LOW)) {
      giveReward();
    }
    else if (millis() > (currentMillis + rewardWindow)) {
      servoReset();
    }
  }
}

//===============

void mode3() {
  timeoutWindow=random(1000,5000);
  if (digitalRead(TriggerSensorIn == LOW)) {
    currentMillis=millis();
    while (digitalRead(TriggerSensorIn == LOW)) {
      while (millis() > currentMillis + timeoutWindow) {
        tone(ToneOut, 3000, 2000);
        {
          goto rewardSeeking3;
        }
      }
    }

rewardSeeking3:
    currentMillis=millis();  // reset timer
    if (millis() < (currentMillis + rewardWindow) && digitalRead(RewardSensorIn == LOW)) {
      giveReward();
    }
    else if (millis() > (currentMillis + rewardWindow)) {
      servoReset();
    }
  }
}

//===============

void loop() {

  digitalWrite(TriggerSensorOut, digitalRead(TriggerSensorIn));  //This is to record to our computer the states of the trigger sensor
  digitalWrite(RewardSensorOut, digitalRead(RewardSensorIn));  //This is to record to our computer the states of the reward sensor

  if (digitalRead(ModeStateIn1) == LOW && digitalRead(ModeStateIn2) == LOW) {
    // Using the two mode selective switches to define mode1
    mode1();
  }

  else if (digitalRead(ModeStateIn1) == LOW && digitalRead(ModeStateIn2) == HIGH) {
    // Using the two mode selective switches to define mode2
    mode2();
  }

  else if (digitalRead(ModeStateIn1) == HIGH && digitalRead(ModeStateIn2) == LOW)  {
    // Using the two mode selective switches to define mode3
    mode3();
  }
}

//===============END

```

# Answer
> 1 votes
This is a snippet of how I would refactor the code:

```
void mode3() {
  int timeout = millis() + random(1000,5000);
  while (digitalRead(TriggerSensorIn == LOW) &&
         millis() < timeout) {
  };
  if (digitalRead(TriggerSensorIn == LOW) &&
         millis() > timeout) {
     tone(ToneOut, 3000);
     timeout = millis() + rewardWindow;
     while (millis() < timeout)
       if (digitalRead(RewardSensorIn == LOW)
         giveReward();
  }
  noTone();
}

```

....

```
void loop() {
  // This is to record to our computer the states of
  // the trigger sensor
  digitalWrite(TriggerSensorOut, digitalRead(TriggerSensorIn));

  // This is to record to our computer the states of
  // the reward sensor
  digitalWrite(RewardSensorOut, digitalRead(RewardSensorIn));

  int msin1 = digitalRead(ModeStateIn1);
  int msin2 = digitalRead(ModeStateIn2);

  if (msin1 == LOW)
      if (msin2 == LOW)
          mode1();
      else
          mode2();
  else if (msin2 == LOW)
    mode3();
}

```

But I think you should first try to write it down in plain English and verify that at least that algo works. Then you can think how to transpose it into code.

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


title: TinyGPS (Plus) Library

text:
# Question
Title: TinyGPS (Plus) Library
Is there a particular function in the library TinyGPS or TinyGPS Plus which outputs the raw NMEA sentences? I couldn't find anything about it on the website guide of the library.

# Answer
There doesn't seem to be, but what you could do is print each character as it arrives. From their example code:

```
  while (nss.available())
  {
    if (gps.encode(nss.read()))    // <--- pass to TinyGPS
      return true;
  }

```

So, change that to be:

```
  while (nss.available())
  {
    char c = nss.read();  // <--- get the incoming character
    Serial.print (c);     // <--- print it
    if (gps.encode(c))    // <--- now pass it to TinyGPS
      return true;
  }

```
> 2 votes

---
Tags: arduino-ide, library, gps, tinygps
---


title: Quick Programming Check/Review

text:
# Question
Title: Quick Programming Check/Review
I've been racking my head trying to start programming in a library organized method. My code works, but the translation and split to a .h and .cpp file is riddled with errors.

It's gotta be stupidly simple all I'm asking for is a review:

Header File

```
# ifndef _INITIALIZE_H
#define _INITIALIZE_H

#if (ARDUINO >= 100)
# include <Arduino.h>
#else
# include <WProgram.h>
#endif

//-Extra Includes-
#include <config.h> //Provides baud...
#include <SSC32.h>

#define STANDARD 0
#define DEBUG    1
#define VIRTUAL  2

class Initialize {
    private:
        int _mode;
    public:
        Initialize();
        void begin();

};

#endif

```

associated .cpp file:

```
//Comments
#include <Initialize.h>
SSC32 SSC;

Initialize::Initialize()
{
    _mode = STANDARD;
}

void Initialize::begin()
{
    SSC.begin(baud);
    if(Serial.available() > 0){
        if(sscReturn == 1){
            Serial.println("ver");
        }
    }
}

```

The error from the compiler:

```
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp: In member function 'void Initialize::begin()':
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:12: error: expected primary-expression before '=' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:16: error: expected primary-expression before ')' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:16: error: expected ';' before ')' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:7: error: expected primary-expression before '=' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:7: error: expected ')' before ';' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:17: error: expected primary-expression before '==' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:21: error: expected ';' before ')' token
Failed compiling libraries

```

# Answer
Sorry, figured it out.

In the "config.h" file I was pulling, I had a `#define = 18;`

instead of a `#define 18`

I might be wrong, but the compiler stopped complaining
> -1 votes

---
Tags: programming, code-review
---


# Question
Title: Connect the Sparkfun CAN bus shield with an RFduino
I have a problem which I am working on for some days now. I do have knowledge in electronics, but not extensively. I also posted this question in the RFduino Forum but couldn't get any good answers.

What I am trying to do: I want to connect the Sparkfun CAN bus shield to the RFduino. I am using the code further below. It compiles without problem and **does work** with my Arduino Leonardo!

I used a logic analyser (ignore the filled shapes, some display error) to further narrow down the problem and found the following on the **RFduino**:

On the **Leonardo**, it looks different:

It seems like I don't get a response on the MISO line! I played around with different speeds, but nothing seemed to work.

I do have a suspicion however: The RFduino works with 3.3V, while the Leonardo works with 5V. So the logic signals on the RFduino can only achieve 3.3V P-P. I confirmed this with my old CRO, LOW is at GND and HIGH at 3.3V. The Leonardo has 5V P-P. On page 70 of the datasheet for the MCP2515 (the chip used on the shield), it says that the supply voltage VDD ranges from 2.7V to 5.5V. So supply voltage should be ok. V\_INPUT\_HIGH ranges from 2.31 to 4.3V. V\_INPUT\_LOW ranges from -0.3V to 0.495V. I am in this range! Similarly so for the V\_OUTPUT\_LOW (up to 0.6V) and V\_OUTPUT\_HIGH (at least 2.8V). Could this nevertheless be a problem?

What would you try or change?

MCP2515 Datasheet

```
#include <SPI.h>

// demo: CAN-BUS Shield, send data
#include <mcp_can.h>

MCP_CAN CAN0(SS);                                      // Set CS to pin 10

unsigned char stmp[8] = {0, 1, 0, 3, 0, 5, 0, 7};

void setup()
{
  Serial.begin(115200);
  while (!Serial) {
    ;                  // wait for serial port to connect. Needed for Leonardo only
  }
  // init can bus, baudrate: 500k
  if(CAN0.begin(CAN_500KBPS) == CAN_OK) Serial.print("can init ok!!\r\n");
  else Serial.print("Can init fail!!\r\n");
               // send data per 100ms
}

void loop()
{
//    // send data:  id = 0x00, standrad flame, data len = 8, stmp: data buf
//  CAN0.sendMsgBuf(0x00, 0, 8, stmp);
}

```

# Answer
Ok, I found the solution. The fix first: I had to **physically connect the reset line from the RFduino to the MCP2515 reset pin.** On page 55 in the datasheet of the MCP2515 it says that you can either reset it by pulling the reset line low or by sending a command over the SPI. The library I used is sending this reset command, but it isn't working for some reason. The logic analyser shows me this signal, it is the first recorded. Maybe it is a timing issue, that the reset has to be sent at the same time as the RFduino resets. Connecting the reset pin solves this issue, because then the RFduino and the MCP2515 are being reset at the same time. If anybody knows more about this, feel free to tell me!
> 2 votes

# Answer
It is difficult to tell whether your chip select is working correctly or not with the logic analyzer view. Have you tried hooking it up to an o-scope to capture what the CS is actually doing(in the analog world)?

What cabling have you chosen between the CAN and arduino?

If you get the o-scope out, you may want to check the MISO and MOSI for ringing, which may lead back to cabling.
> 0 votes

---
Tags: spi, can-bus
---


# Question
Title: Arduino Uno powers off when circuit plugged in to +5V and GND pins
I have a max7219 driving an 8 digit 7 segment LED array with forward current of 20mA and typical forward voltage of 1.85V. I'm trying to power this through my arduino UNO (which itself is drawing power from USB), and have the max7219 chip's +5V and ISet(+resistor) and ground pins connected to the respective pins on the arduino. When I try to plug this in, the arduino will not power up, but removing the jumpers from +5V and GND allows the arduino to power up.

I have confirmed with my multimeter that there is no short between any of the power cables on my led circuit.

The voltage supplied by the arduino works normally if I connect it up to a simple resistor and led on a breadboard.

The voltage across the +5V & GND pins on the arduino drops from 5V to 0V if the jumpers are inserted whilst the arduino is powered up.

I thought perhaps the circuit was trying to draw too much power from the USB, so tried higher resistor values than my initial resistor (20K), to no effect.

What else could be causing this?

# Answer
> 1 votes
> and have the ... ISet(+resistor) and ground pins connected to the respective pins on the arduino.

*What* pin on the Arduino?

The ISet resistor should go to +5 V - don't connect it to an Arduino pin (unless you mean the +5 V Arduino pin). See diagram:

I had a 7-segment display working fine on an Arduino via the USB, see photo:

More details here: Interfacing LED displays with the MAX7219 driver

---
Tags: arduino-uno, power, max7219
---


# Question
Title: AES Simplified for Arduino - Having hard time achieving desired result
Okay, here's the story. I'm not **very** familiar with how Arduino works but learning. I have a project that requires AES encryption on the Arduino Uno. As per a previous question we managed to figure out the problem but failed to resolve it fully so we started using another library. (This one: https://github.com/qistoph/ArduinoAES256)

`uint8_t key[] = { //
 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
 };`

Now onto the problem itself. Using an online AES encryption tool such as: http://aesencryption.net/ Simply asks for a `Key of the encryption` in **plain text** and the output is `base64` as specified by the service here: `The result of the encryption will appear in base64 encoded to prevent character encoding problems.` Also, **plain text** can be used to process the encryption using `AES` algorithm.

I've been trying to achieve the exact same result using an `Arduino Uno` board with the exact same requirements. The end result is to have a `base64` string that can be decrypted on another remote location having the same `key`.

Now as for the `.ino` file it has this setup:

```
#include "aes256.h" //Include library files
#define DUMP(str, i, buf, sz) { Serial.println(str); \
    for(i=0; i<(sz); ++i) { if(buf[i]<0x10) Serial.print('0'); Serial.print(char(buf[i]), HEX); } \
    Serial.println(); } //Help function for printing the Output

aes256_context ctxt;

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

  Serial.println("Initializing AES256... ");
  uint8_t key[] = { //
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
  };
  DUMP("Key: ", i, key, sizeof(key));
  aes256_init(&ctxt, key);

  uint8_t data[] = { //"asdfasdfasdfasdf"
    0x61, 0x73, 0x64, 0x66, 0x61, 0x73, 0x64, 0x66,
    0x61, 0x73, 0x64, 0x66, 0x61, 0x73, 0x64, 0x66
  };
  DUMP("Unencrypted data: ", i, data, sizeof(data));

  aes256_encrypt_ecb(&ctxt, data);
  DUMP("Encrypted data: ", i, data, sizeof(data));

  aes256_decrypt_ecb(&ctxt, data);
  DUMP("Back decrypted data: ", i, data, sizeof(data));

  aes256_done(&ctxt);
}

void loop() {
}

```

---

### 1) I can't seem to understand what is required to have a `plain text` key and `plain text` message to encrypt giving an end result of `base64` output.

For example if I were to do this using `JavaScript`: (And this is just an example).

---

### 2) I'd like to achieve something like this:

```
var key = "32 characters plain text here";
var plain = "Unlimited characters text here that can be used by the library to encrypt this plain message variable";
var base64_output = aes.encrypt256(key, plain);

```

---

### 3) **I'd like to have the base64\_output as base64 string so that it can be printed on a third-party printer hooked to the Arduino.** \- Is this impossible to achieve? We've been trying for some time now from endless conversions to splitting up our `plain` text into chunks of 16 characters so that we can encrypt the message.

---

Any help is greatly appreciated. If someone doesn't mind us contacting them over the phone we would also greatly appreciate a phone call to have this issue explained and resolve so we can share our experience with the Arduino community.

Thanks in advance.

## edit:

We're getting this error

## edit2:

Thank you @Nick Gammon for the quick response. After removing const from the function 4 places and the `key` variable declaration, everything seems to be working fine now. We modified the code in order to print all bytes for each cipher block. We have this output:

```
140 145 154 38 228 66 98 128 116 68 245 193 70 84 205 115
Œ‘š&äBb€tDõÁFTÍsŒ‘š&äBb€tDõÁFTÍs
186 174 17 21 162 83 96 210 128 134 46 206 172 215 0 103
º®¢S`Ò€†.Î¬×
112 4 216 150 27 202 6 176 77 159 123 231 127 128 32 132
pØ–Ê°MŸ{ç€ „pØ–Ê°MŸ{ç€ „
215 110 118 33 167 193 212 121 156 46 63 139 183 124 63 152
×nv!§ÁÔyœ.?‹·|?˜×nv!§ÁÔyœ.?‹·|?˜
130 91 174 118 4 202 250 74 228 7 173 40 246 124 53 173
‚[®vÊúJä(ö|5‚[®vÊúJä(ö|5
231 48 204 82 235 172 202 139 33 134 137 81 209 191 210 217
ç0ÌRë¬Ê‹!†‰QÑ¿ÒÙç0ÌRë¬Ê‹!†‰QÑ¿ÒÙ
184 161 98 135 12 230 86 213 183 113 103 234 187 213 224 133
¸¡b‡æVÕ·qgê»Õà…¸¡b‡æVÕ·qgê»Õà…
Done

```

We're trying to convert each array of bytes into a `char` array of hex values then base\_64 encode it. But we're getting this output which is not what we want. Can you please explain how can we achieve this. Please let us know if it is possible to open a chat with you so that we can understand this better.

# Answer
> We've been trying for some time now from endless conversions to splitting up our plain text into chunks of 16 characters so that we can encrypt the message.

To address this question/issue, below is some code that will take an arbitrary length string and break it into 16-character strings suitable for encoding with AES:

```
const int KEY_SIZE = 32;
const int BLOCK_SIZE = 16;
const char message [] = "Unlimited characters text here that can be used by the library to encrypt this plain message variable";
const byte key [KEY_SIZE] = "32 characters plain text here";

void encrypt_it (const byte plaintext [BLOCK_SIZE], const byte cipherkey [KEY_SIZE]);  // prototype
void encrypt_it (const byte plaintext [BLOCK_SIZE], const byte cipherkey [KEY_SIZE])
  {
  // encrypt here
  }

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

  const char * p = message;

  while (strlen (p) > 0)
    {
    byte plain [BLOCK_SIZE];
    memset (plain, 0, BLOCK_SIZE);  // ensure trailing zeros
    // copy block into plain array
    memcpy (plain, p, min (strlen (p), BLOCK_SIZE));
    // encrypt it
    encrypt_it (plain, key);
    // advance past this block
    p += min (strlen (p), BLOCK_SIZE);
    }
  Serial.println ("Done");
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

---

> I'd like to have the base64\_output as base64 string so that it can be printed on a third-party printer hooked to the Arduino. - Is this impossible to achieve?

Of course it is possible. Just look up (Google) a C or C++ function to base-64 encode a string. There must be thousands of them. This is not an Arduino question, this is a C programming question.

---

> As per a previous question we managed to figure out the problem but failed to resolve it fully ...

Namely here: Implementing DES or AES Encryption with DateTime Synchronization on Uno.

This question actually looks remarkably similar to your previous one.
> 1 votes

# Answer
> 2) I'd like to achieve something like this:
>
> `var key = "32 characters plain text here";
>  var plain = "Unlimited characters text here that can be used by the library to encrypt this plain message variable";
>  var base64_output = aes.encrypt256(key, plain);`

So do it.

```
#define MAX_MESSAGE_SIZE 256
uint8_t key[] = "32 characters plain text here";
uint8_t plain[MAX_MESSAGE_SIZE+1] = "Unlimited characters text here that can be used by the library to encrypt this plain message variable";
aes256_init(&ctxt, key);
aes256_encrypt_ecb(&ctxt, plain);
// plain is now encrypted.

```

That is limited to a maximum message (and encrypted output) size of 256 bytes due to the (purely arbitrary) size of the array I chose.
> 1 votes

# Answer
If you don't have to have the features of the String object, I'd highly recommend you use a uint8\_t (or 'byte' or 'char') array from the get-go. It avoids the conversion altogether, as well as the code complexities of dealing with Strings.

`uint8_t plain = "Hello World";` works great for a literal string, or if you need more flexibility, `uint8_t plain[256+1] = "Hello World";` lets you use or re-use that space for whatever strings you need to hold at run-time (pick a size appropriate for your needs, obviously). Will that let you get past the conversion road-block to focus on encryption (about which, I'd be no help at all).
> 0 votes

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


# Question
Title: Disabling i2c internal pull up resistors
How do you do this? I've been digging around and I can see that I should do this and supply my own external pull up resistors but I don't know exactly how to disable them. The pages I've been reading never explicity state how.

I'm trying to enable I2C between a leonardo and an uno, but I think the i2c bus is slowing down considerably because of the internal pullups. I want to switch to two 4.7k resistors but I can't figure out how to disable the internal ones. I know that the Wire library enables the internals by default, but how do I edit the library or disable the pullups in my sketch?

Maybe I just haven't been reading the right forums or articles, but if anyone could point me in the right direction that would be much appreciated.

EDIT: So the problem is probably with my setup or code, I'll put it down here. Everything I have before setup is importing libraries and variables like my mac, ip, placeholders for output, pwm, etc.

Master:

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

  Wire.begin();

  Ethernet.begin(mac, ip);
  delay(1000);

  server.begin();
  if(server.available()){
    Serial.println("Client Available");
  }
}

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

  ethernetwrite();

}

void ethernetwrite() {
  EthernetClient client = server.available();
  while(client) {
    if(client.find("P")) {
      output = client.parseInt();
      pwm = client.parseInt();

      Serial.println("Begin Transmitting");
      Wire.beginTransmission(14);
      Wire.write(output);
      Wire.write('\t');
      Wire.write(pwm);
      Wire.endTransmission();
      Serial.println("Done Transmitting");

      Serial.print(output);
      Serial.print('\t');
      Serial.println(pwm);

    }
  }
}

```

Slave:

```
void setup() {
  Wire.begin(14);
  Wire.onReceive(wirewrite);

// *   - Base frequencies:
// *      o The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.
// *      o The base frequency for pins 5 and 6 is 62500 Hz.
// *   - Divisors:
// *      o The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64,
// *        256, and 1024.
// *      o The divisors available p1on pins 3 and 11 are: 1, 8, 32, 64,
// *        128, 256, and 1024.

    // Leg 1
    pinMode(leg[1], OUTPUT); setPwmFrequency(leg[1],8); analogWrite(leg[1], offset);

    // Leg 2
    pinMode(leg[2], OUTPUT); setPwmFrequency(leg[2],8); analogWrite(leg[2], offset);

    // Leg 3
    pinMode(leg[3], OUTPUT); setPwmFrequency(leg[3],8); analogWrite(leg[3], offset);

    // Leg 4
    pinMode(leg[4], OUTPUT); setPwmFrequency(leg[4],8); analogWrite(leg[4], offset);

    // Mirror
    pinMode(leg[0], OUTPUT); setPwmFrequency(leg[0],clkdivisor); analogWrite(leg[0], 255);
}

void loop() {

    int time = 10;
    time = time*128/clkdivisor;

    // box(time, 255, 1); // box(delay time, radius pwm, pwm step size);
    // autodisplay();
    updateL();

}

void updateL(){
  if (output == 0) pwm = 255 - pwm;
  switch (output) {
    case 1: pin =  3; break;
    case 2: pin =  9; break;
    case 3: pin =  10; break;
    case 4: pin =  11; break;
    case 0: pin = 5; break;
  }
  //if (output < 5) {
    analogWrite(pin, pwm);
  //}
}

void wirewrite(int numBytes) {
  String message;
  while(Wire.available()>0) {
    char c = Wire.read();
    message.concat(c);
  }
  output = Wire.parseInt();
  pwm = Wire.parseInt();
}

```

When I send data to the master, on the serial monitor it freezes in the first wiring transmission or in the next few, and my slave doesn't seem to respond to the message being sent over i2c. My controls for my device and setup worked prior to my attempts with the Wire library, so there's no problem there.

EDIT: I also am sending a message that looks like this: "P1 103" every .4 seconds or so, but I usually can't get past the first transmission between the arduinos

# Answer
From the datasheet:

> Note that the internal pull-ups in the AVR pads can be enabled by setting the PORT bits corresponding to the SCL and SDA pins, as explained in the I/O Port section.

To disable the internal pull-ups:

```
digitalWrite(A4, LOW);
digitalWrite(A5, LOW);

```

or

```
digitalWrite(2, LOW);
digitalWrite(3, LOW);

```
> 4 votes

# Answer
Let's go back to basics. A low-value pull-up resistor actually improves the shape of the I2C clock and data.

---

### One internal pull-up:

---

### Both ends with the internal pull-up:

---

### 10 k external pull-up:

---

### 4.7 k external pull-up:

---

### 2.2 k external pull-up:

---

As Majenko pointed out, leaving the internal pull-ups enabled would give you a pull-up between 4.7 k and 2.2 k. And as my screenshots show, that is perfectly acceptable.

In fact, it is probably better. See the nice square signals?

---

So your hypothesis that the pull-up is responsible for it running slowly is not supported.

You need to post your code, and other details, such as the length of the cable runs.

> I think the i2c bus is slowing down considerably ...

What do you mean "slowing down"? Compared to what? What are your figures? What is the transmission time? What do you expect it to be? Some facts please.

---

## Reference

My page about I2C
> 4 votes

---
Tags: arduino-uno, i2c, arduino-leonardo, pull-up
---


# Question
Title: Signal sampling: losing data every 103 points when it is recorded in SD
I'm working on a system of acquisition and ECG datalogging with the Arduino, and I'm having the following problem: I'm losing data every 103 points (just 103). No matter the sampling frequency to use, every 103 points, some points are lost, damaging the signal sampling. It could be the recording time on the SD card, but even when the SD.close () command is run only once, the data is lost. Here is a simple test algorithm with a 100 Hz sine wave at the entrance.

---

```
#include <SD.h>
#include <SPI.h>

int CS = 4;
int ECG_PIN = 1;
int voltage;

int index = 0;
const int bufferSize = 5;
int vetor[bufferSize];
int RECORD_TIME = 20000;
File logFile;

void setup(){
  pinMode(CS, OUTPUT);
  pinMode(ECG_PIN,INPUT);

  if(!SD.begin(CS)){
    return;
  }
  logFile = SD.open("ECG_log.txt", O_CREAT | O_WRITE);

}

void loop(){
  while(millis() <= RECORD_TIME){

      voltage = analogRead(ECG_PIN);
    if(logFile){

       logFile.println(voltage);

       delay(0.5);
    }
  }
  logFile.close();
}

```

---

What could it be? Speed analogRead ()? Problem on the SD card?

Sorry if the question is very basic, I am beginner, in a way, the Arduino platform. Any help will be very welcome.

Thanks!...

# Answer
> 4 votes
It's all to do with writing to the SD card.

You have a buffer of 512 bytes which is one "block" of the SD card. When you have written to the card enough to fill that buffer up it has to write that buffer to the SD card and empty the buffer so you can start filling it again.

That writing to the SD card takes time - lots and lots of time (relatively), and it can't be doing anything else at the same time as writing to the SD card.

The only way you can get around that is to have your sampling performed within an interrupt - maybe a timer interrupt - so that it can interrupt the writing to the SD card. However, that's not a simple task.

You would need to implement a system known as *ping-pong* buffers. You have a pair of buffers for storing incoming samples within your interrupt routine. When one buffer is filled up you switch to the other buffer and signal to your main loop() routine that you have filled the buffer. It's then the job of loop() to save that buffer to the SD card and empty it ready for when the second buffer has been filled up. The name *ping-pong* comes from the game of table tennis (also known as *ping-pong*) as you are switching from one buffer to the other and back again in a constant backwards-and-forwards motion like the ball in a game of table tennis.

Getting the right size of buffers is also critical. You have to ensure that the time taken to fill one buffer is always going to be longer than the longest amount of time it takes to write a buffer to the SD card, including any flushing of the internal SD card buffer. The best size is probably going to be to match that internal SD card buffer so every *ping* or *pong* you will be doing an entire SD card block's worth of data - so 512 bytes.

That means you have 3 buffers of 512 bytes - your two ping-pong buffers and the SD card's buffer, which is 1536 bytes - not far off the limit of an Uno, so you may struggle with that. For this kind of thing it is better to use one of the boards with a more meaty chip, like the Mega2560.

Also the line:

```
delay(0.5);

```

is meaningless. `delay()` takes an integer value, so `0.anything` is actually truncated to `0`. To delay for less than a millisecond you should use `delayMicroseconds()`.

---
Tags: analogread, sd-card, signal-processing
---


title: Arduino with ESP8266

text:
# Question
Title: Arduino with ESP8266
I have completed the circuit and code to interface ESP8266 module with Arduino UNO.

When i send `AT`,`AT+RST` from serial monitor the reply is correct .

But when i send AT commands to search WIFI networks (`AT+CWLAP`) & connect to WIFI (`AT+CWJAP="SSID","password"`) the reply is `ERROR`.

But the IP address (may be default) is obtained as `192.168.4.1` when i send `AT+CIFSR` .

Here is my code

```
#include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3

void setup()
{
    Serial.begin(9600);
    esp8266.begin(9600); // your esp's baud rate might be different
}

void loop()
{
    if(esp8266.available()) // check if the esp is sending a message
    {
        while(esp8266.available())
        {
            // The esp has data so display its output to the serial window
            char c = esp8266.read(); // read the next character.
            Serial.write(c);
        }
    }
    if(Serial.available())
    {
        // the following delay is required because otherwise the arduino will read the first letter of the command but not the rest
        // In other words without the delay if you use AT+RST, for example, the Arduino will read the letter A send it, then read the rest and send it
        // but we want to send everything at the same time.
        delay(1000);
        String command="";
        while(Serial.available()) // read the command character by character
        {
            // read one character
            command+=(char)Serial.read();
        }
        esp8266.println(command); // send the read character to the esp8266
    }
}

```

# Answer
> 6 votes
Finally i found the solution .

Send `AT+CWMODE=1` first , then all other commands working fine.

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


# Question
Title: One free pin. Need to display output for the user?
I'm working with lightblue bean. I have a device that writes data to an SD card on a long button press and switches what will be written (from a list of 5 items) on short button press.

The output, printed both to the SD card and to serial looks like this:

```
12:38, 7/15/15, subway
12:55, 7/15/15, subway
12:38, 7/15/15, bus
12:55, 7/15/15, rail

```

etc. It's basically a time stamp then a vale from this list:

```
char* modes[]= {"walking", "subway", "bus", "railroad", "other"};

```

This works perfectly. But the bean has very few pins:

* 5 SCK -- connected to SD card.
* 4 MISO -- connected to SD card.
* 3 MOSI -- connected to SD card.
* 2 SS -- connected to SD card.
* 1 -- input button, takes long and short presses
* 0 --
* A1 SDA --- connected to real time clock for timestamp
* A0 SCL --- connected to RTC (real time clock) for timestamp

I have ***one*** free DIGITAL pin. I need to let the user know what they have selected. This could be done with 5 LEDs that light up next to the user's choice, or maybe displayed text? This is a portable item so a servo that points to the user's choice might be too unreliable.

I've done some research into shift registers. They all seem to need 3 digital pins min. If I could do it with 2 I could rework the button...

Ideas?

# Answer
The 7-segment display board is all very well, but that displays 4 digits. That isn't exactly 5 LEDs. In any case that board has a chip on it, if you are going to buy another chip you may as well get an Attiny and use that. Just have serial input (same as the 7-segment board did).

On the Attiny you have 8 pins, 3 of which will be reserved: Vcc, Gnd, Reset. That leaves you with 5 for the communications *and* the 5 LEDs. So, use one pin for incoming serial, or two pins for SDA/SCL, and use the remaining 3 pins for the LEDs. You can can use Charliplexing to use 3 pins to light up to 6 LEDs.

##

For the fun of it, I made up an example using my Uno (it still only uses 3 pins to light 6 LEDs).

There are 3 x 100 Ω resistors as in the schematic. One is completely hidden by the LEDs (leading from the middle yellow wire to the middle pins of the LEDs).

Code:

```
const byte X1 = bit (2);   // D2 on Uno
const byte X2 = bit (3);   // D3 on Uno
const byte X3 = bit (4);   // D4 on Uno

const byte patterns [7] [2] = {
// PORT DDR
  { 0,   0, }, // all off
  { X1, X1 | X2 }, // LED1: X1 on,  X2 off, X3 HiZ
  { X2, X1 | X2 }, // LED2: X1 off, X2 on,  X3 HiZ
  { X2, X2 | X3 }, // LED3: X2 on,  X3 off, X1 HiZ
  { X3, X2 | X3 }, // LED4: X2 off, X3 on,  X1 HiZ
  { X1, X1 | X3 }, // LED5: X1 on,  X3 off, X2 HiZ
  { X3, X1 | X3 }, // LED6: X3 on,  X1 off, X2 HiZ
};

void setup ()
  {
  }  // end of setup

void loop ()
  {
  for (int i = 0; i < 7; i++)
    {
    DDRD = patterns [i] [1];
    PORTD = patterns [i] [0];
    delay (500);
    }  // end of for loop
  }  // end of loop

```

The code displays each of the 6 LEDs (plus all off) in a cycle. For each one it configures the DDR (data direction register) plus the PORT (output register) appropriately to light the desired LED.

It works perfectly, except that you may need to work out which LED is which by experimentation.
> 2 votes

# Answer
Seems you have I²C on the board you could possibly use an I²C LCD backpack, like from breakouts if you already have an LCD, this means you can have the RTC and display on the I²C bus and probably more things.

Another option seems you mentioned LEDs, you could still use the I²C bus and use an I/O expander and hook LEDs up to that and address them over the I²C. You can use a PCF8575(16 I/O), as there are Arduino libraries. There are breakouts for it. Or you could make your own from another AVR, like one from the ATTiny line, seems there is 5 LEDs.

A I²C bus example:
<sub>(source: ermicro.com)</sub>

Seems you want to use the PWM, you can use a dot/bar driver IC, such as the LM3914 it takes an analog value and shows it as a point on the strip of LEDs, example below:

The IC can also work down to 3V.

What you will need to do is add a low pass filter to convert the PWM to a smooth analog value. You will add this in place of the input circuitry(D1 & C1) there:

If there is any confusion on the LM3914, there are quite a few tutorials on google.
> 4 votes

# Answer
I've found a solution! 7-segment display breakout board.

This works art 3.3v which is critical for a lightblue bean. I think a servo might be the most creative solution.

I'm still convinced there must be some way to use PWM...
> 0 votes

---
Tags: pins, sd-card, display, shift-register, rtc
---


# Question
Title: How to detect if more than one button was pressed
I am designing a turn signal bicycle blinker using two pushbuttons as input, one for each side, with a corresponding light for each button. The idea is this:

1. Pressing one side makes same side start blinking;
2. Pressing same side again to turn it off;
3. Pressing other side turns off this side and turns other side on;
4. (now the tricky part!) if **both** buttons are pressed (or more precisely, if one button is pressed before the other is released), then - and only then - I start blinking both sides ("warning signal" feature).

As I see it, the problem is that I need to wait until I release a single button (that would be one complete click) to turn a single side on, because if I press the second while the first remains pressed, that would be another event/gesture ("both\_click", for lack of a better name).

Another design option would be to turn a single light on immediately on press, and if I press the second before release the first, then in would *also* turn the other light (thus comprising the "warning", both-lights-blinking mode). While that sounds feasible, there is all the debouncing logic in the Button ("Botao") class, and I am afraid I painted myself into a corner with the specific object-oriented design choices I've made.

EDIT: a third design option would be to add a `run` method on each button and, instead of only running the tested "pseudo-event" method, save the current state and event in variables, testing those variables in `loop()` (property `button.wasPressed` instead of method `button.wasPressed()`, for example).

I'm posting my current code (relevant parts only). Note there is a comment in the loop where I think I should detect double click.

Main .ino file:

```
#include "PiscaPisca.cpp"
#include "Botao.cpp"

PiscaPisca pisca;

Botao botao1;
Botao botao4;

void setup() {

  pisca.configure(LEFT, RIGHT, BUZZER);

  botao1.configure(BUTTON1);
  botao4.configure(BUTTON4);
}

void loop() {

  // HOW SHOULD I DETECT BOTH WERE PRESSED??
  // if (bothPressed()) { pisca.toggleWarning(); }

  if (botao1.wasPressed()) { pisca.toggleLeft();  }
  if (botao4.wasPressed()) { pisca.toggleRight(); }

  pisca.run();
}

```

Botao.cpp (this is a button class with debounce)

```
#include <Arduino.h>

class Botao
{
    int _pino;

    const int DEBOUNCE_DELAY = 30;

    int buttonState;
    int lastState = HIGH;

    int lastDebounceTime;

    public : void configure(int pino)
    {
        _pino = pino;
        pinMode(pino, INPUT_PULLUP);
    }

    public : boolean wasPressed()
    {
        return debounce(LOW);
    }

    public : boolean wasReleased()
    {
        return debounce(HIGH);
    }

    public : boolean debounce(int state)
    {
        boolean gotEvent = false;

        int reading = digitalRead(_pino);

        if (reading != lastState) {
            lastDebounceTime = millis();
        }

        if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
            if (reading != buttonState) {
                buttonState = reading;

                if (buttonState == state) {
                    gotEvent = true;
                }
            }
        }

        lastState = reading;

        return gotEvent;
    }
};

```

PiscaPisca.cpp (the state-machine itself)

```
#include "Arduino.h"
#include "PwmPin.cpp"
#include "Beeper.cpp"

typedef enum {
    NONE        = 0,
    RIGHT_LIGHT = 1,
    LEFT_LIGHT  = 2,
    BOTH        = 3
};

class PiscaPisca
{
    PwmPin _left;
    PwmPin _right;

    Beeper _beeper;

    long _timeReference = 0;

    const int PERIOD = 350;

    boolean
        _running = false,
        _lightState = false;

    int _sides_to_turn = NONE;

    public : void configure(int leftPin, int rightPin, int buzzerPin)
    {
        _left.configure(leftPin);
        _right.configure(rightPin);
        _beeper.configure(buzzerPin);
    }

    public : void run()
    {
        evaluateBlink();
    }

    public : void toggleLeft()
    {
        checkRestart(LEFT_LIGHT);
    }

    public : void toggleRight()
    {
        checkRestart(RIGHT_LIGHT);
    }

    void checkRestart(int lightSide)
    {
        _timeReference = 0;

        // some clever bit-twiddling can never hurt too much:
        _sides_to_turn = lightSide & ~_sides_to_turn;

        Serial.println(lightSide);
        Serial.println(_sides_to_turn);

        if (_sides_to_turn > 0)
        {
            _running = true;
        }
        else
        {
            lightsOff();
            _running = false;
            _lightState = false;
        }
    }

    void evaluateBlink()
    {
        if (!_running)
        {
            return;
        }
        else
        {
            long currentMillis = millis();
            if (currentMillis - _timeReference > PERIOD) {
                _timeReference = currentMillis;
                _lightState = !_lightState;
                performBlink();
            }
        }
    }

    void performBlink()
    {
        if (_lightState)
        {
            _beeper.beepIn();
            lightsOn();
        }
        else
        {
            _beeper.beepOut();
            lightsOff();
        }
    }

    void lightsOn()
    {
        if (isLightSet(LEFT_LIGHT))
        {
            _left.on();
        }
        if (isLightSet(RIGHT_LIGHT))
        {
            _right.on();
        }
    }

    boolean isLightSet(int lightSide)
    {
        return (_sides_to_turn & lightSide) == lightSide;
    }

    void lightsOff()
    {
        _left.off();
        _right.off();
    }

};

```

# Answer
Interesting question, and tricky to get perfect. :)

I wrote a switch manager class a while back. It's just a .h file which you can put in your libraries folder (or add to your sketch).

**SwitchManager.h**

```
#include <Arduino.h>

class SwitchManager
  {
  enum { debounceTime = 10, noSwitch = -1 };
  typedef void (*handlerFunction) (const byte newState,
                                   const unsigned long interval,
                                   const byte whichSwitch);

  int pinNumber_;
  handlerFunction f_;
  byte oldSwitchState_;
  unsigned long switchStateChangeTime_;  // when the switch last changed state
  unsigned long lastLowTime_;
  unsigned long lastHighTime_;

  public:

     // constructor
     SwitchManager ()
       {
       pinNumber_ = noSwitch;
       f_ = NULL;
       oldSwitchState_  = HIGH;
       switchStateChangeTime_ = 0;
       lastLowTime_  = 0;
       lastHighTime_ = 0;
       }  // end of constructor

     void begin (const int pinNumber, handlerFunction f)
       {
       pinNumber_ = pinNumber;
       f_ = f;
       if (pinNumber_ != noSwitch)
         pinMode (pinNumber_, INPUT_PULLUP);
       }  // end of begin()

     void check ()
       {
       // we need a valid pin number and a valid function to call
       if (pinNumber_ == noSwitch || f_ == NULL)
         return;

        // see if switch is open or closed
        byte switchState = digitalRead (pinNumber_);

        // has it changed since last time?
        if (switchState != oldSwitchState_)
          {
          // debounce
          if (millis () - switchStateChangeTime_ >= debounceTime)
             {
             switchStateChangeTime_ = millis ();  // when we closed the switch
             oldSwitchState_ =  switchState;  // remember for next time
             if (switchState == LOW)
               {
               lastLowTime_ = switchStateChangeTime_;
               f_ (LOW, lastLowTime_ -  lastHighTime_, pinNumber_);
               }
             else
               {
               lastHighTime_ = switchStateChangeTime_;
               f_ (HIGH, lastHighTime_ - lastLowTime_, pinNumber_);
               }

             }  // end if debounce time up
          }  // end of state change
       }  // end of check()

     unsigned long getLastStateChangeTime () const { return switchStateChangeTime_; }
     unsigned long getLastStateLowTime ()    const { return lastLowTime_; }
     unsigned long getLastStateHighTime ()   const { return lastHighTime_; }

  };  // class SwitchManager

```

More details here.

Put that into a folder called `SwitchManager`, put that into your sketch folder -\> `libraries` folder and restart the IDE.

That basically handles:

* debouncing
* detecting state changes (eg. now on, was off)

Using that we can now write a sketch that does the indicators:

```
#include <SwitchManager.h>

typedef enum {
    NONE,
    LH_DOWN,
    RH_DOWN,
    LH_LIGHT_ON,
    RH_LIGHT_ON,
    BOTH
};

const unsigned long BLINK_INTERVAL = 500; // ms

// pin assignments
const byte LH_SWITCH_PIN = 2;
const byte RH_SWITCH_PIN = 3;
const byte LH_LIGHT = A4;
const byte RH_LIGHT = A5;

SwitchManager LHswitch;
SwitchManager RHswitch;

byte state = NONE;

void handleLHPress (const byte newState, const unsigned long interval, const byte whichPin)
  {
  // switch down?
  if (newState == LOW)
     {
     switch (state)
       {
       // if other switch down, switch to warning mode
       case RH_DOWN:
         state = BOTH;
         break;

       // if already on or warning signal, turn all off
       case LH_LIGHT_ON:
       case BOTH:
         state = NONE;
         break;

       // otherwise switch is now down, but not yet released
       default:
         state = LH_DOWN;
         break;
       }  // end of switch
     return;
     }  // end of LH switch down

  // switch must be up

  if (state == LH_DOWN)  // if down, switch to down-and-released mode
    state = LH_LIGHT_ON;
  }  // end of handleLHPress

void handleRHPress (const byte newState, const unsigned long interval, const byte whichPin)
  {
  // switch down?
  if (newState == LOW)
     {
     switch (state)
       {
       // if other switch down, switch to warning mode
       case LH_DOWN:
         state = BOTH;
         break;

       // if already on or warning signal, turn all off
       case RH_LIGHT_ON:
       case BOTH:
         state = NONE;
         break;

       // otherwise switch is now down, but not yet released
       default:
         state = RH_DOWN;
         break;
       }  // end of switch
     return;
     }  // end of RH switch down

  // switch must be up

  if (state == RH_DOWN)  // if down, switch to down-and-released mode
    state = RH_LIGHT_ON;
  }  // end of handleRHPress

void setup ()
  {
  LHswitch.begin (LH_SWITCH_PIN, handleLHPress);
  RHswitch.begin (RH_SWITCH_PIN, handleRHPress);
  pinMode (LH_LIGHT, OUTPUT);
  pinMode (RH_LIGHT, OUTPUT);
  }  // end of setup

unsigned long lastBlink;
bool onCycle;

void blinkLights ()
  {
  lastBlink = millis ();
  onCycle = !onCycle;

  // default to off
  digitalWrite (LH_LIGHT, LOW);
  digitalWrite (RH_LIGHT, LOW);

  // every second time, turn them all off
  if (!onCycle)
    return;

  // blink light
  switch (state)
    {
    case NONE:
      break;

    case LH_DOWN:
    case LH_LIGHT_ON:
      digitalWrite (LH_LIGHT, HIGH);
      break;

    case RH_DOWN:
    case RH_LIGHT_ON:
      digitalWrite (RH_LIGHT, HIGH);
      break;

    case BOTH:
      digitalWrite (LH_LIGHT, HIGH);
      digitalWrite (RH_LIGHT, HIGH);
      break;

    }  // end of switch on state

  }  // end of blinkLights

void loop ()
  {
  LHswitch.check ();  // check for presses
  RHswitch.check ();  // check for presses

  if (millis () - lastBlink >= BLINK_INTERVAL)
    blinkLights ();

  // other stuff
  }  // end of loop

```

The state machine has a number of states:

* NONE -\> all lights off
* LH\_DOWN -\> LH switch depressed, not yet released
* RH\_DOWN -\> RH switch depressed, not yet released
* LH\_LIGHT\_ON -\> LH switch depressed, and released
* RH\_LIGHT\_ON -\> RH switch depressed, and released
* BOTH -\> Warning lights mode (flash both lights)

If we get a LH down while the RH is still pressed, or vice-versa, we switch to warning mode.

On a button release we switch from "switch down" to "switch released".

A second press, while either or both lights are on cancels them.

Note that my switches were wired to ground with the internal pull-up, so they are LOW when pressed and HIGH when not pressed.
> 2 votes

---
Tags: programming, c++, library, button, algorithm
---


# Question
Title: Determining power consumption with Arduino and JeeLib
I built a basic LED blinker to serve as a car theft deterrent. Originally I was using a 9V battery and delay() but I've refined my approach to consume less power. Here's my code, utilizing the JeeLib library:

```
#include <JeeLib.h>

int led = 13;
ISR(WDT_vect) { Sleepy::watchdogEvent(); }

void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

void loop() {
  blink_quick();
  blink_quick();
  Sleepy::loseSomeTime(8000);
}
void blink_quick() {
  digitalWrite(led, HIGH);
  Sleepy::loseSomeTime(250);
  digitalWrite(led, LOW);
  Sleepy::loseSomeTime(250);
}

```

It just blinks twice every 8 seconds. I also used 4 AA batteries as they have a higher amperage rating. How long should this system work before I need to replace the batteries?

My thinking is that AA batteries offer 2000mAh and an Arduino typically consumes about 45mA on average. If I were running the above code with delay() instead of the JeeLib functions, it would last for 44 hours. Let's call one cycle the two blinks and the following 8 seconds of rest. I am confused about how long I should factor in for the digitalWrite(led, HIGH) and the corresponding 'low' call, because the rest of the time, the circuit is using JeeLib. I am just interested in figuring out how long I can let this run without changing the batteries, and admittedly I am not experienced enough to tell definitively.

Thanks!

# Answer
> 1 votes
What board are you using? For example, the Uno has a lot of other components that will consume power, even if you sleep the main processor. Instead use something like a Pro Mini.

You can bypass the voltage regulator, and just supply 4.5v by using 3 AA batteries. You can even use just 2 AAs if you have the 3.3v version. The lower the voltage the less current the ATMega uses.

Most importantly, measuring the power consumption using a multimeter. Measure the current the led uses. Disconnect the led, and measure how much the arduino uses. Use this handy Battery Life Calculator, and just fill in those numbers.

Run the led with the lowest current, where the led is still visible enough. Running a power-led at just 1mA will still give a decent amount of light.

In your situation, if coded correctly, power usage of the ATMega is negligible. The only real power user is the led. If you run the led at 1mA, and use a set of AA batteries, you get around 3.5 years of running time, no problem.

# Answer
> 0 votes
As mentioned in another answer use a multimeter to measure. However I would recommend using the cars battery to power the system. A parasitic draw on a cars battery of under 1 amp is considered acceptable (per what I learned in school). A parasitic draw is current used while the car is off. Get a clamp ammeter and check your parasitic draw and if you have the available amperage to spare run it from your battery. To check your parasitic draw place the clamp around the ground wire (or multiple ground wires) at the battery terminal.

If you run it from your car battery you will never have to worry about changing the battery and it becomes a set and forget system.

# Answer
> 0 votes
I have a lot of detail about here: Power saving techniques for microprocessors

> Let's call one cycle the two blinks and the following 8 seconds of rest. I am confused about how long I should factor in for the digitalWrite(led, HIGH) and the corresponding 'low' call, because the rest of the time, the circuit is using JeeLib.

To answer this specific question, we can work out a "power budget" by taking the large consumption time (eg. the LED being on) and working out how much that is, as a fraction.

So in your case you have the LED on for 500 ms every 8 seconds. That is:

```
8 / 0.5 = 16

```

That is, 1/16th of the time. Or, putting it another way:

```
0.5 / 8 = 0.0625

```

So, let's say the LEDs use 20 mA. The *average* consumption then is:

```
0.020 * 0.0625 = 0.00125 A (1.25 mA)

```

And let's assume that while asleep it uses 1 mA. So the total consumption on average is:

```
1 + 1.25 = 2.25 mA

```

So if you have a 2000 mAh battery, you would get:

```
 2000 / 2.25 = 888.88  hours

```

However as others have pointed out, this is pretty meaningless if you use a development board. The on-board LED, the voltage regulator, the USB chip etc. will use much more power than you save by going to sleep. You have to move to a low-power or custom design, which minimizes these extra effects.

With careful design you should be able to get the sleep usage down to around 6 µA with the watchdog timer to wake you up.

---
Tags: led, power, battery
---


title: How to test Arduino board?

text:
# Question
Title: How to test Arduino board?
A little history: I have two Arduino Uno and I couldn't program them by IDE, I got these errors:

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00

```

So I googled it for a while and I suspect of missing bootloader on atmega micro on the board, as I don't have AVR programmer I programmed both Arduinos with Raspberry Pi and Arduino IDE tool through ICSP pins.

It (burning bootloader) runs perfectly on both Arduino. One of them got fixed and got back to normal, but the other one gave me same error, so I changed their Atmega micro, but same result. Second Arduino (bad one) can't transfer program to AVR even with other one (good one) AVR so both AVRs on the boards are good. The program (blink LED) run even on the bad Arduino and pin 13 blink.

My questions are:

How could I test the suspected Arduino board? Is the second Atmel micro near usb female port need bootloader too?

> **Update 1**: I follow this tutorial but my Arduino couldn't go to DFU mod by shorting the pins. When I connect those pins led pin 13 not blink and lsusb command show Arduino not Atmel.
>
> **Update 2** : I went through this question and this troubleshoot to upload bootloader to Atmel USB device but my second Arduino (bad one) didn't respond and gave me this error :

```
Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul 13 2015 at 11:14:35 with Arduino IDE 105.
Attempting to enter ICSP programming mode......................................................
Failed to enter programming mode. Double-check wiring!
Programming mode off.

```

> Is it possible my Atmega16U2 chip is burned?
>
> **Update 3** : I do reach the point that I am pretty sure Atmega16U2 is dead and it isn't responding to its ICSP pins and it blocks any USB to AVR connection. I check the wiring and I test it on good Arduino and its sequence are correct and it works on good one. Now what can I do, as Atmega16U2 is not rechangeable, should I throw bad Arduino away?

# Answer
This answer is for your 3dr Update - should you throw it away? I'd say no, if you are comfortable with using the Raspberry PI as programmer, as you already did. You will not be able to use the USB-based programming, nor you will be able to emulate USB peripherals, but that's it.

Everything else will (or should) work normally, so why would you throw it away? :-)

I also suggest you grab the stronger magnifying lens you can find and have a look at the soldering of all the components. Especially those connected to the Atmega16U and the chip itself. Maybe it's not broken, but there is some short caused by conductive debris or by some excess of soldering material. If that's the case, it might be easy to remove it.
> 0 votes

# Answer
does the built-in arduino LED light up?? If yes try connecting your arduino in another uno usb port or try pressing the reset button on your arduino uno.
> 0 votes

---
Tags: arduino-uno, bootloader
---


# Question
Title: avrdude : stk500_get sync<> attempt 10 of 10 not in sync : resp=0x20 how do i get pass this error for ardunio uno board
When I first started with a bare minimum code. The compiler compiles the code, but when I try to upload, this is the error message I get:

```
 AVRDUDE: STK500_GETSYNC<> ATTEMPT 10 OF 10 NOT IN SYNC :RESP=0X20

```

How do I fix this?

# Answer
There are multiple reasons why you are getting this error.

1. Bootloader is either missing or corrupted. This is fairly unlikely.
2. Wire connected to pin 0 (RX)
3. Wrong COM port is chosen within the arduino IDE.
4. Drivers are not installed. You can update it within the Device Manager if you are using Windows.

Here is a link to an article explaining the causes and how to fix them, http://www.instructables.com/id/A-solution-to-avrdude-stk500getsync-not-in-syn/
> 1 votes

---
Tags: arduino-uno, avrdude, compile
---


# Question
Title: How do you send data via I2C without the wire library?
I have the following digital potentiometer: DS1803-100 which, according to the datasheet, can be controlled using a two-wire serial interface. I have managed to get it working using Wire, however I can't seem to get it working using only digitalWrite (link to code). Can somebody tell me why? For reference, **0x50** is the *address + r/!w bit*, **0xA9** is the *command (write to pot 0 in my case)* and the next **0xA9** is the *value to write*. I know there's something wrong with the code, however I cannot figure out what. Thank you in advance!

EDIT: Here is the code

```
int PIN_SCK = 12;
int PIN_SDA = 11;

const int delayvalue = 10;

void setup(){
    digitalWrite(PIN_SCK, 1); // I can first declare the state
    digitalWrite(PIN_SDA, 1);
    pinMode(PIN_SCK, OUTPUT); // then turn them on
    pinMode(PIN_SDA, OUTPUT);

    delay(1000);

    digitalWrite(PIN_SDA, 0); // start bit

    shift_out(PIN_SDA, PIN_SCK, 0x50);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);

    digitalWrite(PIN_SDA, 1); // stop bit

}

void loop(){

}
// uint8_t is the same as 8 bits aka one byte
void shift_out(uint8_t datapin, uint8_t clockpin, uint8_t val){
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        digitalWrite(datapin, !!(val & (1 << (7 - i))));
        delay(1);
        digitalWrite(clockpin, 0);
        delay(delayvalue);
        digitalWrite(clockpin, 1);
        delay(delayvalue);
    }

    digitalWrite(datapin, 0); // to enable stop bit
    delay(100); // wait fro aknowledgement

}

```

# Answer
> 4 votes
Well, short answer: It was the acknowledge bit, I forgot to send a clock pulse in order to receive it (duh! my device generates the clock for the attached potentiometer, I was waiting for the device to "send" me a bit, I needed to "request" the bit on a rising edge of the clock).

Long answer: the code looks like this now:

```
int PIN_SCK = 12;
int PIN_SDA = 11;

const int delayvalue = 10;

void setup(){
    digitalWrite(PIN_SCK, 1); // I can first declare the state
    digitalWrite(PIN_SDA, 1);
    pinMode(PIN_SCK, OUTPUT); // then turn them on
    pinMode(PIN_SDA, OUTPUT);

    delay(1000);

    digitalWrite(PIN_SDA, 0); // start bit
    delay(10);
    digitalWrite(PIN_SCK, 0);
    delay(10);

    shift_out(PIN_SDA, PIN_SCK, 0x50);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);

    digitalWrite(PIN_SDA, 1); // stop bit

}

void loop(){

}
// uint8_t is the same as 8 bits aka one byte
void shift_out(uint8_t datapin, uint8_t clockpin, uint8_t val){
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        digitalWrite(datapin, !!(val & (1 << (7 - i))));
        delay(1);
        digitalWrite(clockpin, 1);
        delay(delayvalue);
        digitalWrite(clockpin, 0);
        delay(delayvalue);
    }

    digitalWrite(datapin, 0); // to enable stop bit
    delay(10);

    // Here I handle the AKNOWLEDGE signal which happens after
    // each byte sent. Be it address, command or value
    digitalWrite(clockpin, 1);
    delay(10);
    digitalWrite(clockpin, 0);
    delay(10);

}

```

So basically I followed and reproduced the signals in this timing diagram faithfully with one small exception: I did not generate a rising edge when I expected the acknowledge bit (basically the diagram but with SCK being 0 right below the acknowledge bits).

Hope this helps somebody!

# Answer
> 1 votes
I2C is a lot more complex than just shifting bytes out.

See: I2C - Two-Wire Peripheral Interface - for Arduino

Your code does not seem to take any of that into account.

Why do you not want to use the Wire library? The hardware on the chip (what chip do you have?) supports it. Why ignore that and try to do it yourself?

---
Tags: arduino-uno, i2c, digital-analog-conversion
---