# Question
Title: Reading HMC5883L hex values in 2's compliment C code
I want to develop my C code for HMC5883L.

I have 2 questions for my current code development.

My first question is: But what I found in the datasheet is that the values are in the 2's compliment, so I don't know how to deal with them?! Do I have to take the values as they are in the data registers and convert them to decimal values and that's it? Or I have to convert them from 2's compliment to the original hex values?

This is a quote from the datasheet:

> Send 0x3D 0x06 (Read all 6 bytes. If gain is changed then this data set is using previous gain) Convert three 16-bit 2’s compliment hex values to decimal values and assign to X, Z, Y, respectively.

My second question: How o read the data registers? What is the procedure? I saw in the datasheet the following method but I didn't understand it.

> Loop Send 0x3D 0x06 (Read all 6 bytes. If gain is changed then this data set is using previous gain) Convert three 16-bit 2’s compliment hex values to decimal values and assign to X, Z, Y, respectively. Send 0x3C 0x03 (point to first data register 03) Wait about 67 ms (if 15 Hz rate) or monitor status register or DRDY hardware interrupt pin End\_loop

So, I didn't understand that I send read command then I send write command, so how HMC5883L would return the value to me?

Regards,

# Answer
2's complement is the normal signed values in any modern system, including Arduino.

Just place the bytes into a signed variable of the right size in the right positions and there is your value.

In I2C, to read a register, you typically have to make two transactions. The first is a write to set the register number you want to access, the you follow that with a read transaction to get the data.
> 1 votes

---
Tags: arduino-nano, i2c, c, gyroscope
---


# Question
Title: Seven-Segment Display doesn't work on two lights
This is my code:

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

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

```

This is my circuit:

Problem:

Light A and B doesn't work when I plug the red cable to 4 and 5. All the other lights works just fine.

# Answer
> 0 votes
As jwpat7 states, you need a current-limiting resistor for *each* segment, between the data pin (on the Arduino) and the segment pin (on the display). Your Fritzing diagram only shows *one resistor* in the circuit, from the common cathode to GND on the Arduino.

You can not, or should not, *share one resistor to ground* (assuming that you have a common cathode seven segment display). You need a current-limiting resistor on *each anode* (again, (assuming that you have a common cathode seven segment display).

If you are sharing the current-limiting resistor between all segments, and then try to light more than more segment, at a time (which it sounds like you are doing ("when I plug the red cable to 4 and 5"), then the current through the current-limiting resistor will increase, and as a result, the voltage will change significantly enough, such that there is not sufficient voltage drop across the LED in order to make it light up.

Remember, 0.7 V is dropped across the LED.

Test each on the segments, **one at a time**, to make sure they all work, as Ignacio states in his comment.

Also, your sketch should be more complete, along the lines of:

```
void setup() {
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
}

void loop() {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
    digitalWrite(8, HIGH);
}

```

Connect up all of the pins, using a current-limiting resistor on each anode, and then try it programmatically.

If your seven segment display is a common anode, then, again, you need a resistor between each cathode and the data pins, and bring the pins `LOW` to light the corresponding segment, i.e.

```
    digitalWrite(8, LOW);

```

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


# Question
Title: Scrambled query responses from ESP8266 to Uno, what are possible causes of the problem?
I have a small test sketch that sends queries to an ESP8266 chip \[mounted on an ESP-01 board\], and these responses are invariably scrambled, though the response varies from execution to execution, e.g.,

(execution 1)

```
_________[ Connect to AP ]__________
__________[ AT+CWJAP="KCTcircuit2","" ]__________
AT+CWJAX="I⸮Tcircuiz2",""H

```

(execution 2)

```
__________[ Connect to AP ]__________
__________[ AT+CWJAP="KCTcircuit2","" ]__________
AT+CWJAH="KCTcircuiz2!,""H

```

What could be the source of the problem? I need to resolve this before I can start testing the real sketch.

My test sketch follows \[stripped of extraneous code\]:

```
#include <SoftwareSerial.h>
// _______________________________
#define sendit(x) ( { \
    Serial.print(F("__________[ ")); \
    Serial.print(x); \
    Serial.println(F(" ]__________")); \
    esp8266.write(x); \
    esp8266.write(F("\r\n")); \
    esp8266.readBytes(buffer, sizeof(buffer)); \
    Serial.println(buffer); \
    delay(2000); \
  } )

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

// _______________________________
SoftwareSerial esp8266(12, 13); // RX, TX
char buffer[50];

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

// _______________________________
void loop()
{
}

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

// ____________________________________________________________________________________________________
void CommandList()
{
  desc("Test AT Startup");
  sendit("AT");
  desc("Restart the module");
  sendit("AT+RST");
  desc("Query baud rate");
  sendit("AT+CIOBAUD?");
  desc("Query firmware version");
  sendit("AT+GMR");
  desc("WIFI mode");
  sendit("AT+CWMODE?");
  desc("Get local IP address");
  sendit("AT+CIFSR=?");
  desc("Query current multiplex mode");
  sendit("AT+CIPMUX=?");
  desc("Enable echo (Sends back received command before response)");
  sendit("ATE1");
  desc("Set Station mode");
  sendit("AT+CWMODE=3");
  desc("Lists available APs");
  sendit("AT+CWLAP");
  sendit("AT+CWLAP");
    desc("Connect to AP");
  sendit("AT+CWJAP=\"KCTcircuit2\",\"\"");
  desc("Prints the SSID of Access Point ESP8266 is connected to.");
  sendit("AT+CWJAP?");
  desc("List clients connected to ESP8266 softAP");
  sendit("AT+CWLIF");
  desc("Get IP address of ESP8266 station.");
  sendit("AT+CIPSTA?");
  desc("Get information about connection");
  sendit("AT+CIPSTATUS=?");
  desc("Get local IP address");
  sendit("AT+CIFSR=?");
  desc("Get the SSID of Access Point ESP8266 is connected to.");
  sendit("AT+CWJAP?");
  desc("Get the SSID of Access Point ESP8266 is connected to -CUR");
  sendit("AT+CWJAP_CUR?");
  desc("Configuration of softAP mode");
  sendit("AT+CWSAP?");
  desc("Configuration of softAP mode = CUR");
  sendit("AT+CWSAP_CUR?");
  desc("Disconnect from AP");
  sendit("AT+CWQAP");
  Serial.println(F("__________________"));
  Serial.println();
 }

```

Typical output is as follows:

```
"ESP8266_ATcmdtest", compiled on: Jun  5 2017 at 14:00:04
Running on: Arduino UNO: ATmega328P

__________[ Test AT Startup ]__________
__________[ AT ]__________
ATn

__________[ Restart the module ]__________
__________[ AT+RST ]__________
AT+QST$

__________[ Query baud rate ]__________
__________[ AT+CIOBAUD? ]__________
AT+CHOBAUD⸮⸮

__________[ Query firmware version ]__________
__________[ AT+GMR ]__________
AT+TJ⸮⸮AUD⸮⸮

__________[ WIFI mode ]__________
__________[ AT+CWMODE? ]__________
AT+CWLODE?G⸮

__________[ Get local IP address ]__________
__________[ AT+CIFSR=? ]__________
AT+CHFSR=?⸮

__________[ Query current multiplex mode ]__________
__________[ AT+CIPMUX=? ]__________
AT+CIPMUX=r⸮

__________[ Enable echo (Sends back received command before response) ]__________
__________[ ATE1 ]__________
ATE0=PMUX=r⸮

__________[ Set Station mode ]__________
__________[ AT+CWMODE=3 ]__________
AT+CWMODE=⸮⸮

__________[ Lists available APs ]__________
__________[ AT+CWLAP ]__________
AJ+CWL@P⸮=⸮⸮
__________[ AT+CWLAP ]__________
AT+CWLAP⸮=⸮⸮

__________[ Connect to AP ]__________
__________[ AT+CWJAP="KCTcircuit2","" ]__________
AT+CWJAH="KCTcircuiz2!,""H

__________[ Prints the SSID of Access Point ESP8266 is connected to. ]__________
__________[ AT+CWJAP? ]__________
AT+CWJAP?⸮KCTcircuiz2!,""H

__________[ List clients connected to ESP8266 softAP ]__________
__________[ AT+CWLIF ]__________
AV+CWLIFx⸮KCTcircuiz2!,""H

__________[ Get IP address of ESP8266 station. ]__________
__________[ AT+CIPSTA? ]__________
AT+CIPSTA?CTcircuiz2!,""H

__________[ Get information about connection ]__________
__________[ AT+CIPSTATUS=? ]__________
AT+CIP*UQUM⸮⸮2ircuiz2!,""H

__________[ Get local IP address ]__________
__________[ AT+CIFSR=? ]__________
AT+CIFSR=?}⸮⸮2ircuiz2!,""H

__________[ Get the SSID of Access Point ESP8266 is connected to. ]__________
__________[ AT+CWJAP? ]__________
AT+CWJAP? }⸮⸮2ircuiz2!,""H

__________[ Get the SSID of Access Point ESP8266 is connected to -CUR ]__________
__________[ AT+CWJAP_CUR? ]__________
AT+CW⸮AP5UI⸮⸮⸮ircuiz2!,""H

__________[ Configuration of softAP mode ]__________
__________[ AT+CWSAP? ]__________
AT+CWSAP?HI⸮⸮⸮ircuiz2!,""H

__________[ Configuration of softAP mode = CUR ]__________
__________[ AT+CWSAP_CUR? ]__________
AT+CWSAP5UI⸮r⸮ircuiz2!,""H

__________[ Disconnect from AP ]__________
__________[ AT+CWQAP ]__________
AZ+CWPAP⸮UI⸮r⸮ircuiz2!,""H
__________________

```

# Answer
Cause: software serial at 115200 baud.

Solution: configure the esp8266 for a lower baud rate or use hardware serial.

The problem is basically that the Arduino cannot run 115200 baud SoftwareSerial reliably. It is common to get corruption of incoming characters, or characters completely skipped, due in part to the SoftwareSerial implementation being unable to react fast enough to the data coming in. The time between one stop bit and the next start bit is often shorter than the amount of time taken to store the data in the receive ring buffer, so the ISR cannot respond to the new start bit in time, and data is lost. Running at a lower baud rate gives more time for the data to be stored before the next start bit arrives, thus giving the ISR time to finish and be ready to respond to the next byte coming in.

You need to change the baud rate of the ESP8266 itself (I find 9600 is a good reliable value) using one of (depending on your firmware version):

```
AT+CIOBAUD=9600

```

or

```
AT+UART_DEF=9600,8,1,0,0

```

or

```
AT+IPR=9600

```

Last time I did it on an ESP8266 it was the first one that worked.

Then you will need to change your program to use 9600 baud instead of 115200 baud in your `esp8266.begin(...)`.
> 2 votes

# Answer
Since you mentioned you tried other baud rates, I am guessing it could be an RF issue. ESP8266 is a very sensitive device and is known to have weird electrical behaviour. Do you have a cap between VCC and GND?
> 0 votes

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


title: Pause in the program for some time

text:
# Question
Title: Pause in the program for some time
I have a variable `timeInSec` which records the time as loop begins. It is defined as `timeInSec = millis();`. I have two conditions. If `(timeInSec - lastRun)< 5` (that is 5 sec) , the first condition is executed(the if statement).Otherwise if `(timeInSec - lastRun)>5` the second condition is executed(else statement). Here is the code:

```
void loop(){
  timeInSec = millis();  // Records time in seconds
  // if(lastRun > 0) {   // if i run this, only else statement is executed
  // delay(10000);
  // }
  if((timeInSec - lastRun) < 5000){  // Treshold time (if condition which runs when timeInSec is less than 5 seconds)
    // Some code
  }
  else{ // If treshold time exceeds (executes when timeInSec is > 5seconds)
   delay(10000);  // if i run this, only else statement is executed
   lastRun = timeInSec;
  }
}

```

Here the `else` statement executes once and control goes back `if` statement again. I want to pause the control at `else` statement for 10 seconds and then go back to `if` statement for further execution. Everytime the control should pause at `else` statement for 10 seconds. I have used `delay` in the `else` statement and in this case only `else` statement is being executed. The same happens if I use `delay` at the start of loop (as in code). I have tried without using `delay` but didn't succeed.

Thanks for the help!

# Answer
Do not try to change `millis()`. Instead, record the last time the second code (else statement) ran, and check whether that was more than five seconds ago:

```
void loop() {
    static uint32_t lastRun;
    uint32_t now = millis();
    if (now - lastRun < 5000) {
        // Some code
    }
    else {
        // Some code
        lastRun = now;  // record the time
    }
}

```

This is essentially the same technique used in the Blink without delay Arduino tutorial.
> 2 votes

---
Tags: arduino-uno, arduino-ide, c, time, millis
---


# Question
Title: Recursive list of files on SD card with indexing
I'm trying to create a way to make a recursive list of the long name of files from an SD card with an index so that I call the file I'd like. Right now, I'm having trouble getting the files to list (!CFile.open() is always returning true regardless of the number of files on the card)

```
#include<SPI.h>
#include "SdFat.h"
#include "FreeStack.h"

// SD card chip select pin.
const uint8_t SD_CS_PIN = 10;

SdFat sd;
SdFile file;
SdFile dirFile;

// Number of files found.
uint16_t numberOfFiles = 0;

// Position of file's directory entry.
uint16_t dirIndex[300];
//**Is there a way I make an array without allocating the size here?
//------------------------------------------------------------------------------
void setup()
{
  Serial.begin(38400);
  while (!Serial) {}

  // Initialize at the highest speed supported by the board that is
  // not over 50 MHz. Try a lower speed if SPI errors occur.
  if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50)))
  {
    sd.initErrorHalt();
  }
  if (dirFile.open("/", O_READ))
  {
  Serial.print("Reading: ");
  Serial.println();
  printDirectory(&dirFile, 0);
  }
}
void printDirectory (SdFile* CFile, int numTabs)
{
  while (file.openNext(CFile, O_READ))
  {
    if (file.isHidden()||file.)
    {
      //file hidden, skip
    }
    else
    {
      for (uint8_t i = 0; i < numTabs; i++)
      {
        Serial.print('\t');
      }
      if (file.isSubDir())
      {
        file.printName(&Serial);
        Serial.println();
        printDirectory(&file, numTabs++);
      }
      else
      {
        // Save dirIndex of file in directory.
        dirIndex[numberOfFiles] = file.dirIndex();
        // Print the file number and name.
        Serial.print(numberOfFiles++);
        Serial.write(' ');
        file.printName(&Serial);
        Serial.println();
      }
    }
  file.close();
  }

```

If someone could help me catch what I've got wrong, I'd like to get a second opinion.

Edit: Updated Code

Edit 2: I'm now getting the first level, but the second level is not printing I think I may be doing something wrong with pointers?

# Answer
> 3 votes
dirFile.open("/", ...) opens the root directory which always exist, even if there are no files.

You can check if there are files by checking openNext. If the first call returns false, there are no files or folders.

Some unrelated remarks:

* Name variables you use, with more than 1 character (so e.g. numberOfFiles instead of n)
* Do not increase a variable inside a Serial.print statement .. if you remove the 'test/debug' code, your sketch behaves differently.

Update:

I now see your question about the array. 300 is probably what you assume is the maximum number of files. Note that if 300 is passed, the sketch will crash.

What you can do to prevent this:

* Easy solution: stop storing files after 300. In this case, make 300 a constant.
* Solid solution: do not use a predetermined length array. However, this means some disadvantages:
    + You have to create a list structure and dynamically change the code.
    + This is slower (probably not an issue since SD card communication is much slower)
    + It can result in memory gaps, resulting in hard to solve memory problems later if the code is extended and more memory is needed.

I suggest you add some code, to stop storing at 300.

---
Tags: arduino-mega, programming, c++, sd-card
---


title: Using tinyGPS++ with millis errors

text:
# Question
Title: Using tinyGPS++ with millis errors
Hi I am trying to make search GPS (using tinGPSplus) every x time. The problem is when I do compile the code:

```
void loop()
{
    read=BP_mnger.pressedButton();
    navigateMenus(read);
    dealWithUsedEvents(getmenuUsed());
    setmenuUsed(0);

    if (isStarted && (GPSSearchPeriod<=millis()-oldMillisVallue)) {

        oldMillisVallue=millis();// if i comment this line it works
        Serial.print(F("oldMillisVallue: "));
        Serial.println(oldMillisVallue);
        while (ss.available() > 0){
            if (gps.encode(ss.read()))
                if (gps.location.isUpdated() || gps.date.isUpdated() || gps.time.isUpdated() || gps.altitude.isUpdated() || gps.satellites.isUpdated() || gps.hdop.isUpdated())
                    GPSSentence=makeGPSSentence( );
        }

    }

```

I get this:

```
oldMillisVallue: 22355
oldMillisVallue: 24356
oldMillisVallue: 26357
oldMillisVallue: 28358
oldMillisVallue: 30359

```

When I comment out:

```
oldMillisVallue=millis();// if i comment this line it works

```

I get this :

```
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
2000,0,0,4294967295,15,43,3,36,5,41,4.066298,48.269157,77,0.12,90,380,98,2,1,3
2000,0,0,4294967295,15,43,3,39,5,43,4.066298,48.269157,79,0.122200,92,380,98,2,1,3
------------------------
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0

oldMillisVallue: 0
oldMillisVallue: 0
2000,0,0,4294967295,15,43,4,39,5,43,4.066265,48.269126,80,0.12,94,380,101,3,2,5
2000,0,0,4294967295,15,43,4,41,5,45,4.066265,48.269127,82,0.121900,94,380,103,3,2,5
------------------------
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0
oldMillisVallue: 0

```

# Answer
> 4 votes
You're only reading from the serial port every `GPSSearchPeriod` milliseconds. That gives plenty of time for the small serial read buffer to overflow and lose the data.

Instead you should be reading *all the time* regardless of your desire to only do things periodically. Sure, *report* the data periodically, but you *must* read all the time *as well*.

---
Tags: arduino-uno, gps
---


# Question
Title: Lighting up LED lights on Arduino tank using Arduino transmitter
I am making an Arduino tank using the motor shield, more of a recon tank as it has no gun. And I'm using one Arduino board as the receiver and controller of the tank and the other as the transmitter. I'm thinking of adding lights to the build and want to remotely operated them. I don't know where to look at or start. Can someone help me?

# Answer
Well, Im going to see your question with good eyes and help you out giving you the properly guidance. With no sarcasm.

First of all you just would do some google searchs using the correct words.

To achieve the correct words you need to enumerate important things just doing the following quastions.

What do I have?

```
Arduino, Led

```

What do I want?

```
Controlling Led Remotely

```

So with these couple of question I could achieve the following sentence:

```
controlling led arduino remotely

```

This gave me the following good and usefull link with source code: http://www.instructables.com/id/Arduino-Control-LEDs-with-a-Remote-Control/

Now you can improve your serach and come back here, bringing us what you have done so far with a far more accurated techinical question like:

```
What is the best way to controlling LED remotely in the given situation?

```

And go on.

The most important thing to know is how to separate requirements from impediments. I think now you are fair well introduced about how to use this very good resource.
> 2 votes

---
Tags: arduino-uno
---


title: Understanding the ESP8266

text:
# Question
Title: Understanding the ESP8266
I've received my ESP8266-01 and playing with it I discovered that with a baudrate of 74880 I can get the boot modes and \`hy version, etc: ets Jan 8 2013,rst cause:1, boot mode:(3,0)

```
load 0x40100000, len 1856, room 16
tail 0
chksum 0x63
load 0x3ffe8000, len 776, room 8
tail 0
chksum 0x02
load 0x3ffe8310, len 552, room 8
tail 0
chksum 0x79
csum 0x79

2nd boot version : 1.5
  SPI Speed      : 40MHz
  SPI Mode       : DIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

rf cal sector: 249
rf[112] : 00
rf[113] : 00
rf[114] : 01

SDK ver: 1.5.4.1(39cb9a32) compiled @ Jul  1 2016 20:04:35
phy ver: 972, pp ver: 10.1

```

With this baudrate I'm not able to check the AT commands. Then, when I switch to a baudrate of 115200 I am able to communicate with the ESP:

```
Ai-Thinker Technology Co. Ltd.
ready
AT
OK
AT+CWL
ERROR
AT+CWJAP?
No AP
OK
AT+CWLAP?
ERROR
AT+CWLAP
+CWLAP:(4,"bbox2-7f0d",-88,"00:1 ",1,-46,0)
+CWLAP:(0,"PROXIMUS_FON",-94,"06: ec:6b",1,-47,0)
+CWLAP:(5,"PROXIMUS_AUTO_FON",-88,"0a: :ec:6b",1,-44,0)
+CWLAP:(3,"WiFi-2.4-BB3D-ext",-51,"00: 9a:38",1,-12,0)
+CWLAP:(3,"NGUYEN",-79,"e0:b ",11,-2,0)
+CWLAP:(0,"PROXIMUS_FON",-81,"42:6 ",11,0,0)
+CWLAP:(5,"PROXIMUS_AUTO_FON",-79,"42 ",11,0,0)
+CWLAP:(4,"WiFi-2.4-6858",-75,"4 e",11,1,0)
+CWLAP:(0,"PROXIMUS_FON",-89," ",11,-6,0)
OK

```

How is that possible that it has two different baudrates?

Thanks in advance,

# Answer
> How is that possible that it has two different baudrates?

Very simple. Exactly the same as the Arduino.

If you put:

```
Serial.begin(9600);

```

in your program then your sketch runs with the serial port at 9600 baud. However, just before then, the bootloader runs at 115200 baud for a few seconds listening for instructions from the PC.

There's no magic there.

You can even do it yourself:

```
Serial.begin(9600);
Serial.println("Hello at 9600 baud");
Serial.flush();
Serial.end();
Serial.begin(115200);
Serial.println("Hello at 115200 baud");
Serial.flush();
Serial.end();

```

The baud rate isn't fixed. It's whatever the firmware that is running at that precise moment deems it to be - whether that is the bootloader, the AT firmware, or your own custom sketch.
> 1 votes

---
Tags: serial, esp8266, baud-rate
---


# Question
Title: Button not working - Arduino Due project (MiniEngine v2)
I am building Arduino Due based project called MiniEngine v2 (an open-source motion control software for timelapse photography).

The project is not very active anymore but there are still all the documentation at github. Project owner had webshop where he sold MiniEngine shields for arduino but they are not available anymore. There was gerber files available at project github page so I orderer PCB's form seeed.com.

Project's Github page is at: https://github.com/airiclenz/miniEngine2

Everything seems to work ok but one of the buttons is not working. There is only 2 buttons and one rotary encoder.

I think the reason why the button is not working is that the output voltage for button from 74HC14N (hex smith trigger) is too low (I am not very good at electronic so I might be totally wrong.

I tried to measure values with voltage meter and here is the result what I got for those two buttons:

Here are the values in written format ( I took measurement from SN74HC14N )

* btn\_2 (pin9 input, pin8 output)
* btn\_1 (pin11 input, pin10 output)

**SETTINGS BUTTON** (btn\_2) -\> **this one works** fine

* 1) button up - metering from input pin 11 =\> 3.26
* 2) button down -metering from input pin 11 =\> 0
* 3) button up - metering from output pin 10 =\> 0.6
* 4) button down - metering from output pin 10 =\> 2.38

**START/BACK BUTTON** (btn\_1) -\> **this one does not work**

* 1) button up - metering from input pin 9 =\> 3.26
* 2) button down - metering from input pin 9 =\> 0
* 3) button up - metering from output pin 8 =\> 1.43
* 4) button down - metering from output pin 8 =\> 1.53

Here is how the buttons are initialized:

```
    void input_init() {

  // set pin modes
  pinMode(PIN_ROTARY_PRESS, INPUT);
  pinMode(PIN_KEY_1, INPUT);
  pinMode(PIN_KEY_2, INPUT);

  // attach interrupts for the keys
  attachInterrupt(PIN_ROTARY_PRESS, input_interrupt_keyRotary_press,  RISING);
  attachInterrupt(PIN_KEY_1,        input_interrupt_key1,             RISING);
  attachInterrupt(PIN_KEY_2,        input_interrupt_key2_press,       RISING);

  // attach interrupts to both encoder pins for every state change
  attachInterrupt(PIN_ROTARY_A,     input_interrupt_rotary,           CHANGE);
  attachInterrupt(PIN_ROTARY_B,     input_interrupt_rotary,           CHANGE);

  // set the initial rotary values & configurations
  rotary.setPosition(0);
  rotary.setKeyMode(true);
  rotary_old_pos = 0;
}

```

And here is function for btn\_1 press that is never called (except once in powering the shield/arduino due)

```
void input_interrupt_key1() {

  if ((key_1_time + DEF_INPUT_DEBOUNCE) < millis()) {

    key_1_time = millis();
    setBit(input_status, BIT_2);

  }
}

```

I can only use 2 links in posts (I do not have 10 reputation) so you can find the code for inputs at Github (link above). (folder ***MiniEngine2/Software/miniEngine2/mE2\_input.ino***)

All code files are at Sotfware at folder: ***MiniEngine2/Software/miniEngine2***

I have put Serial.println command in code and nothing is printed when btn\_1 is pressed. When I plug power on then the btn\_1 is triggered once...

Here is link to the the schematic for that shield ( it is quite big so that's why I did not embed the photo):

Schematic for shield is at Github folder : ***Hardware/miniE shield v2 revB BED board - schematic.pdf***

Here is also link to the video where you can see how I took the measurements: https://youtu.be/wFR7P65qMGA

Please ask if I need to provide more information...

# Answer
> 1 votes
It was the Arduino Due issue. Arduino digital pin 43 was faulty or something. I managed to change 43 to 53 and now the button works...

---
Tags: button
---


title: A1 was not declared in the scope

text:
# Question
Title: A1 was not declared in the scope
I'm trying to put all my settings in a config.h file and then `#include` it in the Arduino sketch.

Here's what my config.h looks like:

**RobotConfig.h**

```
#ifdef BOT
    //hardware pins
    int motor1Pin = 9; //s0
    int motor2Pin = 10; //s1

    //pins for light
    int light2 = A4;
    int light3 = A2; //right
    int light1 = A1; //left

```

And here's what .ino sketch looks like:

```
#define BOT
#include "RobotConfig.h"

void setup() {
  //Light INIT
  pinMode(light1, OUTPUT); //left light with motor1/s1 in front
  pinMode(light2, OUTPUT); //middle light with motor1/s1 in front
  pinMode(light3, OUTPUT); //right light with motor1/s1 in front
  ...
}

```

This compiles fine on my Mac but I'm trying to compile this on Raspberry Pi (Pi3 with new Jessie install with `sudo apt-get install arduino`) and get an error while doing so. The error says:

> A1 was not declared in the scope etc.

What am I missing?

# Answer
> 3 votes
RobotConfig.h needs to include Arduino.h in order to have those constants.

---
Tags: arduino-uno, sketch, mac-os, raspberrypi
---


# Question
Title: Servo Driven Through Custom Library Not working Properly
I'm a little new to Arduino, but not to programming or electronics in general. I'm working on a library that will be more fleshed out later, but I'm having issues getting the basics working properly.

The following code produces the desired behavior if a servo is attached to pin 3:

```
#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(3);
}

void loop() {
  myServo.write(1);
  delay(1000);
  myServo.write(45);
  delay(1000);
  myServo.write(90);
  delay(1000);
  myServo.write(135);
  delay(1000);
  myServo.write(180);
  delay(1000);
}

```

However, when I try to implement similar functionality in my own library the servo locks and just sort of grinds. Here's the header file:

```
#ifndef MotorControl_h
#define MotorControl_h

#include "Arduino.h"
#include "Servo.h"

class MotorControl
{
  public:
    MotorControl(int north, int south, int west, int east);
    void setNorth(int value);
    void setSouth(int value);
    void setWest(int value);
    void setEast(int value);
    int getNorth();
    int getSouth();
    int getWest();
    int getEast();
  private:
    Servo _north;
    Servo _south;
    Servo _west;
    Servo _east;
    int _northVal;
    int _southVal;
    int _westVal;
    int _eastVal;
};

#endif

```

And here's the .cpp file:

```
#include "Arduino.h"
#include "MotorControl.h"
#include "Servo.h"

MotorControl::MotorControl(int north, int south, int west, int east)
{
  _north.attach(north);
  _south.attach(south);
  _west.attach(west);
  _east.attach(east);
  _northVal = 0;
  _southVal = 0;
  _westVal = 0;
  _eastVal = 0;
}

void MotorControl::setNorth(int value)
{
  _north.write(value);
  _northVal = value;
}

void MotorControl::setSouth(int value)
{
  _south.write(value);
  _southVal = value;
}

void MotorControl::setWest(int value)
{
  _west.write(value);
  _westVal = value;
}

void MotorControl::setEast(int value)
{
  _east.write(value);
  _eastVal = value;
}

int MotorControl::getNorth()
{
   return _northVal;
}

int MotorControl::getSouth()
{
  return _southVal;
}

int MotorControl::getWest()
{
  return _westVal;
}

int MotorControl::getEast()
{
  return _eastVal;
}

```

And finally, the code using the above library which should produce the same behavior as the code up top, but does not:

```
#include <MotorControl.h>

MotorControl mc(3, 5, 6, 9);

void setup() {}

void loop() {
  mc.setNorth(1);
  delay(1000);
  mc.setNorth(45);
  delay(1000);
  mc.setNorth(90);
  delay(1000);
  mc.setNorth(135);
  delay(1000);
  mc.setNorth(180);
  delay(1000);
}

```

I'm not sure what else to add ... this is running on an Uno R3.

Edit: This is interesting. I've tried the code from this example: How do I initialize a servo object in my own library? which works out just fine. I'm still not sure that I see what I'm doing incorrectly here. I see the differences between my code and the example, but not how they are causing problems.

If it's worth mentioning, I've also stored my library in the libraries folder. Just throwing out any random detail I can think of.

# Answer
In C++, when an object is declared as a member of another object, the **constructor method of the inner object must be called explicity** (see constructors and member initializer lists).

In your code, properties of *Servo* type can be constructed within the header of the *MotorControl* constructor:

```
MotorControl::MotorControl(int north, int south, int west, int east)
    : _north(), _south(), _west(), _east()
{
  _north.attach(north);
  _south.attach(south);
  _west.attach(west);
  _east.attach(east);
  _northVal = 0;
  _southVal = 0;
  _westVal = 0;
  _eastVal = 0;
}

```
> 1 votes

# Answer
When you create your instance at global scope then you have no control over when exactly the constructor gets called. If it gets called before init() runs then your attach lines won't work out. You should have a begin method in your class that handles attaching the servos and call that method from setup.
> 0 votes

---
Tags: arduino-uno, library, servo
---


title: Arduino Esplora

text:
# Question
Title: Arduino Esplora
So I'm trying to turn my Arduino Esplora into a controller, and my first step is to understand how the controller works. I've copied and pasted this code into the Arduino 1.8.2 IDE.

```
Esplora.writeRGB(255, 255, 255); // sets red, green and blue all to full brightness

```

But I get an error saying,

exit status 1 'Esplora' does not name a type

Please explain why it's doing this.

# Answer
You probably forgot:

* To include Esplora.h in your sketch.
* To select "Esplora" for the board.
> 0 votes

---
Tags: programming
---


# Question
Title: Control a 5 volt water pump with an Arduino
I want to control (only on/off) a small water pump (5 V, 200 mA max.) with my Arduino.

I read something about NPN transistor, because the output pins of the Arduino can't supply enough current to the pump. However, I don't know how to choose the right transistor and how to connect it with my Arduino and my water pump.

# Answer
To use an NPN, connect a power rail of 5V to the pump's positive terminal, and from its negative terminal wire it to the transistor's collector pin. Wire emitter to GND, and place a \>=220 ohms resistor between your arduino control pin and the transistor *base*.

If instead using an N-channel MOSFET, wire load to drain, source to GND, and use a 4K7 pull-down on gate.

Also add a diode, with its anode at the pump's negative terminal, and cathode (white ring) at the positive terminal.
> 3 votes

---
Tags: arduino-uno, transistor
---


title: Source code for Arduino “firmware”?

text:
# Question
Title: Source code for Arduino “firmware”?
I am wondering if anyone here knows where the source code for the Arduino "firmware" is available for reading? I think it must be more than the 'boot loader' but I am not sure. Thanks!

p.s. I assume this kind of question is ok here, even though it's not ok on StackOverflow?

# Answer
The “firmware” is whatever program a microcontroller runs. On an Arduino, it is typically the program **you** write and upload into the microcontroller's flash memory.

If by “firmware” you mean the core library (the source code of `pinMode()`, `digitalRead()` and so on), it is here:

https://github.com/arduino/ArduinoCore-avr

If by “firmware” you mean the bootloader (the small program that runs at reset and will accept the upload of your firmware), is is here:

https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/bootloaders/optiboot

Note that this is valid for the AVR-based Arduinos. The cores and bootloaders used in other architectures are stored is separate repositories, e.g.

https://github.com/arduino/ArduinoCore-sam
> 7 votes

# Answer
If you are looking for the Flash Firmware, I think the github project documentation is pretty well developed, here:

https://github.com/arduino/Arduino

This is a good introduction to build and flash your Arduino UNO:

http://angryelectron.com/arduino-firmware/

And here a good start to build you own Arduino on a breadboard:

https://www.arduino.cc/en/main/standalone
> 4 votes

---
Tags: arduino-uno
---


title: Write data on the computer with Arduino

text:
# Question
Title: Write data on the computer with Arduino
I wonder if in Arduino you can modify the computer eg create a text file inside the computer using Arduino. Is there any way you can do this or something like that?

Because you can use the library `#include <stdio.h>`, which is a C++ language library to handle file on the computer.

In Arduino maybe you can create files on the computer using pointers or a library? Because using the library `"Keyboard.h`" you can handle the computer. The Keyboard library can interact with the computer by typing on the computer

I'm in doubt, I need your knowledge.

# Answer
> 2 votes
The arduino can't directly modify the contents of the PC hard drive, the ability for a peripheral device to do this would be considered a massive security flaw in the PC operating system.

Having said that there are a few ways to do it:

To save a text file without anything special on the PC:
Have the Arduino act as a keyboard. Send (windows key + R) (pause) notepad \< enter \> (pause) \[ The text you wish to save to the PC \] (alt-f) s \< file name \> \< enter\>
This does require the PC to be unlocked (or you send the unlock key sequence first) and setting the directory to save to or overwriting a file could get tricky but should be possible if you work out the correct key sequence. The (windows key + r) combination is very powerful and also very dangerous. It makes it trivial to wipe the entire computer so use it with care.

To save a binary file to the PC:
Set up the arduino to act as a serial port. Start the terminal program of your choice and set it to log to a file. Send the data from the arduino. On the PC wait until the transfer is complete and then save the log file.

To read/save/modify any file without user interaction:
Set up the arduino to act as a serial port. Write a desktop PC application that takes the data from the Arduino. Define a protocol that allows the arduino to to specify the filename and what to do with it. The arduino doesn't directly access any files, instead it sends the commands to an application running on the PC, that application then performs the required file operations.

Alternative way to read/save/modify any file without user interaction:
Connect the arduino to the PC using USB. Exploit a flaw in the PC operating system to install a virus on the PC that gives you full control over the computer.

# Answer
> 1 votes
The keyboard library just sends key presses to the computer like a keyboard. From the PCs point of view it's no different from you banging on the keyboard in front of it. The Arduino can't control anything on the computer and it can't run any code on the computer. Now if you can do what you want completely from the keyboard then arduino could send those same keypresses. But the Arduino has no access to the PCs operating system or file system.

# Answer
> 1 votes
There are a number of serial-terminal programs that run on your PC (and pretty much any OS) that will copy the data they receive to a file. I use CoolTerm on MacOS. I think Windows HyperTerminal offers that capability as well on Windows. You have to start the terminal program on the PC, set it to capture, and open the capture file yourself - the Arduino can't cause the PC to do that - but once you've done it, the terminal program will copy all output from the Arduino to the capture-file. You might also have to set the PC to not sleep, if you need it to capture data without you being present.

---
Tags: arduino-uno
---


# Question
Title: ESP8266 proper power circuit for avoid reset issue
I am using an ESP8266 in a project which will be on for at least 18 hours a day. I'm using an Arduino 3.3V power supply to feed the ESP8266.

The issue I'm facing is a reset issue. It sometimes disconnects from the hotspot automatically. I have heard this could be because the ESP8266 draws more power than the Arduino's regulator is able to supply.

I want to know what will be the proper circuit to power the ESP8266.

I know I have to use an AMS1117 regulator, but I also know I have to use capacitors too. How would I configure the AMS1117 with capacitors to properly power an ESP8266?

# Answer
You don't "need" an AMS1117 regulator. You *need a power source that can supply enough current.* One *example* is an AMS1117-33, although it's not a great one as far as efficiency goes (though it is simple).

The basic circuit is to have a 10µF capacitor on both the input and output of the regulator - that should be enough for most uses.

simulate this circuit – Schematic created using CircuitLab

Powered from more than around 5V the AMS1117-33 would need some heatsinking. You can also add some smaller (100nF) capacitors in parallel with the 10µF ones if you want to improve high frequency response.

You can pick modules up with this circuit on from eBay for a dollar.

A better power source would be a "buck" switching regulator. These are far more efficient and generate much less heat. It's harder to search for these on eBay since all the AMS1117-33 modules seem to be labelled erroneously as "buck" regulators (which they so are not!), so be careful when looking around. A true "buck" regulator will have an inductor on it. Here's one example.
> 3 votes

---
Tags: esp8266, power
---


# Question
Title: Optimizing Arduino File Selection from SD card
the following code will display the files on an SD card in an Arduino and allow the user to open a file of their choosing. Here's the code with a walkthrough of what it does.

In the Init state, I call the libraries needed to run the code

```
// Example use of lfnOpenNext and open by index.
#include<SPI.h>
#include "SdFat.h"
#include "FreeStack.h"

// SD card chip select pin.
const uint8_t SD_CS_PIN = 10;

SdFat sd;
SdFile dirFile;
SdFile file;

// Number of files found.
uint16_t numberOfFiles = 0;

```

**This is the area of the real problem, calling** `SdFile parIndex[50];` **Takes a large amount of dynamic memory. For number of files on an SD card, this is a pretty small number, so I need to get at something better**

```
// Position of file's directory entry.
uint16_t dirIndex[50];
SdFile parIndex[50];
//------------------------------------------------------------------------------

```

In the Setup phase, we make sure the SD card is plugged in and, if it is, we call the function to give the files on the SD card.

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

  // Initialize at the highest speed supported by the board that is
  // not over 50 MHz. Try a lower speed if SPI errors occur.
  if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50)))
  {
    sd.initErrorHalt();
  }
  if (dirFile.open("/", O_READ))
  {
  printDirectory(dirFile, 0);
  }
}

```

The printDirectory function (This is the part most open to edits, if there's any way to improve performance here, please let me know as well).

```
void printDirectory (SdFile CFile, int numTabs)
{
  SdFile file;
  while (file.openNext(&CFile, O_READ))
  {
  if (file.isHidden()||false)
    {
      //file hidden, skip
    }
    else
    {
      for (uint8_t i = 0; i < numTabs; i++)
      {
        //create tabs for spacing
        Serial.print('\t');
      }
      if (file.isSubDir())
      {
        SdFile SubDirFile;
        printDirectory(SubDirFile, numTabs+1);
      }
      else
      {
        // Save dirIndex of file in directory.
        dirIndex[numberOfFiles] = file.dirIndex();
        parIndex[numberOfFiles] = CFile;
        // Print the file number and name.
        Serial.print(numberOfFiles);
        Serial.write(' ');
        file.printName(&Serial);
        Serial.println();
        numberOfFiles++;
      }
    }
  file.close();
  }
}

```

---

This is the user interface portion, it was largely slapped together as a proof of concept for the above code. As it's written, the code only accepts index values 0-9, but my actual program could call any index value.

```
void loop() {
  int c;

  // Read any existing Serial data.
  do {
    delay(10);
  } while (Serial.available() && Serial.read() >= 0);
  Serial.print(F("\r\nEnter File Number: "));

  while (!Serial.available()) {
    SysCall::yield();
  }
  c = Serial.read();
  uint8_t i = c - '0';
  if (!isdigit(c) || i >= numberOfFiles) {
    Serial.println(F("Invald number"));
    return;
  }

```

After making sure that the input value exists, it calls up the arrays that contain the parent's directory SdFile object and the index of the desired file.

```
  Serial.println(i);
  if (!file.open(&parIndex[i], dirIndex[i], O_READ)) {
    sd.errorHalt(F("open"));
  }
  Serial.println();

  char last = 0;

  // Copy up to 500 characters to Serial.
  for (int k = 0; k < 500 && (c = file.read()) > 0; k++)  {
    Serial.write(last = (char)c);
  }
  // Add new line if missing from last line.
  if (last != '\n') {
    Serial.println();
  }
  file.close();
  Serial.flush();
  delay(100);
}

```

The main issue I have is that `SdFile parIndex[50];` uses 22% of my dynamic memory vs the rest of the program using 12%. How can I rewrite my code to not require keeping the SDFile objects in dynamic memory?

For anyone unfamiliar, documentation for the SdFat library can be downloaded from that link.

---

Edit: In terms of use: The SD files are .csv files that store speed and time parameters for running a motor test. Each test lasts for a few minutes to hours.

# Answer
> 1 votes
You have several possibilities:

* Do not store the names of all files, but use the index and iterate through all files again. Disadvantage: this takes a lot of time (every time you need the file name)
* Add SRAM to the Arduino (e.g. 23LC1024, 23K256), depending on your memory needs. Disadvantage: you have to 'manage' this memory yourself.
* If you know something about the file names, you might generate the name. Probably it's not the case, but just to add another option. E.g. if you know that file nr 10 will always be called 'File10.txt', you can 'generate' the name.
* I don't know exactly how you want to use the file names, but you might store only the latest x files used, to prevent having to iterate again reading the SD card. Of course, this only helps if there is a high chance the last x files are used more than the non recent files.

Update: If you need to read the files while leaving the Arduino unblocked, you have to incorporate it in your loop, but don't read all the files in a loop. Something in pseudo code like:

bool readingSd = false; // True between reading first and last file uint16\_t lastTimeRead = 0; // Last time read

```
void loop()
{
   // Check if file read needed (initial or one hour past, I don't take
   // overflow into account
   if (lastTimeRead == 0 || (lastTimeRead + 1000 * 60 < millis())
   {
      checkReadFile();
   }

   // Perform your normal code... this will run between processing/reading
   // one file/dir.
   ...
}

void ProcessSingleFile()
{
   readingSd = true; // Within reading first/last file
   "read/process ONE file or dir (without containing files)";
   if ("last file read")
   {
       readingSd = false;
       lastTimeRead = millis(); // Move to top to prevent reading time
         // between first/last to take into account
   }
}

```

---
Tags: arduino-mega, sd-card, code-optimization, performance
---


# Question
Title: How to change a code for an I2C 16x2 to a 20x4?
I have found a sketch that someone wrote for a rotary encoder controlled LCD menu.

The code is for an I2C that is 16x2 and I have an I2C that is 20x4. With the code that I found, the layers are all 3 lines, so when they appear on the LCD, it is on 2 "pages". Since my LCD is 20x4, I don't need to scroll to a second page.

How do I get that third line on the same page as the first two? I am also still looking at other sketches people have posted for LCD menus, but most of them seem to have outdated libraries or are for 16x2 screens.

```
#include <OneButton.h>
#include <Encoder.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C  lcd(0x27, 2,1,0,4,5,6,7);

// ROTARY ENCODER
long oldPosition  = 0;
int encoderDTpin = 34;
int encoderCLKpin = 30;
Encoder myEnc(encoderDTpin, encoderCLKpin);

int buttonPin = 26;
OneButton button0(buttonPin, true);

// MENU ARRAY
// First number in array = amount of menu items in root layer. Same goes for next layer.
//(Example: first value in array is 4. This means Layer 0 has 4 menu items. Layer 1 has only 2 menu items.)
// First number infront of menu text is the layer number that item points to. (Example: 1_Rotation points to Layer 1)
// Second number infront of menu text is the number of the value connected to that menu item in the values array.
//(Example: 15Direction points to position 5 in the values array)

String menu[] = {"4","1__Rotation","056Active","3__Watches","4__Item4",       // Layer 0
                 "3","100Rotations","105Direction","109Speed",                // Layer 1
                 "3","256Active","2__Item2.2","2__Item2.3",                    // Layer 2
                 "4","4__Watch 1","3__Watch 2","3__Watch 3","3__Watch 4",     // Layer 3
                 "2","4__Item3.1.1","4__Item3.1.2"};                          // Layer 4

// VALUES ARRAY
// TYPES, 1 numeric / 2 character value range
// 1 - type,value,increments,min,max
// 2 - type,starting value in options array,lowest value options array,max value options array
int values[] = {1,11,25,50,1450, //0-4 WATCH1
                2,2,0,2,         //5-8
                1,600,25,75,600, //9-13

                1,11,25,50,1450, //14-18 WATCH2
                2,2,0,2,         //19-22
                1,600,25,75,600, //23-27

                1,11,25,50,1450, //28-32 WATCH3
                2,2,0,2,         //33-36
                1,600,25,75,600, //37-41

                1,11,25,50,1450, //42-46 WATCH4
                2,2,0,2,         //47-50
                1,600,25,75,600, //51-55

                2,4,3,4,         //56-59 WATCH1 ACTIVE
                2,4,3,4,         //60-63 WATCH2 ACTIVE
                2,4,3,4,         //64-67 WATCH3 ACTIVE
                2,4,3,4};        //68-71 WATCH4 ACTIVE

String options[] = {"CW","CCW","MIX",
                    "No","Yes"};

// Custom character for LCD.
byte cursor[8] = {
  0b10000,
  0b10000,
  0b01000,
  0b00110,
  0b01000,
  0b10000,
  0b10000,
  0b00000
};

byte watch[8] = {
  0b01110,
  0b01110,
  0b11011,
  0b10001,
  0b10001,
  0b11011,
  0b01110,
  0b01110
};

int currentType = 0;
int value = 0;
int numIncr = 0;
int Min = 0;
int Max = 0;

int currentLayer = 0;
int lastLayer = 99;
int currentLength = menu[0].toInt();
int currentPosition = 0;
int currentSelect = 1;
int currentChange = 0;
String currentPress = "";
float currentlcdLayerFloat = 0;
int currentlcdLayer = 0;
int lastlcdLayer = 0;
int lcdUpdated = 0;
int currentLine = 0;
int cursorLayer = 0;
int cursorPosition = 0;
int valueLength = 0;

/*
int homeScreen = 1;

String currentTime = "00:00:00";
String lastTime = "00:00:00";
String temptime = "00";
String currentDate = "";

int watch1active = values[56] - 3;
int watch2active = values[60] - 3;
int watch3active = values[64] - 3;
int watch4active = values[68] - 3;
int watch1rotations = 0;
int watch2rotations = 0;
int watch3rotations = 0;
int watch4rotations = 0;
int watch1left = values[1];
int watch2left = values[15];
int watch3left = values[29];
int watch4left = values[43];
String temprotationsleft = "";
*/

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

  // Map rotary button to actions single and doubleclick.
  button0.attachClick(singleClick);
  button0.attachDoubleClick(doubleClick);

  lcd.begin (16,2);
  lcd.setBacklightPin(3,POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.home();

  // Create the custom character.
  lcd.createChar(0, cursor);
  lcd.createChar(1, watch);

  lcd.setCursor (2,0);
  lcd.print("Watch Winder");
  delay(1000);
  clearLine(0);

  // Set the select cursor on the first line.
  cursorLayer = 0;
  lcd.setCursor (0,cursorLayer);
  writeCursor();

}

void loop() {

    // Listen to button presses.
    button0.tick();

    // Listen if the rotary encoder moves.
    rotary_check();

    // Print the LCD menu.
    lcdMenu();

}

void singleClick() {

  // IF current layer number is the same as redirect layer number, we stay on the same layer
  // AND no item is selected in the menu
  // AND the selected item has a redirect to another layer
  if(currentLayer == menu[currentPosition + currentSelect].substring(0,1).toInt()
      && menu[currentPosition + currentSelect].substring(1,3) != "__" && currentPress == ""){

    currentPress = menu[currentPosition + currentSelect].substring(3);
    currentChange = menu[currentPosition + currentSelect].substring(1,3).toInt();

    Serial.println("Currentpress: " + currentPress);

    currentType = values[currentChange];
    value = values[currentChange + 1];

    // Type select change is numeric
    if(currentType == 1){
      Min = values[currentChange + 3];
      Max = values[currentChange + 4];
      numIncr = values[currentChange + 2];

      Serial.println("Currentvalue: " + String(value));
      Serial.println("Increments: " + String(numIncr));
      Serial.println("Min: " + String(Min));
      Serial.println("Max: " + String(Max));

      valueLength = String(value).length();

    // Type select change is character range
    } else if(currentType == 2){
      Min = values[currentChange + 2];
      Max = values[currentChange + 3];

      Serial.println("Currentvalue: " + options[value]);
      Serial.println("Options: ");

      for (int i=Min; i <= Max; i++){
        Serial.println(options[i]);
      }

      valueLength = options[value].length();

    }

    clearSelect();
    cursorPosition = 15 - valueLength;
    lcd.setCursor(cursorPosition,cursorLayer);
    writeCursor();

  // ELSE IF something is selected in the menu, and the button is pressed again. We deselect the item.
  } else if(currentPress != ""){

    currentValues();
    currentPress = "";
    currentChange = 0;

    clearChar(cursorPosition,cursorLayer);
    lcd.setCursor(0,cursorLayer);
    writeCursor();

  // IF nothing is selected and nothing will be deselected, move to the redirect layer listed in the first position of the array.
  } else {

    currentLayer = menu[currentPosition + currentSelect].substring(0,1).toInt();
    currentSelect = 1;
    currentlcdLayerFloat = 0;
    currentlcdLayer = 0;
    lastlcdLayer = 0;

    clearSelect();
    cursorLayer = 0;
    lcd.setCursor (0,cursorLayer);
    writeCursor();

  }

}

// Reset to layer 0.
void doubleClick() {
  if(currentLayer == 0){
    currentLayer = 0;
    currentSelect = 1;
    currentlcdLayerFloat = 0;
    currentlcdLayer = 0;
    lastlcdLayer = 0;

    clearSelect();
    cursorLayer = 0;

    lcd.clear();
    lcdUpdated = 0;
  }
  if(currentLayer != 0){
    currentLayer = 0;
    currentSelect = 1;
    currentlcdLayerFloat = 0;
    currentlcdLayer = 0;
    lastlcdLayer = 0;

    clearSelect();
    cursorLayer = 0;
    lcd.setCursor (0,cursorLayer);
    writeCursor();
  }
}

void rotary_check(){

  // Constantly read the position of the rotary encoder
  long newPosition = myEnc.read() / 4;

  // IF the new position of the encoder is different then the old position
  if (newPosition != oldPosition) {

    // IF nothing has been selected in the menu
    if(currentPress == ""){

      if(newPosition > oldPosition && currentSelect < currentLength){
        clearSelect();
        currentSelect++;
        currentlcdLayerFloat = currentlcdLayerFloat + 0.5;
        currentlcdLayer = currentlcdLayerFloat;

        cursorSelect();

        lcd.setCursor (0,cursorLayer);
        writeCursor();
        Serial.println("> " + menu[currentPosition + currentSelect].substring(3));

      } else if (newPosition < oldPosition && currentSelect != 1){
        clearSelect();
        currentSelect--;
        currentlcdLayerFloat = currentlcdLayerFloat - 0.5;
        currentlcdLayer = currentlcdLayerFloat;

        cursorSelect();

        lcd.setCursor (0,cursorLayer);
        writeCursor();
        Serial.println("> " + menu[currentPosition + currentSelect].substring(3));

      }

      if(lastlcdLayer != currentlcdLayer){
        lcdUpdated = 0;
      }

      lastlcdLayer = currentlcdLayer;
      oldPosition = newPosition;

    // IF something has been selected in the menu, we are going to change the value of a menu item.
    } else if(currentPress != ""){

      lcd.setCursor(cursorPosition + 1,cursorLayer);
      // IF the new position is HIGHER then the old position
      if(newPosition > oldPosition){
        clearChar(cursorPosition,cursorLayer);

        // IF the selected item has a change type that is NUMERIC.
        // AND the MAXIMUM of the selected item has not been reached.
        // We change the value UPWARDS with the icrements listed in the array.
        // SAME applies for next ELSE IF, just for the change type character. And the next ELSE IF we just go down.
        if(currentType == 1 && value < Max){
            value = value + numIncr;
            values[currentChange + 1] = value;
            Serial.println(value);

            clearValue();
            valueLength = String(value).length();
            cursorPosition = 15 - valueLength;
            lcd.setCursor(cursorPosition + 1,cursorLayer);
            lcd.print(value);
          }

        if(currentType == 2 && value < Max){
            value++;
            values[currentChange + 1] = value;
            Serial.println(options[value]);

            clearValue();
            valueLength = options[value].length();
            cursorPosition = 15 - valueLength;
            lcd.setCursor(cursorPosition + 1,cursorLayer);
            lcd.print(options[value]);
          }
          lcd.setCursor(cursorPosition,cursorLayer);
          writeCursor();

      } else {
        clearChar(cursorPosition,cursorLayer);

        if(currentType == 1 && value > Min){
          value = value - numIncr;
          values[currentChange + 1] = value;
          Serial.println(value);

          clearValue();
          valueLength = String(value).length();
          cursorPosition = 15 - valueLength;
          lcd.setCursor(cursorPosition + 1,cursorLayer);
          lcd.print(value);
        }

        if(currentType == 2 && value > Min){
            value--;
            values[currentChange + 1] = value;
            Serial.println(options[value]);

            clearValue();
            valueLength = options[value].length();
            cursorPosition = 15 - valueLength;
            lcd.setCursor(cursorPosition + 1,cursorLayer);
            lcd.print(options[value]);
          }
          lcd.setCursor(cursorPosition,cursorLayer);
          writeCursor();

      }

      oldPosition = newPosition;
    } else {
      oldPosition = newPosition;
    }

  }
}

void lcdMenu(){
  if (lastLayer != currentLayer || lcdUpdated == 0){

    currentLength = menu[0].toInt();
    currentPosition = 0;

    for (int i=0; i < currentLayer; i++){
      currentPosition = (menu[currentPosition].toInt() + 1) + currentPosition;
      currentLength = menu[currentPosition].toInt();
    }

    clearMenu();
    int tempPosition = currentPosition;

    if(currentlcdLayer != 0){

      currentPosition = currentPosition + (currentlcdLayer * 2);
    }

    Serial.println("LCD-------------");

    for (int i=1; i <= 2; i++){
      lcd.setCursor (1,i - 1);
      lcd.print(menu[currentPosition + i].substring(3));

      currentType = 0;
      value = values[menu[currentPosition + i].substring(1,3).toInt() + 1];
      String tempvalue = "";

      if(menu[currentPosition + i].substring(1,3) != "__" && menu[currentPosition + i].substring(1,3) != ""){
        currentType = values[menu[currentPosition + i].substring(1,3).toInt()];
        if(currentType == 1){
          lcd.setCursor (16 - String(value).length(),i - 1);
          lcd.print(value);
          tempvalue = " "+ String(value);
        }else if(currentType == 2){
          lcd.setCursor (16 - options[value].length(),i - 1);
          lcd.print(options[value]);
          tempvalue = " "+ options[value];
        }

      }

      Serial.println(menu[currentPosition + i].substring(3) + tempvalue);
    }
    Serial.println("----------------");

    currentPosition = tempPosition;
    lastLayer = currentLayer;
    lcdUpdated = 1;

    /**
    Serial.println("Layer " + String(currentLayer + 1));
    Serial.println("Layer length " + String(currentLength));
    Serial.println("Layer position " + String(currentPosition));
    **/

  }
}

void currentValues(){

  Serial.println("Currentpress: " + currentPress);

  if(currentType == 1){
      Serial.println("Currentvalue: " + String(value));
      Serial.println("Increments: " + String(numIncr));
      Serial.println("Min: " + String(Min));
      Serial.println("Max: " + String(Max));

    } else if(currentType == 2){
      Serial.println("Currentvalue: " + options[value]);
      Serial.println("Options: ");

      for (int i=Min; i <= Max; i++){
        Serial.println(options[i]);
      }
    }
}

void clearChar(int charPosition, int line){
  lcd.setCursor (charPosition,line);
  lcd.print(" ");
}

void clearLine(int line){
  lcd.setCursor (0,line);
  lcd.print("                ");
}

void clearMenu(){
  lcd.setCursor (1,0);
  lcd.print("               ");
  lcd.setCursor (1,1);
  lcd.print("               ");
}

void clearSelect(){
  lcd.setCursor (0,0);
  lcd.print(" ");
  lcd.setCursor (0,1);
  lcd.print(" ");
}

void cursorSelect(){
  switch (currentSelect){
          case 1:
            cursorLayer = 0;
            break;
          case 2:
            cursorLayer = 1;
            break;
          case 3:
            cursorLayer = 0;
            break;
          case 4:
            cursorLayer = 1;
            break;
          case 5:
            cursorLayer = 0;
            break;
          case 6:
            cursorLayer = 1;
            break;
        }
}

void writeCursor(){
  lcd.write(byte(0));
}

void clearValue(){
  for (int i = 16 - valueLength; i <= 16; i++){
        lcd.setCursor (i,cursorLayer);
        lcd.print(" ");
      }

}

```

# Answer
Change line

```
lcd.begin (16,2);

```

to

```
lcd.begin (20,4);

```

then position cursor as you did for lines 0 & 1.
> 1 votes

---
Tags: arduino-mega, i2c, rotary-encoder
---


# Question
Title: How can I load fonts into Adafruit GFX for TFT display (ILI9341)
I get a compile error when I try to set a different font in Adafruit GFX on a TFT display on my Arduino Uno.

I'm testing a new TFT shield for Arduino equipped with an ILI9341 by using the Adafuit GFX libraries and examples. The test program supplied with the library works fine out of the box displaying text and all kind of drawings on the screen.

However, the standard font built into the Adafruit GFX library is "blocky" to save memory space. They do provide other fonts, but I get an error when I try to invoke them.

The segment of code that throws the compile error is this one:

```
unsigned long testText1() {
  tft.setFont();    // When I remove this line the sketch compiles OK
  tft.fillScreen(BLACK);
  tft.setCursor(0, 50);
  tft.setTextColor(RED);
  tft.setTextSize(13);
  tft.println("1234");
}

```

When compiling I get this error:

> "error: ‘class Adafruit\_ILI9341\_8bit\_AS’ has no member named ‘setFont’"

According to Adafruit's GFX manual, the `setFont()` procedure allows to define a new font or revert to the standard one.

I examined the libraries and nowhere could I find a procedure to select a font, yet the example has declarations like these below, so changing fonts should be possible:

```
#include <Adafruit_GFX_AS.h>
#include <Adafruit_ILI9341_8bit_AS.h>
#include <Font16.h>
// #include <Font32.h>
// #include <Font64.h>
// #include <Font72.h>
#include <Font7s.h>
#include <Load_fonts.h>

```

I would like to load the 7segment font with:

```
tft.setFont(&Font7s);

```

Does anybody have experience to share loading these fonts?

# Answer
Newer versions of the library CAN use fonts.

```
#include <Fonts/FreeSerifBold12pt7b.h>

```

and then...

```
matrix.setFont(&FreeSerifBold12pt7b);

```

Whether they work or not, I dunno. ***Case closed, lol!***
> 1 votes

# Answer
Tested on Windows, with newest libraries **Adafruit-GFX** and **Adafruit\_PCD8544** (Nokia5110 LCD connected to Arduino Nano).

```
#include <Fonts/FreeSerifBold12pt7b.h>

```

and then

```
matrix.setFont(&FreeSerifBold12pt7b);

```

Then there is one very important difference how to use function `drawChar(...)`. Coordinates of character (x,y) begins in left-bottom corner of character instead of top-left corner so this will not work (you will see only about 1 px of character):

```
matrix.drawChar(0,0,'1', 1, 0, 6),

```

**Use this to show all pixels of character:**

```
matrix.drawChar(20,20,'1', 1, 0, 6),

```

Full manual for using fonts here: Adafruit GFX Graphics Library - Using Fonts
> 1 votes

# Answer
Looking further into documentation on the Adafruit website they indicate that indeed, their GFX library published on GitHub does not handle different fornts.

Case closed :-)
> 0 votes

---
Tags: arduino-uno, adafruit
---


# Question
Title: Trying to map a room with Arduino controlled bot
What you see above is a map of my room. The boxes in black are obstacles and the box in red is my bot.

Now I want my bot to go around the room, avoiding all obstacles, but at the same time, covering the entire floor. Think of it like the robot is painting the floor and it has to paint the entire floor avoiding all obstacles.

Now my first approach was to put 3 HC-SR ultrasonic sensors on 3 sides and listen to them in a sequence, deciding which path is best and then going there. But this method leaves out quite a lot of floor area uncovered.

So how can I cover the entire floor area here?
Presently I am working with Arduino UNO and HC-SR04 but wouldn't hesitate to throw my Pi3 or a few more sensors in there...-

# Answer
> 1 votes
This is actually quite a complex thing to achieve. I'll give some suggestions, though this is not something I have attempted (yet).

The main thing to do is divide the room up into a grid. The resolution you choose (X and Y dimensions) depends on how small your robot is, how big the room is, and how much memory your have available (on an Uno that's not much at all).

The second thing you need to do is work out a way of determining exactly where in the room you are. That could be done by trying to get as close to the bottom-left corner as possible before starting to map.

Now you can work from square to square (you could do with some encoders to know how far you have driven, and a magnetometer so you know which direction you are facing) using whatever method you like to decide which way to go, and in each square you look to see which of the squares around you are accessible. From that you can work out which way you can go from that square.

As you go you maintain a map in memory of all the squares you have been to, and the squares that you cannot get to. Note that it may not be enough to say "You can't get to square 4,3" - instead you may to keep a more detailed list (depending on what your obstacles are). "You can't get to square 4,3 from square 4,2, nor 3,3, but you can get to it from square 5,3" for example (e.g., a thin obstacle that only blocks entry to that square from certain sides).

Since your sensors cover longer ranges than just one square (unless you have big squares) you can work out how far away an obstacle is, and mark the square it's in before you even get close to it. The square immediately preceding it on a path between it and you would be the "you can't get there from here" square.

Now you can work out paths and routes to get to the squares you need to so you can cover all the available floor.

---
Tags: arduino-uno, raspberrypi, hc-sr04
---


# Question
Title: Pushing sketches to pro mini with Uno 101
So I just bought a Pro Mini the other day, however, I didn't get an FTDI cable or a USB/Serial converter board. From what I understand from this article I can use my Arduino Uno 101 to push sketches onto the Pro Mini.

The wires are all hooked up (grounded reset on the Uno) and I have uploaded the sketch to disable the serial communication port on the Uno, however, when I try to push a sketch to the Mini it errors out with the following message

```
Arduino: 1.8.3 (Windows Store 1.8.6.0) (Windows 10), Board: "Arduino Pro or Pro Mini,
ATmega328 (5V, 16 MHz)"

Sketch uses 928 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for
local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\\.\COM3": The system cannot find the
file specified.

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

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

The only part of the suggested troubleshooting guide that maybe applicable is the drivers section.

> Drivers
>
> The Arduino Uno and Mega 2560 use standard drivers (USB CDC) provided by the operating system to communicate with the ATmega8U2 on the board. Other Arduino boards use FTDI drivers to communicate with the FTDI chip on the board (or in the USB-serial convertor).

I could be wrong but to me it doesn't seem like the second sentence applies to this situation since the the Uno sits between the pc and the mini. However, when I check the windows device manager I can see that the Uno is connected on a COM port, but nothing about the Mini. Though I am not sure that it should show up.

I am using the IDE(1.8.3) to program and "Arduino Pro or Pro Mini" as the board. Though Tools\>Port is greyed out when I have this board selected.

# Answer
There is no "Arduino Uno 101" there are only "Arduino Uno" and "Arduino 101".

101 uses completely different hardware, and tricks to use an Uno as an USB to UART adapter won't work on an 101.

101 has also separate serial interfaces for USB serial (`Serial`) and hardware serial (`Serial1`).

If you have have an Arduino 101 you can solve this by software means.
The board needs to be able to change the baud rate and use DTR for reset.

There is a sketch from PaulStoffregen on GitHub that does that.

```
/* USB to Serial - Teensy becomes a USB to Serial converter
   http://dorkbotpdx.org/blog/paul/teensy_as_benito_at_57600_baud

   You must select Serial from the "Tools > USB Type" menu

   This example code is in the public domain.
*/

// set this to the hardware serial port you wish to use
#define HWSERIAL Serial1

unsigned long baud = 19200;
const int reset_pin = 4;
const int led_pin = 13;  // 13 = Teensy 3.X & LC
                         // 11 = Teensy 2.0
                         //  6 = Teensy++ 2.0
void setup()
{
  pinMode(led_pin, OUTPUT);
  digitalWrite(led_pin, LOW);
  digitalWrite(reset_pin, HIGH);
  pinMode(reset_pin, OUTPUT);
  Serial.begin(baud);       // USB, communication to PC or Mac
  HWSERIAL.begin(baud);     // communication to hardware serial
}

long led_on_time=0;
byte buffer[80];
unsigned char prev_dtr = 0;

void loop()
{
  unsigned char dtr;
  int rd, wr, n;

  // check if any data has arrived on the USB virtual serial port
  rd = Serial.available();
  if (rd > 0) {
    // check if the hardware serial port is ready to transmit
    wr = HWSERIAL.availableForWrite();
    if (wr > 0) {
      // compute how much data to move, the smallest
      // of rd, wr and the buffer size
      if (rd > wr) rd = wr;
      if (rd > 80) rd = 80;
      // read data from the USB port
      n = Serial.readBytes((char *)buffer, rd);
      // write it to the hardware serial port
      HWSERIAL.write(buffer, n);
      // turn on the LED to indicate activity
      digitalWrite(led_pin, HIGH);
      led_on_time = millis();
    }
  }

  // check if any data has arrived on the hardware serial port
  rd = HWSERIAL.available();
  if (rd > 0) {
    // check if the USB virtual serial port is ready to transmit
    wr = Serial.availableForWrite();
    if (wr > 0) {
      // compute how much data to move, the smallest
      // of rd, wr and the buffer size
      if (rd > wr) rd = wr;
      if (rd > 80) rd = 80;
      // read data from the hardware serial port
      n = HWSERIAL.readBytes((char *)buffer, rd);
      // write it to the USB port
      Serial.write(buffer, n);
      // turn on the LED to indicate activity
      digitalWrite(led_pin, HIGH);
      led_on_time = millis();
    }
  }

  // check if the USB virtual serial port has raised DTR
  dtr = Serial.dtr();
  if (dtr && !prev_dtr) {
    digitalWrite(reset_pin, LOW);
    delayMicroseconds(250);
    digitalWrite(reset_pin, HIGH);
  }
  prev_dtr = dtr;

  // if the LED has been left on without more activity, turn it off
  if (millis() - led_on_time > 3) {
    digitalWrite(led_pin, LOW);
  }

  // check if the USB virtual serial wants a new baud rate
  if (Serial.baud() != baud) {
    baud = Serial.baud();
    if (baud == 57600) {
      // This ugly hack is necessary for talking
      // to the arduino bootloader, which actually
      // communicates at 58824 baud (+2.1% error).
      // Teensyduino will configure the UART for
      // the closest baud rate, which is 57143
      // baud (-0.8% error).  Serial communication
      // can tolerate about 2.5% error, so the
      // combined error is too large.  Simply
      // setting the baud rate to the same as
      // arduino's actual baud rate works.
      HWSERIAL.begin(58824);
    } else {
      HWSERIAL.begin(baud);
    }
  }
}

```

Then you need to connect:

```
Arduino 101  |  Arduino Pro Mini
-------------+------------------
VCC          |  VCC
GND          |  GND
TX           |  RX
RX           |  TX
PIN 4        |  DTR

```

After that you can use the port as a Arduino Pro Mini programmer.
> 1 votes

---
Tags: arduino-uno, serial, arduino-pro-mini
---


# Question
Title: Error trying to compile an example from newly added Arduino menu library
I added the ArduinoMenu library https://github.com/neu-rah/ArduinoMenu and when I try to compile one of the examples, I get following error.

> Using library LiquidCrystal at version 1.0.5 in folder: C:\Program Files (x86)\Arduino\libraries\LiquidCrystal exit status 1 Error compiling for board Arduino/Genuino Mega or Mega 2560.

How can I fix this?

# Answer
I think you have to add your library in the library folder. Below is the path of that folder. It will help you.

`C:\Program Files (x86)\Arduino\libraries`
> 2 votes

# Answer
Can you compile the LCD example for that board? just to make sure you have LiquidCrystal library ok.

Then tell us what was the example? There are hardware specific examples.

Also try to compile the serial menu example, just to make sure that ArduinoMenu library is ok for your board.
> 0 votes

---
Tags: arduino-mega, lcd, library, compile
---


# Question
Title: Error using Crypto Library for Arduino: Speck
I'm trying to encrypt a string in my Arduino Uno using the following library:

https://github.com/rweather/arduinolibs/tree/master/libraries/Crypto

And I'm getting this error:

> In function 'void setup()':
>
> TESTING\_SPECK\_LIB:27: error: request for member 'setKey' in '*(byte*)(& cipher)', which is of non-class type 'byte {aka unsigned char}'
>
> cipher-\>setKey(\*key,keySize);
>
> exit status 1 request for member 'setKey' in '*(byte*)(& cipher)', which is of non-class type 'byte {aka unsigned char}'

This is the code I'm using:

```
#include <Crypto.h>
#include <Speck.h>
#include <SpeckSmall.h>
#include <SpeckTiny.h>
#include <string.h>

Speck speck;
SpeckSmall speckSmall;
SpeckTiny speckTiny;

byte buffer[16];
byte cipher[16];
size_t keySize = 32;

void setup() {

  const uint8_t key[32]={0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                    0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00};
  byte plaintext[16]={0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                    0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20};
  byte ciphertext[16]={0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                    0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18};

  Serial.begin(9600);

  cipher->setKey(*key,keySize);
  cipher->encryptBlock(buffer, plaintext);

}

void loop() {

}

```

I know that I'm doing something wrong, but I don't understand what the error means, someone knows what it means and how to fix it?

# Answer
`byte cipher[16];` declares `cipher` as an array of 16 bytes. As such, `cipher` has no methods, much less ones called `setKey()` or `encryptBlock()`.

Note, `setKey()` and `encryptBlock()` look like method names one would find in `Crypto` or `Speck` library code; however, I don't find them in the `Crypto` and `Speck` headers I looked at on github sites. Also, `buffer`, `cipher`, and `keySize` look like variables and parameters one would use in creating an object for use with encryption methods.

In short, it appears your code fails to set up an appropriate class of objects that have `setKey()` and `encryptBlock()` methods.

Note, while I am not familiar with their details, I question whether all of the header files `Speck.h`, `SpeckSmall.h`, and `SpeckTiny.h` should be included in your code. It seems more likely that you would choose one of them as appropriate to your needs.

---

*Edit 1:* Looking at `TestSpeck.ino` as mentioned in `per1234 6`'s comment, one sees a function `perfCipher()`, with its first argument declared as `BlockCipher *cipher`. That is, `cipher` is declared as an object of a class that has `setKey()` and `encryptBlock()` methods.

The `TestSpeck.ino` sketch includes all three of the header files `Speck.h`, `SpeckSmall.h`, and `SpeckTiny.h` because it runs performance tests that compare results using different `Speck` implementations. In practice you usually won't need more than one of those headers.
> 2 votes

---
Tags: arduino-uno, library
---


# Question
Title: Arduino-Pyserial communication on Python 3, Windows machine: Pyserial.write() doesn't seem to do anything
I've recently gotten my hands on an Arduino (or rather a Genuino, but the overall architecture should be the same) UNO. I'm now using that Arduino to test how data is transmitted from a USB to Serial Connector to the Arduino.

I've already verified that data transmission from Arduino to the PC is possible, by using hTerm and PySerial. However, whenever I send data from Pyserial or hTerm, it doesn't show up in the Arduino serial terminal. Also, I'm using SoftwareSerial to set up a secondary serial terminal to see what the Arduino receives. (I'm using the standard serial port to send data to the terminal, and the SoftwareSerial Port to connect to the USB to Serial Connector.)

Here's my code so far:

Python side:

```
import serial
import time
import sys
import struct
ser = serial.Serial('COM3', 9600, timeout=0)
time.sleep(10)
while 1:
    print(ser.write(struct.pack('>B', 0)))
    time.sleep(2)
    print(1)
    sys.stdout.flush()

```

The Arduino side looks like this, and is essentially the default example: https://www.arduino.cc/en/Tutorial/SoftwareSerialExample

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
  // put your setup code here, to run once:
  if (Serial) {
    Serial.end();
  }
  Serial.begin(9600);
  while (!Serial) {
    ;
  }

  Serial.println("Godnight moon!");

  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() {
  // put your main code here, to run repeatedly:
  mySerial.listen();
  if (mySerial.available() > 0) {
    Serial.println("Hello User");
    Serial.println(mySerial.read());
  }
}

```

The Terminal never prints "Hello User". Also, no other signals are being printed. By removing the if-condition, I get a whole lot of "Hello User" and "-1" in the Arduino IDE serial monitor.

Concerning my setup:

I've got an USB to Serial converter, which is connected as "COM3". On the other side, I have an Arduino UNO which is connected via USB to the same computer. The TX pin of the converter is connected to the RX pin of the Arduino and vice versa. Also, Ground is connected to Ground. Furthermore, I use Jupyter/IPython notebook to run my Python script, and the default Arduino IDE to compile programs for my Arduino. In the case there I received data from the Arduino, I used the script specified in the URL provided, which is very similar to the one I'm already showing here. Also, `ser.write()` is replaced by `ser.read(1)`, so that it reads one byte at a time. My system is Windows 7 (64 Bit).

Edit: Here is an established connection between hTerm (a serial terminal) and the Python script while using com0com as a port emulator.

# Answer
What do you think should come out?

I'm no expert with Python but you seem to be using struct pack, which I think prepends a number of bytes to the data to generate a 4 byte word. You are using NULL, 0 to pack the structure. When Serial.println() encounter a NULL it will assume that is the end of the string. So you seem to be printing a zero byte string.

Oh and Serial.read() only reads one byte of data, so there is an issue with that too. I suspect that the write call has a similar issue, you normally need to supply a size parameter because its binary data.

Does that make sense?
> 1 votes

# Answer
When you run your python code, do you see the things you are sending on the screen there?

I think you need to be calling ser.open().
> 0 votes

---
Tags: serial, softwareserial, python
---


# Question
Title: Arduino autorestarts when powered externally
I'm trying to finish building an alarm system with relays, leds and bluetooth. I finally made it working but when externally powered (12v source) after about 10 seconds it starts to reboot continuously. This issue comes with no pc connection.

# Answer
https://www.arduino.cc/en/Main/ArduinoBoardUno

Majenko has a good lead,

12V is just within spec of the voltage regulator.

Though this may be different per manufacturer or different in your environment.

To battle overheating you can:

* Create beter airflow
* Add a heatsink
* Draw less current

But you should try a 9V source, that can deliver enough current (not the 9V "block" batteries).

Also check if the system draws excessive current, maybe the circuit has a low resistance or power hungry part (on the 5V rail)

If nothing works, you could try and use another Arduino board, maybe the regulator is faulty/damaged.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to read Negative number with serial.read
how i can read negative number with command Serial.read()? beacouse i with this

```
    char tmpChar = Serial.read(); //read incoming character from serial port
    if (isDigit(tmpChar)) { //check if the in character it's a number
        setpoint =  (setpoint  * 10 ) + tmpChar - '0'; // convert from ascii code to it's corresponding number; '0' == DEC 48
      }
if (tmpChar == '\n' || tmpChar == '\r') { //if CR or LF was received
    if (setpoint > 0) {
      tmpChar = "";
      Serial.print(setpoint);
      Serial.println(" NUMERO STEP IN AVANTI");

    }

```

im using an encoder motor, i want to move for N steps the motor forward (positive number) or backward (negative number) , i insert the number of step in serial input

i can read only positive number. Thanks for help

how suggest Majenko i made a partial solution :

```
char buf[8];
int valore = 0;

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

void loop() {
  if (Serial.available() >= 8) {
    for (int i = 0; i < 8; i++) {
      buf[i] = Serial.read();

    }
    String str();
    if (buf[0] == "-") {
      valore = (atoi(buf)) * -1;
      Serial.println(valore);

    }
    else {
      valore =  atoi(buf);
      Serial.println(valore);
    }
  }
}

```

but the problem now it's the static array , unpleasant to use

# Answer
> 0 votes
Personally I would read the data into a char array then use either `atoi()` or `strtol()` to convert that char array into a number.

Using those functions is more robust that parsing the data yourself since they identify where the number ends and discards any trailing garbage. It also skips any white space before the number. For instance it will interpret all these as the number `-32`: `" -32"`, `"-32 Degrees"`, `" -32+4 "` and `"-32-2"`.

`strtol()` has the additional advantage that it can work in other bases than 10, so you could interpret hexadecimal data, binary data, sexagesimal data, etc.

`atoi()` and `strtol()` are standard C functions.

E.g.:

```
int val = atoi(mycharbuffer);

```

or

```
long val = strtol(mycharbuffer, NULL, 10);

```

# Answer
> 1 votes
You could do something like this:

```
static int setpoint;      // the partially read setpoint
static bool isNegative;   // whether it should be negative
void applySetpoint(int);  // apply the setpoint when fully read

char tmpChar = Serial.read();
if (isDigit(tmpChar)) {
    setpoint =  (setpoint  * 10 ) + tmpChar - '0';
} else if (tmpChar == '-') {  // minus sign
    isNegative = true;
} else if (tmpChar == '\r') {  // line terminator
    if (isNegative) {
        setpoint = -setpoint;
        isNegative = false;  // reset for next read
    }
    applySetpoint(setpoint);
}

```

Note that this is not very robust: it will happily interpret "3-2" as meaning "-32". Note also that I assumed your terminator to be '\r', you may be using another one.

# Answer
> 0 votes
The `parseInt` can read negative numbers (I think it does, the reference is very cryptic). The `parseInt` has a `timeout` so it does not wait forever.

Can you tell what kind of data you are reading ? Is it part of more data ?

---
Tags: serial
---


# Question
Title: How to pulse a signal at 100ms to 500ms?
Based on this PDF I need to pulse between 100ms and 500ms to record a video (the description is apparently wrong according to this guy). How would I generate such a pulse? The small module has 3 wires I can use, which are positive, ground, and a yellow wire. I assume I need to pulse the yellow wire.

I don't want to hook anything up wrong, but my guess would be using `pulseIn()`. However, I am not sure at all. Any help appreciated.

# Answer
Okay, so pulsing is apparently easy enough. If I just do:

```
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);

```

It will start recording, then turn off about a second later, start again about a second later, and then repeat. I somehow managed to get a 5 second recording as well. I'm not really sure how this is supposed to work. I need to test some more.

EDIT: Turns out the schematics were right. If I do something as simple as:

```
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(1000);

```

It will turn on the video recording and turn off whenever it gets HIGH again.
> 1 votes

---
Tags: pulsein
---


title: The LCD doesn't display the words typed

text:
# Question
Title: The LCD doesn't display the words typed
I've tried this code on an LCD, and instead of displaying "Hello World!" it displays what is shown on the picture.

Code:

```
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  lcd.begin(16, 2);
}

void loop() {
  lcd.print("Hello World!");
  delay(500);
  lcd.clear();
  delay(500);
}

```

# Answer
> 1 votes
Try the following

1. Double-check the LCD soldering
2. Double-check your wiring
3. Ensure that the pins you are using for your LCD are not assigned to some other function. This caused jumbled, random characters here.

# Answer
> 1 votes
From the attached I can see that you are connecting D7 to digital 2 of arduino. And I assume the pins D6 D5 D4 are also connected to 3, 4, 5 pins respectively, which is correct for your code. But make sure the R/W pin is connected to proper ground. Verify that by measuring voltage if possible. Also serial print whatever you are giving the lcd to make sure it is not an encoding issue.

# Answer
> 0 votes
Don't take this the wrong way but some of those solder joints looks a little rough. I'm not sure this is your issue but you need some soldering practice. Solder joints should be bright and shiny and should completely cover the pad.

I can tell by the joint on pin 16 you didn't get it hot enough or the solder would have flowed to cover the entire pad. Some of the other joints look like they were overheated. Does your soldering iron have a temperature control? Experience will help you know when to turn it up and when you can get by with a lower temperature. Is your tip too large or needs replacing?

There's lot's of soldering how-to videos out there but no substitute for practice, practice, practice and then practice some more. :)

---
Tags: arduino-uno
---


# Question
Title: How do I erase the memory of the Arduino Uno?
I'm just a tinkerer learning Arduino with my son and I was surprised that when I plugged the USB cord back in to the Arduino the program was still running and I thought to myself, "it's a good thing I didn't just blow anything up."

So, what's the normal way people call it a day with these things? Do you usually load up the bare-bones do nothing sketch or just unplug everything?

# Answer
When booted, the Arduino will run whatever program was put on it last. Solution: Don't turn it on if you don't want it to run.

When out of the box, the Arduino usually runs the Blink program. So you can just load that and call it a day if you want to "reset" it.

Or have a loop program with a sleep command.

If you've been messing with the USB bootloader via the icsp pins, this isn't enough though, you'll need to reinstall the bootloader. But if you've been uploading programs via usb or directly using a programmer, there is no issue with uploading Blink or some other dummy program to reset it.
> 15 votes

# Answer
If safety is a major concern, then you should almost always load a stop\* sketch onto the board before calling it a day. This would be a good idea, for example, when your board is semi-permanently a part of a larger system. You could do so by:

* Upload the Bare Minimum sketch found in `File` -\> `Examples` -\> `Basic` in the
* Upload a sketch with a large delay in loop.

```
#include <limits.h>

void setup()
{}

void loop()
{
  delay(ULONG_MAX);
}

```

```
void setup()
{
   exit(0);
}

void loop()
{}

```

<sub>\*Stop is simply figurative. The board doesnt really stop running.</sub>
> 9 votes

# Answer
The major thing that can go wrong is if you put your Arduino aside for a couple of weeks, forget what sketch (code) is loaded onto it, then get back to work on it, plug in hardware (like a switch, LED or motor) and have it unexpectedly light up / turn on, because the previous code addressed the pin it was connected to.

---

### Solution 1. Load the new code first.

A simple and safe technique is to load the new code that you are working on today **before** you plug any hardware in. Now you know what the code does, what pins it uses, and you then plug the hardware in afterwards (preferably turning the Arduino off first by unplugging it).

Then when you reconnect power, it runs the sketch you uploaded, you have your hardware connected and all should be well.

---

### Solution 2. Load a "do nothing" sketch.

You can upload this short sketch:

```
int main () { }

```

It "does nothing". All pins will remain as inputs, so you can safely then attach your hardware, and then start coding your new project.

---

### Safety first

A good rule is to not plug or unplug hardware (eg. LEDs, switches, motors) with the power applied. If you get distracted and plug into the wrong socket on the board you might immediately damage either what you are connected, or the Arduino, or both.

With the power off, you can then do a last-minute check that everything is connected to the right place, you have your polarities correct, and so on.

Also make sure you don't have static electricity on your body, particularly if you are wearing a jumper or something fluffy, or are sitting on carpet.

Personally I always reach over and touch some metal part nearby to "ground" myself, before reaching for the Arduino. An example is the metal case of a PC, a headphone socket, or something like that.

If, after connecting power to the Arduino (eg. by the USB cable) you do not immediately see the power LED come on, disconnect the power immediately! You may have shorted something out, and the less time you do that for, the better.
> 1 votes

# Answer
In the Arduino IDE, go to examples, select Eeprom, select eeprom clear and then upload the sketch.

When it is the LED on pin 13 will turn on, you are done.

NB. This may take some time depending on the size of the EEPROM in the Arduino.
> 1 votes

# Answer
My biggest concern when this happens is I've usually wired the Arduino for my new project and I'm plugging in the USB for the initial download of the new sketch. I worry, having no idea what the previous program is going to try, being connected to totally different hardware.

So far nothing bad has happened and I don't think I'll adopt burning BLINK each time I put one of my Arduinos back in the bin. It's probably just a matter of time though.
> 1 votes

# Answer
If the arduino board is connected to any other device then unplug everything and just connect the arduino with the computer using the usb cable and try to upload new sketch i hope it will help.
> 0 votes

---
Tags: arduino-uno, safety, flash
---


title: Windows stops recognizing Arduinos

text:
# Question
Title: Windows stops recognizing Arduinos
I've just got my first Arduino Pro Mini and a USB to TTL chip. When I try to upload the program I get the message `The uploader process failed` followed by

`avrdude: ser_open(): can't open device "\\.\COM6": Access is denied.`

and a bunch of lines like `avrdude: ser_drain(): read error: The device does not recognize the command.
avrdude: ser_send(): write error: sorry no info avail
avrdude: ser_recv(): read error: The device does not recognize the command.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x48
avrdude: ser_send(): write error: sorry no info avail`

with 10 attempts after which nothing comes from avrdude and I can't upload nor get Arduino's visible in port choice menu all the time until the Windows 7 boots again. I can upload to my Arduino Uno with no problems before I try the ttl chip. TTL chip also shows up in the port menu before trying to upload, with correct name next to the port number. I installed drivers I found on a official site that sells the chip that looks just the same as mine, before I did that it wouldn't show up in the port choice menu at all. Is there any way to reset whatever it is that is preventing me from uploading to Arduinos so I don't have to restart my computer every time it happens? I managed to upload one program to the Arduino Pro and it's working fine but after a couple of hours, when I tried again, it didn't work. Maybe it would be of some use to say that I left my pc on sleep with the TTL chip plugged in and powered by the usb. My guess is that this chip is defective and was near it's life end when I uploaded so now it's just confusing the driver to the point where Windows decides to block the driver for the session.

# Answer
After a couple of hours I figured out what was happening so I will write all my analysis here for anyone having some of my problems.

First, a list of my components:

-USB TTL ship, used to upload programs to Arduino Pro. The one on the picture on instructables dot com /id/Usb-to-SerialTTL-adapter/, and used that driver.

-Arduino Pro. Chinese copy, red board just like Sparkfun's. 328p chip @ 5V = 16mhz.

-A board very similar to this one. It has a chip with `FT232` written on it, also `FTDI` in bold letters.

The big USB TTL pcb I was using has 5 output pins: 3v3, 5v, TX, RX, GND. Turns out this is not enough to program Arduino Pro as you need one more pin. If you don't connect this pin, avrdude just gets stuck after opening the COM port and waits indefinitely/until you kill the process. To even be able to see this USB TTL chip in Windows, you need to download a driver from the website(first link) and my guess is that the driver is buggy since it won't exit the process when it encounters this type of error, further leading to suspicious/dangerous behaviour which results in Windows completely shutting down all COM ports until next restart.

To get this pin(it's called DTR/GRN), I borrowed the other chip(3rd) and I connected it regarding to this scheme:

I also had to download a different driver for it, I don't remember where I downloaded it from but it's called CDM21226 driver, when you install it it says `FTDI driver installed`.

Now my uploading was getting stuck no more, however after the first successful upload to my Arduino Pro the upload process would get stuck in the part where it is burning the program, if you turn verbose option in Arduino IDE on, you can see something like `Writing: [####### ]`.

It turns out this driver was faulty too, as I uninstalled it and when I installed it with the very same setup as before it worked seamlessly ever since. It also took me some time how to uninstall a Windows driver without using Device Manager because it wouldn't show up there - no device attached to it.

To do that open Command Prompt as admin and type `pnputil.exe -e` to get a list of all drivers. Among them will be one called FTDI and that's the guy, in my case he was called oem51.inf. To delete him, type `pnputil.exe -d oem51.inf`, or add `-f` before `-d` to force deletion - in my case it kept saying device is busy so it required this drastic measure. Change 51 to the number you have above your ftdi driver. After this just install the driver again and everything should be fine, even without reboot.

Phew... So much work to get a simple program burned to Arduino Pro. Hope you have less trouble with it than I did.
> 1 votes

---
Tags: arduino-pro-mini, uploading, port-mapping, windows
---


# Question
Title: Where to declare timer interrupt variables?
I have a situation where the majority of the code is residing inside timer interrupt functions.

Setup() does what it has, loop() basically reads ADCs and then all the code is inside timer interrupts.

```
void loop()
{
  //Read the ADCs
  while((ADC->ADC_ISR & 0x1CC0)!=0x1CC0);   // wait for ADC 0, 1, 8, 9, 10 conversion complete.
  in_ADC0=ADC->ADC_CDR[7];                  // read data from ADC0
  in_ADC1=ADC->ADC_CDR[6];                  // read data from ADC1
  POT0=ADC->ADC_CDR[10];                    // read data from ADC8
  POT1=ADC->ADC_CDR[11];                    // read data from ADC9
  POT2=ADC->ADC_CDR[12];                    // read data from ADC10
}

void TC4_Handler()
{
 if (effect==0)       {/*HERE THE CODE FOR EFFECT 0*/}
  else if (effect==1)  {/*HERE THE CODE FOR EFFECT 1*/}
    else if (effect==2){/*HERE THE CODE FOR EFFECT 2*/}
      else             {/*HERE THE CODE FOR EFFECT 3*/}

  // We need to get the status to clear it and allow the interrupt to fire again
  TC_GetStatus(TC1, 1);
}

```

The user selects the effect he wants via a button and a hardware interrupt.

What happens when the timer interrupt function ends? Do we go back to loop(), or the timer function is re-run? In this example, all the vars needed inside each functino of the timer interrupt are declared globally.

I was considering if i can declare variables inside each function in the Timer Interrupt function. Therefore, we would save space, by not declaring variables that are not run at the moment. And we would only initialize variables for the effect we want.

Is this possible? Because if the effect i have just selected just re-loops, maybe its not wise for vars to get re-initialized (and their values re-set) each and every time it is looped.

So ultimately, variables taht will be used inside a timer interrupt function, globally or locally?

# Answer
If they are only used in the interrupt then yes they can be declared in the interrupt. If you want them to retain their value from one call to another they must be declared `static`, and then they will be the same as global variables as far as memory allocation is concerned.
> 1 votes

---
Tags: interrupt, timers, variables
---