# Question
Title: Problem with DHT11 and DS18B20 temperature sensors
I am trying to connect to my Arduino Uno board two temperature sensors: DHT11 and DS18B20. The problem is with the DHT11 sensor: apparently there's an error with reading the temperature every two measurements.

Here's what I get on the serial monitor (temperature 1 is from the DHT sensor):

As I am new to this, I was wondering what the problem may be. I have read about the one wire interface used by the DS18B20, but I noticed that the DHT is not using the same protocol.

If I use the DHT11 alone, it works perfectly fine.

Also, I am using 4k7 pull-up resistors for both sensors.

Here's the code:

```
#include <DallasTemperature.h>
#include <OneWire.h>
#include <dht.h>

dht DHT;

#define ONE_WIRE_BUS 8
#define DHT11_PIN 7

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup(void) {
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");
  sensors.begin();
}

void loop(void) {
  int chk = DHT.read11(DHT11_PIN);
  sensors.requestTemperatures();
  Serial.print("Temperature1: ");
  Serial.print(DHT.temperature);
  Serial.print(" Temperature 2 : ");
  Serial.println(sensors.getTempCByIndex(0));
}

```

# Answer
> 2 votes
There appears to be several DHT sensor Arduino libraries available:

You might try an alternate library to see if that solves your current problem. Note, some if not all of these libraries need to know which DHT model you are using.

Before going through the DHT and OneWire source code line by line looking for conflicts, try to narrow down what is causing the problem:

1. Try only instantiating the OneWire class and skip calling the read method within the class.

If this works, then the conflict likely resides in the OneWire read method and not in the OneWire initialization code (that is, the OneWire's Constructor).

2. Calling the DHT read method multiple times consecutively to see if the problem resolves it self.

Actually, you have done this and exposed a curious patter of good-bad-bad-good-bad-bad... which is worth looking into. The point here is that if only the 1st call to the DHT read method after a call the the OneWire read method was bad, then there might be a setup problem in the DHT read method.

3. Call the DHT Destructor, the DHT Constuctor then make the call to the DHT read method every time you read the DHT sensor.

This is a test case only and an extreme measure. What you are doing here is re-initializing the DHT library (driver) every time you use it. If this works it points to an initialization problem where the DHT library is initialization something which should probably be re-initialized again inside the DHT read method. As the OneWire library is using the same "something" (resource).

One last thing, the OneWire example I looked at here: PaulStoffregen/OneWire ...did not use the DallasTemperature library. I doubt this will make a difference, but it is usually best to keep your code simple and avoid unnecessary complexities.

Added later...

As pointed out in the comments, it turns out the DHT11 only takes new readings every few seconds. Guessing, the DHT11 library you are using either knowingly returns an unreasonable value of -999.0 until this time passes. Or is returning exactly what the DHT11 reports which, again, is an unreasonable value of -999.0.

In this DHT11 library, there is code:

```
boolean DHT::read(bool force) {
  // Check if sensor was read less than two seconds ago and return early
  // to use last reading.
  uint32_t currenttime = millis();
  if (!force && ((currenttime - _lastreadtime) < 2000)) {
    return _lastresult; // return last correct measurement
}

```

...which returns the last good value for 2 seconds after a DHT11 "real reading" should the library user call upon it faster then the DHT11 can respond.

# Answer
> 2 votes
DHT11 can only be read every 1 second. See manual.

# Answer
> 0 votes
To confirm the answers above, in my case https://github.com/adafruit/TinyDHT library worked fine with Arduino Uno, while http://playground.arduino.cc/Main/DHTLib refused to work. Same setup with DHT11 and DS1820.

---
Tags: arduino-uno, temperature-sensor, 1-wire
---


# Question
Title: How can I get ultra clean dc wall power for my arduino project?
I'm doing an rfid project that requires a read range of at least 5 inches or about 13cm. I'm using a nano with a usb port, a rfid reader from priority 1 design and a large antenna. The problem I'm running in to is that when I power the project from the usb port I get a pretty decent read range of 11-13cm. But when I power the project from a DC power supply the read range drops considerably.

After a lot of testing with various power supplies I believe that all my power adaptors are dirty enough to cause rf interference and reduce the range. Powering the project with a 9v battery and a 5v power regulator gives me really good range: 18cm with the largest antenna. But I need plug in power.

So how can I power this project in a way that gives me ultra clean power?

1. I tried that same 5v regulator with a 5v adaptor and still had short read range.
2. Someone suggested adding a smoothing capacitor between V+ and Gnd but I wouldn't know what size. I'm not an EE - I'm just a coder with a soldering iron.
3. Is there a better power supply I can get?

\[EDIT\] Also just FYI, when I connect even only the ground wire the the computers USB port I get a much farther read range. So..

4. Could it be a case of needing to ground the circut better as the switching power supplies only have 2 prongs and probably no real "ground". (Or am I making stuff up?)

\[EDIT 2\] What about a rechargable situation where my wall adaptor keeps a litium charged and the litium supplies clean power to the circuit?

Also I now know that I can charge my whole circuit with anything from 5 to 12 volts. In fact it would be better to have more in the 7 to 12 range than strictly 5v.

\[UPDATE 3\] Since this project is in my wall I was able to ground essentially to "earth" and that cleared up the noise. See this question as well: https://electronics.stackexchange.com/questions/230024/grounding-dc-project-to-clean-rf-noise

# Answer
> 2 votes
This is what I use, although admittedly not in your application. I run it from a 12V wall adaptor and adjust the output voltage to suit my requirements. The input should ideally be at least a couple of volts above the output(depends on current and temperature at 25degC and 20mA it's \> 1.6V and 1.5A at the same temp it's \> 2.7V).

Another alternative if you want to really go to town would be to repurpose an old computer ATX or similar PSU. There are plenty of guides out there and it's a straightforward job.

# Answer
> 0 votes
I think the problem is not the voltage but the magnetic field, so maybe better to use a faraday cage (a metal box) around the power supply and connect it to output DC ground.

---
Tags: power, rfid, rf
---


# Question
Title: Serializing data created by ATTiny85 for use on PC
Have an AES-128 implementation I'd like to install on an ATTiny85 for embedded use but need to come up with a way to **communicate with it from a PC** as you would do via Serial on Arduino Uno. For example, I'd like to stream 16 bytes of plaintext and get back 16 bytes of ciphertext (or signature hash, etc.).

The faster the transfer rate, the better obviously, but it would of course need to fit on the remaining space on an ATTiny85.

Any thoughts or working examples out there (i.e. I2C for PC, etc.) without incurring a lot of extra hardware cost?

# Answer
So thanks to Ignacio Vazquez-Abrams' tip, it looks like I'll be able to accomplish this with V-USB:

> V-USB is a software-only implementation of a low-speed USB device for Atmel’s AVR® microcontrollers, making it possible to build USB hardware with almost any AVR® microcontroller, not requiring any additional chip.

**Requirements:** AVR microcontroller with at least 2 kB of Flash memory, 128 bytes RAM and a clock rate of at least 12 MHz.

Taken from ATTiny85's Datasheet:

> * 8K Bytes of In-System Programmable Program Memory Flash
> * 512 Bytes In-System Programmable EEPROM (enough for third-two 16-byte keys)
> * 512 Bytes Internal SRAM

Looking forward to trying it out :)
> 1 votes

# Answer
> Any thoughts or working examples out there (i.e. I2C for PC, etc.) without incurring a lot of extra hardware cost?

Yet another alternative is to use the Display Data Channel (DDC) on the PC. This is 5V and I2C. Unfortunately not all PC video boards support I2C. Please see the reference for further details.

I2C is supported on ATtiny by the USI module.

Cheers!
> 0 votes

# Answer
> need to come up with a way to communicate with it from a PC

would be difficult to make an uart out of usi?
> 0 votes

---
Tags: arduino-uno, attiny
---


# Question
Title: Why is the constrain function used after the map function?
I am reading some sample code and they use this method of mapping data from IR sensors:

```
  sensor1 = analogRead(0);
  adj_1 = map(sensor1, s1_min, s1_max, 0, 255);
  adj_1 = constrain(adj_1, 0, 255);

```

What is the point of using `constrain` here if `adj_1` is already getting a value 0-255 from the `map` function?

# Answer
> 7 votes
From the official Arduino site:

> \[The map function\] does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired.

EDIT: Example.

You can try this by yourself with this code:

```
int val = 20;
val = map(val, 0, 10, 0, 100);

```

Although you set the upper bound of the value's range to 10, you passed an higher value than that and the function will linearly map it accordingly, resulting in an output of 200.

# Answer
> 0 votes
One caveat would be when mapping an input that ranges from 0 to 1023, since the Arduino is incapable of reading outside of this range there would be no need to constrain. You can check this by running through each iteration from 0 to 1023 and outputting the corresponding mapped value:

```
for (int i = 0; i < 1024; i++){
    Serial.print(i);
    Serial.print(",");
    Serial.println(map(i, 0, 1023, 0, 255));

}

```

Certainly, if your sensor reading offers a range smaller than 0 to 1023, then the constrain() function is definitely required, as per LoganBlade's example. Otherwise, it is not needed, but may still fall into the realm of best practice.

The only hiccup to this logic would be if you are mapping to decimal values (which doesn't make much sense since the function will return a long type anyway), in which case the Arduino's internal typecasting will round-down your lowest value mapping. Example:

```
map(0, 0, 1023, 8.9, 61.9));
>> 0 becomes 8

map(1023, 0, 1023, 8.9, 61.9));
>> 1023 becomes 61

```

Again, for the sake of best practice and the potential time wasted trying to find a mapping bug, using constrain() is better than skipping it.

---
Tags: sensors, map
---


title: RCSwitch on Attiny85

text:
# Question
Title: RCSwitch on Attiny85
I would like to use my Attiny85 as an remote controlled relay switch. I have already tested the sketch on my Atmega328 and it worked. Now I wanted to burn the sketch on my Attiny85 using ArduinoISP but I get the following error in the ArduinoIDE:

```
sketch_dec25a.ino: In function ‘void setup()’:
sketch_dec25a:13: error: ‘class RCSwitch’ has no member named ‘enableReceive’
sketch_dec25a.ino: In function ‘void loop()’:
sketch_dec25a:20: error: ‘class RCSwitch’ has no member named ‘available’
sketch_dec25a:21: error: ‘class RCSwitch’ has no member named ‘getReceivedValue’
sketch_dec25a:22: error: ‘class RCSwitch’ has no member named ‘getReceivedValue’
sketch_dec25a:25: error: ‘class RCSwitch’ has no member named ‘resetAvailable’

```

That's my code:

```
#include <SoftwareSerial.h>
#include <RCSwitch.h>

int RELAY_PIN = 2;

RCSwitch mySwitch = RCSwitch();
SoftwareSerial mySerial(1, 3); // RX, TX

void setup()
{
  pinMode(RELAY_PIN, OUTPUT);
  mySwitch.enableReceive(0);  // Receiver on inerrupt 0 => that is pin #2
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{
  if (mySwitch.available()) {
    Serial.println(mySwitch.getReceivedValue());
    if(mySwitch.getReceivedValue() == 1234567){
      digitalWrite(RELAY_PIN, HIGH);
    }
    mySwitch.resetAvailable();
  }
}

```

I am using these cores: https://code.google.com/p/arduino-tiny/

I am using the SoftwareSerial just for debugging. Sorry for my bad english and thanks for your help!

# Answer
The issue you face is that RCSwitch does not seem to support receive mode for ATtiny.

This is what you can find in `RCSwitch.h`:

```
// At least for the ATTiny X4/X5, receiving has to be disabled due to
// missing libm depencies (udivmodhi4)
#if defined( __AVR_ATtinyX5__ ) or defined ( __AVR_ATtinyX4__ )
#define RCSwitchDisableReceiving
#endif

```

Then all methods related to receptions are not defined in `RCSwitch` class for ATtiny MCUs:

```
#if not defined( RCSwitchDisableReceiving )
void enableReceive(int interrupt);
void enableReceive();
void disableReceive();
bool available();
void resetAvailable();

unsigned long getReceivedValue();
unsigned int getReceivedBitlength();
unsigned int getReceivedDelay();
unsigned int getReceivedProtocol();
unsigned int* getReceivedRawdata();
#endif

```

I am really not sure if there is a way to work around it, I have not looked at the code in `RCSwitch.cpp`.

Maybe you best option would be to find another RC library.

For instance, if you can use Infra-Red RC, then there are libraries out there that could work for ATtiny:

https://github.com/shirriff/Arduino-IRremote
> 4 votes

# Answer
I have tested with Digispark ATtiny85 and https://github.com/sui77/rc-switch work perfect

just comment `#define RCSwitchDisableReceiving` than use in setup code `enableReceive(0);` and external pin 7 PB2(int0) as RF source

Or you can use other software pin interrupt

in setup:`PCMSK |= (1<<PCINT0);//here pin number
GIMSK |= (1<<PCIE);`

interrupt function `ISR(PCINT0_vect) {
 rd.handleInterrupt(); // you need also put handleInterrupt() in public section in RCSwitch.h
}`
> 1 votes

---
Tags: attiny, virtualwire
---


# Question
Title: Flash a hex file to an MCU/Arduino over the air?
I have a processor `AT328` , Arduino bootloaded, and a `Bluetooth` on the serial lines `Tx,Rx` .

I would like to program the chip over Bluetooth, **not using a computer or IDE, but mobile phone with my own Hex uploader.**

So, if the `hex` file was just a huge text that you have to send, i would obviously just send it and thats it, as I understand there is a mechanism ?

**Question** : How exactly a `Hex` file is sent over serial to program the chip ? is it like any other text file? is there any mechanism I have to write? specific `baud rate`? is there any article about this ?

# Answer
*Basically, this is much more involved than it might appear on the surface. If you haven't already, I would make sure that I was comfortable with finding things in the datasheet (and it's a really good datasheet, at that). If you're still up for it, read on.*

## Bootloader

The way a bootloader works on the ATmega328 is that the memory on the chip is self-modifying. This means you can have a piece of code on the chip that modifies memory on the rest of the chip. A bootloader is one such piece of code that runs when the chip first starts up, and checks to see if there's code to be loaded. If there is, it writes that code to the rest of the memory, and then executes it. See section 12.2 of the datasheet.

The way you would program an actual bootloader is described in detail in section 30 "BTLDR - Boot Loader support". I haven't programmed a bootloader before, so you're on your own here, but there are plenty of resources to guide you. In fact, the datasheet has example code in there for it.

(Note that you must program your chip normally at least once, to put the bootloader on it.)

One thing to note is that bootloaders should be small. You don't want bootloaders to take up a lot of your memory, since they only run once on boot and are really just a convenience feature. There are competitions for writing the smallest/most efficient bootloader, and you'll almost certainly want to write your bootloader in assembly. Notice that the only example code given in the datasheet is in assembly. Which brings me to my next point:

## Bluetooth

Bluetooth is very annoying to program for. You have to set up different profiles, or do GATT stuff if your module is actually BLE/"Smart" instead of classic bluetooth, etc. However, I'm assuming from your post that you just have one of those serial modules you can find on eBay for dirt cheap. Before I go on, I want to make this very clear: It is **non-trivial** to set up. It will take up lots of precious code space on your microcontroller that you would want to use on your actual program. Remember how bootloaders are written in assembly? Writing a bluetooth interface in assembly will probably take a while.

As for how your bluetooth module works; it is basically a serial port, but over-the-air. This means the bluetooth interface that you write would need to bit-bang everything if you don't use the built-in USART (say you need those pins for your actual program), and if you do use the built-in USART, setting that up will take even more time. (For a guide on how to setup the USART, see section 24 of the aforementioned datasheet. See? It's really handy.)

Once you actually have bluetooth working, you can do whatever you want. Since you write the bootloader, you can read data from your bluetooth serial link however you fancy. As long as you know what you're sending, all you have to do is read it back accordingly.

## Bonus: Flashing

You are correct that a `.hex` file is just a huge text file that you send to the chip. However, the way the ATmega is actually programmed is *not* simply using the serial port; instead, it's a slightly extended SPI protocol. (If you don't know what SPI is, you really shouldn't be doing this. If you're curious, Sparkfun has a nice tutorial on SPI.) This is called ICSP, or "in-circuit serial programming". The way to do this for AVRs is explained in an application note.

Of course, you cannot replicate this with just a bluetooth module. Instead, you would need a co-processor to program your chip for you, and read the data to-be-programmed from your bluetooth module.

---

**TL;DR: This is probably not worth it. If you're planning on doing this, it will take significant resources, and you might even need a better chip to get anything done. You almost certainly should just buy an ESP8266 / ESP32 instead.**
> 0 votes

---
Tags: bluetooth, bootloader
---


# Question
Title: What is the opposite of this data operation?
If I store in an array a double-value in this format, in which format I should be able to read the same double out?

```
double myDouble = 12.123456;
byte myArray[] = {0x00, 0x00, 0x00, 0x00};

myArray[0] = (myDouble >> 0);
myArray[1] = (myDouble >> 8);
myArray[2] = (myDouble >> 16);
myArray[3] = (myDouble >> 24);

```

# Answer
> 2 votes
You are better off making a union, that will be compiler independent, and won't give you the (possibly) odd results that trying to shift a double would give.

Example:

```
  union
    {
    byte myArray [4];
    double myDouble;
    } foo;

   foo.myArray [0] = Serial.read ();
   foo.myArray [1] = Serial.read ();
   foo.myArray [2] = Serial.read ();
   foo.myArray [3] = Serial.read ();

   double f = foo.myDouble;

```

Even then be cautious that whatever is sending you this double in 4 bytes is using the same encoding for doubles that the Arduino does. For one thing, **double** and **float** are the same on the 8-bit Arduinos (they are only 4 bytes).

# Answer
> 0 votes
in the simplest form (compiler dependent however), a pointer will do.

---
Tags: programming, c++, c, array, variables
---


title: Turning an electric vehicle

text:
# Question
Title: Turning an electric vehicle
I am not sure if what I am asking is possible. I was wondering if I would be able to program my Arduino to have my car go straight until one of the wheels hits a certain amount of wheel rotations then initiating a different code within the same causing that wheel to increase that wheels speed. I have already created a code to make it go and stop in a certain amount of rotations.

```
/* motorshield_code
Pins Utilized
Digital 2 = encoder0APinA
Digital 3 (PWM) = MotorASpeed  //motorshield utilized
Digital 4 = encoder0PinB
Digital 8 = MotorBBrakePin // motorshield utilized
Digital 9 = MotorABrakePin // motorshiled utilized
Digital 11 = MotorBSpeedPin // motorshiled utilized
Digital 12 = MotorADirectionPin // motorshiled utilized
Digital 13 = MotorBDirectionPin // motorshiled utilized
*/

//Encoder values
const int encoder0PinA = 2;
const int encoder0PinB = 4;
const int encoder1PinA = 7;
const int encoder1PinB = 6;
int encoder1Pos = 0;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int encoder1PinALast = LOW;
int n = LOW;
int i = 0;

//Motorshield Pin Values
const int MotorADirectionPin = 12; //digital pin value for A direction
const int MotorASpeedPin = 3; //analog pin value for A speed (PWM)
const int MotorABrakePin = 9; // digital pin value for A brake
const int MotorBDirectionPin = 13; //digital pin value for A direction
const int MotorBSpeedPin = 11; //analog pin value for A speed (PWM)
const int MotorBBrakePin = 8; // digital pin value for A brake
//Motor Control Values
int BrakeA = LOW; //Brake for motor A, LOW = motor off, HIGH = motor on
int BrakeB = LOW;
int DirectionA = HIGH; //Direction for motor A, LOW/HIGH are opposite (based on wiring) assume Low is forward
int DirectionB = LOW;
int SpeedA = 0; //Speed for motor A, PWM value from 0 - 255 (0 is off)
int SpeedB = 0;
int encoder0stop = 469.125; //stop value for encoder 0
int encoder1stop = 469.125; //stop value for encoder 1

void setup() {
  //Set Digital I/O pins 2 and 4 to inputs for encoder
  pinMode (encoder0PinA, INPUT);
  pinMode (encoder0PinB, INPUT);
  pinMode (encoder1PinA, INPUT);
  pinMode (encoder1PinB, INPUT);
  //Set Digital I/O pins as outputs for motorshield
  //Analog pins are already set so don't have to initialize speed pins
  pinMode(MotorADirectionPin, OUTPUT);
  pinMode(MotorABrakePin, OUTPUT);
  pinMode(MotorBDirectionPin, OUTPUT);
  pinMode(MotorBBrakePin, OUTPUT);
  //Start serial monitor at 9600
  Serial.begin (9600);
  delay (0);
  Serial.print("Last Enc State");
  Serial.print(" ");
  Serial.print("Current Enc State");
  Serial.print(" ");
  Serial.print("Encoder Count");
  Serial.print(" ");
  Serial.print("Speed");
  Serial.print(" ");
  Serial.print("Brake");
  Serial.print(" ");
  Serial.print("Direction");
  delay(2000);
}

void loop() {
  if (i == 0) {
    analogWrite(MotorASpeedPin, 255); //set motor A speed
    analogWrite(MotorBSpeedPin, 255); //set motor B speed
    i++;
  }
  //Set values to write to arduino
  if (encoder0Pos < encoder0stop) {
    //if hasn't reached end encoder value
    //Direction Forward, Brake OFF, speed 125
    DirectionA = HIGH;
    DirectionB = LOW;
    BrakeA = LOW;
    BrakeB = LOW;
    SpeedA = 254;
    SpeedB = 253;
  } else {
    //if has reached encoder value
    //Direction Forward, Brake ON, speed 0
    DirectionA = HIGH;
    DirectionB = LOW;
    BrakeA = HIGH;
    BrakeB = HIGH;
    SpeedA = LOW;
    SpeedB = LOW;
  }

  //Write all values to the arduino
  digitalWrite(MotorADirectionPin, DirectionA); //set motor A direction
  digitalWrite(MotorBDirectionPin, DirectionB); //set motor B direction
  digitalWrite(MotorABrakePin, BrakeA); //write motor A brake on/off
  digitalWrite(MotorBBrakePin, BrakeB); // write motor B brake on/off
  analogWrite(MotorASpeedPin, SpeedA); //set motor A speed
  analogWrite(MotorBSpeedPin, SpeedB); //set motor B speed
  //Read Encoder
  //This is reading PinA which should be set to pin 2 and storing it as n
  n = digitalRead(encoder0PinA);
  //Check to see if pin 2 has changed from LOW to HIGH
  if ((encoder0PinALast == LOW) && (n == HIGH)) {
    //Check to see if pin 4 is LOW -> this determines which direction the encoder is going
    if (digitalRead(encoder0PinB) == LOW) {
      //encoder is going "backwards" decrease encoder position
      encoder0Pos--;
    } else {
      //If pin 4 is HIGH
      //encoder is going "forward", increase encoder position
      encoder0Pos++;
    }
    //Tell us what is happening!
    Serial.print (encoder0Pos);
    //go to the next line of code
    Serial.print(" ");
    Serial.print(encoder0PinALast);
    Serial.print(" ");
    Serial.print(n);
    Serial.print(" ");
    Serial.print(encoder0Pos);
    Serial.print(" ");
    Serial.print(SpeedA);
    Serial.print(" ");
    Serial.print(BrakeA);
    Serial.print(" ");
    Serial.print(DirectionA);
    Serial.println();
    encoder0PinALast = n;
  }
  //Set what the last read of pin 2 was so we can compare to see if it changes
  encoder0PinALast = n;
  //End Code for Encoder Reading
}

```

# Answer
> 1 votes
I would say that one of the solutions would be to arrange the code in your car into a finite state machine. So your states would be something like:

1. Start (reset the encoders and set the initial speed)
2. Go straight (both motors at 100%)
3. Turn left (left motor at 75%, right at 100%)
4. Turn right (right motor at 75%, left az 100%)
5. Stop (stop both motors)

Example code:

```
//TODO: Init program and variables
void go_straight()
{
    if(number_of_rotations > 10)
    {
        state = TURN_LEFT
    }
    else
    {
        motor_left = 100;
        motor_right = 100;
    }
}
void turn_left()
{
    if(number_of_rotations > 10)
    {
        state = TURN_RIGHT
    }
    else
    {
        motor_left = 100;
        motor_right = 75;
    }
}
//TODO: Implement remaining methods

void loop()
{
    //Update number of rotations since state change
    update_rotations();
    if(state == START)
        start();
    else if(state == GO_STRAIGHT)
        go_straight();
    else if(state == TURN_LEFT)
        turn_left();
    else if(state == TURN_RIGHT)
        turn_right();
    else
        stop();
    //This code gets executed on every loop cycle and is not dependent on state
    print_status();
    wait(100);
}

```

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


# Question
Title: Working on my second project and I'm confused about proper procedure for turning on the arduino
The first project I did was just making the led blink (it was pulsing a signal to pin 13. I'm guessing most of you have seen similar tutorials).

Today I plugged in some wires and resistors and wrote a program for a volt meter.

How am I to stop the pulses on the output pins from my previous project from messing everything up in the newer project in that interval of time after plugging in the usb and before compiling/ uploading the new code?

The question occurred to me when I saw the led blinking from the last project, before I could hit the upload button... maybe I'm wrong, but I'm envisioning this causing problems for me in the future as my circuits become more and more complex.

# Answer
If you've rewired an Arduino board for a new project, such that outputs from the currently-loaded sketch may cause problems, temporarily jumper from ground to Reset, to hold the MCU (ATmega328, etc.) in reset until you are ready to load the new sketch. Pull the jumper upon starting a download, of either your new project or an empty sketch as suggested in Majenko's comment. Typically, Arduinos are reset at the beginning of each download.

Arduino boards (Uno, Nano, Mega, et al) that use an additional chip (FT232, Atmega16U2 or 32U4, CH340G, etc) as a USB interface should be able to register as USB devices even when the MCU is reset. Arduino boards without a separate USB chip (Leonardo, Micro, et al) should not.
> 1 votes

---
Tags: arduino-ide
---


# Question
Title: How to make the motor move after a certain period of time?
Basically I want my motor to run after let's say 10 seconds passed since the program started up.

The amount of time is determined by user input, and I have already coded for that. The motor is connected to a breadboard and powered by a 9v battery, also connected to the breadboard.

The thing is, the motor runs as soon as I connect it to the breadboard. How can I use the Arduino board to make the motor wait 10 seconds before it moves? I am new to both circuitry and code... Sorry for my cluelessness.

Thanks so much.

# Answer
> 3 votes
You will need to add a logic level mosfet of the appropriate size and specs to control the power to the motor. You can drive the gate of the mosfet from a pin through a current limiting resistor with a larger bleed resistor. For a brushed motor you'll need a ceramic RF supressor cap plus flyback diode for back EMF protection:

simulate this circuit – Schematic created using CircuitLab

For greater RF supression (if your motor is pretty beefy) you can use a 0.1uF between each input lead and the motor case.

When you turn the pin on, motor turns on, low turns off. Using analog and appropriate R values you can control motor speed (setting 0-255):

```
int motorControl = [your pin];

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

void loop()
{
  delay(10000); // delay 10 seconds plus board boot time
  analogWrite(motorControl, 255); // turn motor on full
}

```

You can time the delay with a stop watch and adjust to be exactly 10s by dropping the delay() call to compensate for the boot up time of the board.

More about MOSFETS here:

https://electronics.stackexchange.com/questions/81935/mosfet-usage-and-p-vs-n-channel

# Answer
> 0 votes
I would recommend connecting the motor to a controller of some sort of a controller, maybe a relay or something like that, and then write some code that waits 10 seconds, and then turns on your controller / relay. That will turn on the motor.

---
Tags: motor
---


# Question
Title: Storing data on AT24C02 EEPROM chips with Arduino
I have recently come across some 8-pin 128-byte EEPROM chips. I've seen those USB EEPROM chip programmer units, but I was wondering if there is any way I could manually store data on the chip with my Arduino.

I don't have any application for the chips yet, but I would just like to see if I can read / write data on the chips.

Here's the data sheet for the chips.

# Answer
You wire your chips on a breadboard, with the +/- left rail for Vcc/GND, and the right +/- rail for SCL/SDA, plus a little acrobatics to connect everything.

Your chips can have 8 addresses, 0x50 to 0x57, set up with the A0/1/2 pins: all low = 0x00, all high = 0x07. The you read and write to the EEPROM of your choice with:

```
char i2c_eeprom_read_char(int deviceaddress, unsigned int eeaddress) {
  char rdata = 0xFF;
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8)); // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.endTransmission();
  Wire.requestFrom(deviceaddress,1);
  if (Wire.available()) rdata = Wire.read();
  return rdata;
}

void i2c_eeprom_write_char(int deviceaddress, unsigned int eeaddress, char data) {
  int rdata = data;
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8)); // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.write(rdata);
  Wire.endTransmission();
}

```

If you have more than 8 chips (well throw them away and get larger ones, but anyway, for completeness sake): wire all of them with A1/A2 to GND, and each A0 to a different digital pin. When you need to access a chip, set all A0s to LOW, except the one you want to HIGH, and use 0x51 as the address. By doing this you're setting all chips except the one you want to address 0x50 (which doesn't matter) leaving only one at 0x51. That enables you to have as many chips as you have free digital pins...
> 1 votes

---
Tags: memory, flash, hardware
---


title: Arduino audio frequency reader

text:
# Question
Title: Arduino audio frequency reader
I have a simple project for my arduino : light some leds when i send a certain frequency from my smartphone through the jack output . For example , I play a simple audio file generated with a frequency generator (it generates sinwaves, sawtooth, quadrate waves...) at 1kHz --\> a red led turns on I play another frequency (5kHz) --\> a green led turns on. I read similar questions , but they needed a precise reading of the signal frequency, so they had to convert from AC to DC and from 700mV to 2,5V, is it necessary in my case ? I can also prepare a track with a program called audacity with the current remaining always positive but oscillating between 0 and 0,7 mV. How can i realize my project in the simplest way possible ?

Thank you

# Answer
> 1 votes
Connect the signal to an analogue input on the Arduino, via a DC blocking capacitor, with a potential divider centring it around 2.5v. Make sure the voltage swing is within range, which it should be.

Keep the frequencies of the signal low, under say 2KHz. For example, use 500Hz, 1000Hz, 1500Hz, 2000Hz.

Sample (`analogRead()`) the signal as fast as you can (which is about 10KHz) for a short while, recording the min and max values. From this, you can find the centre value, 1/4 value and 3/4 value.

Now to find your frequency, sample until the signal goes above the 3/4 value. Get the time with `micros()`. Sample until the signal goes below 1/4, and then sample until it goes above 3/4 again and get the time with `micros()`. Do this a few times and average them. The difference between the two times is *approximately* your sample period, so you can easily find the frequency.

Determine which of your chosen frequencies most closely matches the frequency you've sampled.

# Answer
> 1 votes
If you can properly bias your signal, say with a cap and a pot, you could read it with a digital input. You can then time the rising edges with `micros()`, either by polling the pin or using an interrupt. You could achieve greater accuracy by using the “input capture” feature of a 16-bit timer, if you are using an AVR-based Arduino and are not afraid of getting your hands dirty with low-level programming.

You need to get the right voltage range for this to work though. On an Arduino Uno, for example, the thresholds for the input switching from `HIGH` to `LOW` and back are typically around 2.1 and 2.6 V respectively, so you must make sure that your signal amply covers this range. If you can get 1 V peak to peak, that should be enough, and you can then use the pot to tune the offset.

---
Tags: analogread, audio, android, frequency, signal-processing
---


# Question
Title: ESP8266-12E and MCP23017 , unable to identify the application
After googling much I have found that MCP23017 can be used with esp8266-12e for more number of output pins. I have tried all the programs from different tutorials on internet but could not make it work.

Basically my question is , i want to control all the 16 leds connected to GPA0-7 AND GPB0-7 individually , hence i need a program snippet for make it work. I am using AP mode for esp8266-12e and sending get methods with params to identify which led to turn on/off.

Even i have written the basic program , can anyone help me completing the entire program. thanks for the help in advanced.

Pins i have connected are

```
ESP8266-12E    |   MCP23017
−−−−−−−−−−−−−−−+−−−−−−−−−−−−−−
GPIO-14 (scl)  |  PIN-12 (SCL)
GPIO-2 (sda)   |  PIN 13 (SDA)
GND            |  A0,A1,A2

```

My code:

```
#include <Wire.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);

void handleRoot() {
    server.send(200, "text/html", "<h1>You are connected</h1>");
}

void setup() {
    delay(1000);
    Serial.begin(115200);
    Serial.println();
    Serial.print("Configuring access point...");
    WiFi.softAP(ssid, password);

    IPAddress myIP = WiFi.softAPIP();
    Serial.print("AP IP address: ");
    Serial.println(myIP);
    server.on("/", handleRoot);

    server.on("/led1", [](){});
    server.on("/led2", [](){});
    server.on("/led3", [](){});
    server.on("/led4", [](){});
    // up to 16 leds i have written same method.

    server.begin();
}

void loop() {
    server.handleClient();
}

```

# Answer
You have an MCP23017 which connects to the device using the I2C protocol, which means you need the library. You also need to ensure that SCL and SDA are 'pulled up' using 4.7Kohm resistors between the data lines and the +ve line. You will then need to send commands to the device to initialise it and set the pins to OUTPUT. (See http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf).

When running you will need to update the state of this pins by sending messages such as 0x09 0xFF to turn them all on.

It is going to be worth looking for a library that already does all this, but writing your own shouldn't be too hard. You will be able to use an Arduino library on an ESP8266.

These chips are the easiest ones to use and learn about I2C, so its worth looking at the manual and trying to write your own "library" (Just start by writing a C++ class within your sketch folder.)
> 1 votes

---
Tags: programming, arduino-ide, esp8266, i2c
---


# Question
Title: Run different code on different type of reset in arduino nano
I would like to program the arduino such that if I reset it by disconnecting and then reconnecting the usb.. A particular led glows BUT If I press the manual reset button on my nano... I want a different led to glow. How can I achieve this. I have 2 leds and my nano... Along with the laptop and any other necessary components.

# Answer
The MCUSR register (page 79 of the datasheet) tells you what kind of reset happened most recently. As long as the USB interface chip on your nano isn't controlling the RESET pin without the port being opened (i.e., toggling it at power up regardless of the USB state) then you could query that register to see how it reset:

```
if (MCUSR & (1 << 0)) { // POR
    digitalWrite(4, HIGH);
} else if (MCUSR & (1 << 1)) { // External Reset
    digitalWrite(5, HIGH);
}

```

However, if the USB chip does toggle the RESET pin then there is no way you can distinguish between the two resets since they are bot the same "external" reset using the RESET pin.
> 2 votes

---
Tags: arduino-nano, reset
---


# Question
Title: How do I "conditionally" include libraries and declare global objects of them?
I'm trying to write a generic "Test Bench" type of sketch using booleans to indicate whether or not to include specific libraries. After those are defined, I'm attempting to use preprocessor #if statements to determine if the libraries need to be included and create the objects if need be.

Example:

```
const bool useLCD = true;

...

#if (useLCD)
  #include "NHD_4x20.h"
  NHD_4x20 lcd(9);
#endif

```

These statements are before the setup() and loop() functions. This in itself doesn't generate compiler errors, however I get "lcd has not been defined in this scope" when trying to use the object in the setup() and loop() functions.

Is there some simple trick to accomplish this that I'm overlooking here ?

Thanks in advance !

# Answer
> 3 votes
```
const bool useLCD = true;

```

should be:

```
#define useLCD 1

```

---

Here is a complete working example of how to use preprocessor macros for conditional compilation:

```
#define USE_A 1
// #define USE_B 1

#if (USE_A)
int a = 4;
#endif

#if (USE_B)
int b = 6;
#endif

void setup() {
    Serial.begin(115200);
    Serial.print(F("The result is: "));
#if (USE_A)
    Serial.println(a * 2);
#endif
#if (USE_B)
    Serial.println(b * 2);
#endif
}

void loop() {
}

```

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


title: Power save Sleep Mode Arduino

text:
# Question
Title: Power save Sleep Mode Arduino
I'm trying to use this example link

source:

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

/* Sleep Demo Serial
 * -----------------
 * Example code to demonstrate the sleep functions in an Arduino.
 *
 * use a resistor between RX and pin2. By default RX is pulled up to 5V
 * therefore, we can use a sequence of Serial data forcing RX to 0, what
 * will make pin2 go LOW activating INT0 external interrupt, bringing
 * the MCU back to life
 *
 * there is also a time counter that will put the MCU to sleep after 10 secs
 *
 * NOTE: when coming back from POWER-DOWN mode, it takes a bit
 *       until the system is functional at 100%!! (typically <1sec)
 *
 * Copyright (C) 2006 MacSimski 2006-12-30
 * Copyright (C) 2007 D. Cuartielles 2007-07-08 - Mexico DF
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

int wakePin = 2;                 // pin used for waking up
int sleepStatus = 0;             // variable to store a request for sleep
int count = 0;                   // counter

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

void setup()
{
  pinMode(wakePin, INPUT);

  Serial.begin(9600);

  /* Now it is time to enable an interrupt. In the function call
   * attachInterrupt(A, B, C)
   * A   can be either 0 or 1 for interrupts on pin 2 or 3.
   *
   * B   Name of a function you want to execute while in interrupt A.
   *
   * C   Trigger mode of the interrupt pin. can be:
   *             LOW        a low level trigger
   *             CHANGE     a change in level trigger
   *             RISING     a rising edge of a level trigger
   *             FALLING    a falling edge of a level trigger
   *
   * In all but the IDLE sleep modes only LOW can be used.
   */

  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                                      // wakeUpNow when pin 2 gets LOW
}

void sleepNow()         // here we put the arduino to sleep
{
    /* Now is the time to set the sleep mode. In the Atmega8 datasheet
     * http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf on page 35
     * there is a list of sleep modes which explains which clocks and
     * wake up sources are available in which sleep mode.
     *
     * In the avr/sleep.h file, the call names of these sleep modes are to be found:
     *
     * The 5 different modes are:
     *     SLEEP_MODE_IDLE         -the least power savings
     *     SLEEP_MODE_ADC
     *     SLEEP_MODE_PWR_SAVE
     *     SLEEP_MODE_STANDBY
     *     SLEEP_MODE_PWR_DOWN     -the most power savings
     *
     * For now, we want as much power savings as possible, so we
     * choose the according
     * sleep mode: SLEEP_MODE_PWR_DOWN
     *
     */
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    sleep_enable();          // enables the sleep bit in the mcucr register
                             // so sleep is possible. just a safety pin

    /* Now it is time to enable an interrupt. We do it here so an
     * accidentally pushed interrupt button doesn't interrupt
     * our running program. if you want to be able to run
     * interrupt code besides the sleep function, place it in
     * setup() for example.
     *
     * In the function call attachInterrupt(A, B, C)
     * A   can be either 0 or 1 for interrupts on pin 2 or 3.
     *
     * B   Name of a function you want to execute at interrupt for A.
     *
     * C   Trigger mode of the interrupt pin. can be:
     *             LOW        a low level triggers
     *             CHANGE     a change in level triggers
     *             RISING     a rising edge of a level triggers
     *             FALLING    a falling edge of a level triggers
     *
     * In all but the IDLE sleep modes only LOW can be used.
     */

    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                                       // wakeUpNow when pin 2 gets LOW

    sleep_mode();            // here the device is actually put to sleep!!
                             // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

    sleep_disable();         // first thing after waking from sleep:
                             // disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the
                             // wakeUpNow code will not be executed
                             // during normal running time.

}

void loop()
{
  // display information about the counter
  Serial.print("Awake for ");
  Serial.print(count);
  Serial.println("sec");
  count++;
  delay(1000);                           // waits for a second

  // compute the serial input
  if (Serial.available()) {
    int val = Serial.read();
    if (val == 'S') {
      Serial.println("Serial: Entering Sleep mode");
      delay(100);     // this delay is needed, the sleep
                      //function will provoke a Serial error otherwise!!
      count = 0;
      sleepNow();     // sleep function called here
    }
    if (val == 'A') {
      Serial.println("Hola Caracola"); // classic dummy message
    }
  }

  // check if it should go to sleep because of time
  if (count >= 10) {
      Serial.println("Timer: Entering Sleep mode");
      delay(100);     // this delay is needed, the sleep
                      //function will provoke a Serial error otherwise!!
      count = 0;
      sleepNow();     // sleep function called here
  }
}

```

I'm using a Tester for test really efficient of power saving; I read only a power save of 2 mA. Is it possible the Arduino Mega saves only that in sleep mode? Or am I doing something wrong?

# Answer
I have a page about power saving. About the first suggestion on that page is to not use an Arduino "board" (particularly one with a USB interface chip, power LED and voltage regulator). They all take power - a lot of it. These boards are designed for prototyping, not low-power use in the field.

Something like this would be better:

Of course, that isn't an Atmega2560 chip. They only come in surface-mount and will be hard to solder yourself. You may be able to get an Atmega2560 board in minimal form. Or downgrade to a smaller processor that you can assemble yourself. The Atmega644P comes in PDIP which is easy enough to work with.

If you don't need all that RAM and program memory, you could go down to an Atmega328P which are easy to work with and can get down to 100 nA power consumption under the right circumstances.

---

You could conceivably do what Edgar Bonet suggested and cut traces on your Mega2560 board, but be warned that if you do that you won't be able to program the board via the USB interface afterwards. You can still program via the ICSP socket however, if you have a suitable programmer.

---

> What are you using as resonator there?

This one - I can't remember where I got it from.

The Arduino Uno has a resonator on it for the main chip (not a crystal) so using a resonator is fine.
> 2 votes

---
Tags: arduino-mega, power
---


# Question
Title: On extending scrolling 8x8 bitmap to 32x32 or 32x64 (see clip)
I am using an Adafruit 64x32 RGB LED panel with my Arduino Mega 2560. I tried to find/construct working examples of a 32x32 or wider scrolling text/bitmap but have failed.

The smaller version is working and is calling two functions for it to implement:

```
loadSprite(IMAGES2,60);
bildmittig_sprite(data,dpink,300);

```
* `IMAGES2` is of type `const PROGMEM byte IMAGES2[][8]` and is an array of several 8x8 bitmaps
* `data` is a buffer data array element, containing the dynamic movement of bitmaps, called in the `void loop()`

For the whole code here. For the video clip smaller scroller here.

For the video clip to what I would like to extend to:

> Russian Letters: http://dropbox.com/s/n2ilxqgubn83ii9/MOV\_0056.mp4?dl=0
> Or Chinese Letters: http://dropbox.com/s/9rad116adc575u1/MOV\_0057.mp4?dl=0

`loadSprite()` looks like this:

```
void loadSprite(const PROGMEM byte bild[][8],int anzahl) {
  for(int row=0; row < 8; row++) {
    //iterate through each row
    data[row] = 0;
    //reset the row we're working on
    for(int column=0; column < 8; column++) {
      //iterate through each column
      data[row] = data[row] + ((powers[column] & (pgm_read_byte(&(bild[index][row])) << offset)));
      //loads the current charachter offset by offset pixels
      data[row] = data[row] + (powers[column] & (pgm_read_byte(&(bild[index+1][row])) >> (8-offset)));
      //loads the next charachter offset by offset pixels
    }
  }
  offset++;
  //increment the offset by one row
  if(offset==8){offset = 0; index++; if(index==anzahl){index=0;}}
  //if offset is 8 load the next character pair for the next time through
}

```

The displaying function (places it i the middle of 32x32 panel) like this:

```
void bildmittig_sprite (byte bild[8],word cchsv, int duration) {
  for(int i = 0; i <8; i++) {
    for(int ii = 0; ii<8; ii++) {
      int bit = (bild[i] >> ii) & 1;
      if(bit == 0) {
        matrix.drawPixel(7-ii+12, 12+i, black);
      } else {
        matrix.drawPixel(7-ii+12, 12+i, cchsv);
      }
    }
  }
  delay(duration);
}

```

Working for 8x8 bitmaps, It eludes me how I could possible extend the coding (scrolling) for bitmaps like this:

```
const PROGMEM unsigned char rus5[] = {
  0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0xff, 0x03,
  0x00, 0x00, 0x78, 0x00,
  0x00, 0x00, 0x38, 0x00,
  0x00, 0x00, 0x3c, 0x00,
  0x00, 0x00, 0x1c, 0x00,
  0x00, 0x00, 0x1c, 0x00,
  0x00, 0x00, 0x1e, 0x00,
  0x00, 0xfc, 0xde, 0x0f,
  0x00, 0x8f, 0xef, 0x1f,
  0x80, 0x07, 0x3f, 0x3c,
  0xc0, 0x03, 0x0f, 0x3c,
  0xe0, 0x01, 0x0f, 0x3c,
  0xe0, 0x01, 0x07, 0x3c,
  0xf0, 0x80, 0x07, 0x3c,
  0xf0, 0x80, 0x03, 0x3c,
  0x70, 0x80, 0x03, 0x1e,
  0x78, 0xc0, 0x03, 0x1e,
  0x78, 0xc0, 0x03, 0x0f,
  0x78, 0xe0, 0x01, 0x0f,
  0x78, 0xf0, 0x81, 0x07,
  0xf0, 0xf8, 0xc3, 0x03,
  0xf0, 0xef, 0xf6, 0x01,
  0xe0, 0xf7, 0x7c, 0x00,
  0x00, 0xf0, 0x00, 0x00,
  0x00, 0x70, 0x00, 0x00,
  0x00, 0x70, 0x00, 0x00,
  0x00, 0x78, 0x00, 0x00,
  0x00, 0x78, 0x00, 0x00,
  0x00, 0x7c, 0x00, 0x00,
  0x80, 0xff, 0x03, 0x00,
  0x00, 0x00, 0x00, 0x00
};

```

I tried variants of concatenation, like:

* 4 bytes as a row, stitching together several with beforehand created `data` (`data1` `...` `data4`) elements (also adjust coherence for vertical elements).
* And then have them displayed at the correct place to be able to use the existing code but so far only vertical concatenation seemed to work briefly.

I am at the end of my wits for this project, but maybe somebody else sees a better way.

# Answer
> 0 votes
I've looked at your code briefly, long enough to get the impression that each array like `rus5[]` contains 32 groups of 4 bytes each, with each 4-byte group representing a row of a character. \[If not, let me know.\] Also, I read the question a time or two, but don't see specified what direction you want to scroll, and whether you will scroll a string of characters or just one character. Anyhow, in following I suppose you want to scroll a string horizontally with characters entering at the right end of the display and scrolling off the left end.

To support horizontal scrolling, arrange your bit maps such that each group of 4 bytes represents the 32 bits of a single column of the display. Regarding four bytes as an unsigned long, suppose the LSB (least significant bit) corresponds to the top LED in a column. Use code like the following to set pixels, supposing `cn` = current column number; `d` = number of character columns already scrolled off, in range 0 to 31; `maxCol` = number of display columns; and `t[]` is a three-character string corresponding to three characters currently on the 64x32 display. \[That is, a right-hand part of `t[0]` is at the left end of display; then all of `t[1]` appears; then a left-hand part of `t[2]`.\] \[Generally, where this sets `cc=0`, you would set it to point at a current-character in a longer string, instead of at the first character in a three-character array `t[]`; and would advance one character each time `d` gets up to 32.\]

```
cc = 0;     // index of first character to display
c = t[cc];  // first character to display
e = d;      // how far we have scrolled so far
for (cn=0; cn<maxCol; ++cn) {
  unsigned long colData = pgm_read_dword(charData[c][e]);
  for (ro=0; ro<32; ++ro) {
    matrix.drawPixel(cn, ro, (colData&1)? cchsv : black);
    colData >>= 1; // discard used-up bit
  }
  ++e;
  if (e >= 32) {  // Done with current character?
    c = t[++cc];  // Set c to next character
    e = 0;        // Start with leftmost col of character
  }
}

```

*Edit 1:* In the code above, `charData[c][e]` is an unsigned long int. Its 32 bits represent column `e` of ascii character `c`, with the LSB representing the top-row pixel. To create `charData[][]`, write a program on your development system that reads whatever bitmaps you have now and writes out code to properly set up `charData[][]` in ProgMem.

Note, for initial scroll-testing, you could skip writing a development-system program to re-orient characters and instead test with character-data arrays as they are. Characters might display sideways or upside down, but would scroll ok anyway. Or, if bytes are not in proper Endianness to be an unsigned long, they would display in four mis-ordered slices.

*Edit 2* With the following code,

```
void  scroller (const PROGMEM byte bildo1[][4],const PROGMEM byte bildo2[][4],int maxCol, word cchsv) {

int d = 0;
int cc = 0;
unsigned long c[32];

for(int ii=0;ii<32;ii++) {
  c[ii]=0;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][0]))<< 24;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][1]))<< 16;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][2]))<< 8;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][3]));
}
int e = d;      // how far we have scrolled so far
for (int cn=0; cn<maxCol; ++cn) {
  unsigned long colData = c[e];
  for (int ro=0; ro<32; ++ro) {
    matrix.drawPixel(cn, ro, (colData&1)? cchsv : black);
    colData >>= 1; // discard used-up bit
  }
  ++e;
  if (e >= 32) {  // Done with current character?
    for(int ii=0;ii<32;ii++) {
      c[ii]=0;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][0]))<< 24;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][1]))<< 16;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][2]))<< 8;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][3]));
    }
    e = 0;        // Start with leftmost col of character
  }
}}

```

chrisoutwright reports getting an image like the following \[cropped from a larger dropbox.com image\]:

Cutting this into 4 equal-size horizontal slices and swapping slices top to bottom, we get:

That image suggests packing the bytes in reverse order, eg via

```
c[ii] += (long) pgm_read_byte(&(bildo2[ii][0]));
c[ii] += (long) pgm_read_byte(&(bildo2[ii][1]))<< 8;
c[ii] += (long) pgm_read_byte(&(bildo2[ii][2]))<< 16;
c[ii] += (long) pgm_read_byte(&(bildo2[ii][3]))<< 24;

```

Continuing on, if we rotate the left half of the above 90° then flip the rotated image left to right we get a reasonable facsimile of the letter 春 :

The "flip left to right" amounts to reading bits out MSB first instead of LSB first. During testing, one might do that by saying

```
matrix.drawPixel(cn, ro, (colData&(1<<31))? cchsv : black); colData <<= 1;

```

instead of

```
matrix.drawPixel(cn, ro, (colData&1)? cchsv : black); colData >>= 1;

```

but in the longer run, a development-system program should be used to re-orient characters instead of using up MCU memory space and time for bitmap organizing.

---

To make the characters scroll, add a parameter (eg, `byte escroll`) to the calling sequence. Discard variable `d` if it isn't used within scroller, and instead of initializing `e` to `d` (which is always zero hence does not allow for scrolling) initialize it via

```
e = escroll;

```

In the routine that calls `scroller()`, say something like

```
byte es=0;
while (scrolling) {
  scroller(bildo1, bildo2, maxCol, cchsv, es);
  delay(msPerScrollStep);
  ++es;
  if (es >= 32) {
    es = 0;
    // do stuff here about next characters to display
  }
}

```

That is, call `scroller()` within a scroll-timing loop (or perhaps put the timing into `scroller()`, whichever meshes better with overall design).

Note, with the code as it stands, plus suggested changes, `bildo2` will scroll in a second time unless a third character is supplied to scroll in.

For example, with `maxCol` of 64, if `es` is 16, when`scroller()` is called, `e` will go from 16 to 31 displaying the second half of `bildo1`, then from 0 to 31 displaying all of `bildo2`, then from 0 to 15 displaying the front half of `bildo2`.

---
Tags: rgb-led
---


title: Arduino library making

text:
# Question
Title: Arduino library making
I make my own library for arduino.

The file structure is like below.

```
AAA - README.md
    - examples - A - A.ino
               - B - B.ino
    - AAA.h
    - BBB.h
    - CCC.h
    - BBB.cpp
    - CCC.cpp

```

It works well. But I want to grouping a library source files like below.

```
AAA - same as above
    - src - AAA.h
          - BBB.h
          - CCC.h
          - BBB.cpp
          - CCC.cpp

```

It doesn't work at all.

Arduino IDE shows the message

> Specified folder/zip file does not contain a valid library.

But, WiFi101 library was made by src folder. Why isn't it possible for mine?

# Answer
> 2 votes
I'm going to assume your library structure is like this because the structure you described above would not cause that error:

```
AAA
|_src
    |_AAA.h
    |_BBB.h
    |_CCC.h
    |_BBB.cpp
    |_CCC.cpp

```

To be considered valid by the Arduino IDE, a library must either have a .h file in the root folder or a library.properties file if you are using the 1.5 library format. Putting all the source files in the `src` subfolder means your library is in the 1.5 library format. So you need to add a library.properties file in the root of the library formatted as described here: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#libraryproperties-file-format. Then your library should look like this:

```
AAA
|_library.properties
|_src
    |_AAA.h
    |_BBB.h
    |_CCC.h
    |_BBB.cpp
    |_CCC.cpp

```

---
Tags: arduino-ide, library
---


# Question
Title: I2C to UART bridge as breakout or in DIP package
For a project, I need to connect more than one device to an Arduino through a serial port with hardware flow control (RTS/CTS).

Sparkfun used to make breakout boards for the SC16IS750, but this product is discontinued and I can't find any place to order it. There are also plenty of ICs doing what I need, but I am not keen on soldering SMD components and I cannot find any products coming in e.g. an old fashioned DIP package.

Does someone know about an available breakout board or a DIP packages I2C to UART bridge? Since the device will be battery powered, I would prefer a dedicated low-power circuit instead of a programmed microcontroller as suggested by majenko.

# Answer
> 2 votes
Perhaps what you're looking for:

http://sandboxelectronics.com/?product=sc16is750-i2cspi-to-uart-bridge-module

---

From that page:

> ## SC16IS750 I2C/SPI to UART Bridge Module
>
> This module is designed to enable I2C/SPI to UART conversion. It works in I2C/SPI slave mode and interfaces with devices working in I2C/SPI master mode. There are also 4 extra GPIOs for IO expansion. NXP SC16IS750 is used as the key component on this module. Flow control and modem signals are also supported.
>
> This module is useful when extra UART interface is needed. Due to the multi-slave characteristics of I2C and SPI, many UART interfaces could be added to the system at the same time.

---
Tags: i2c, uart
---


# Question
Title: Why is my Serial port not printing the right output?
am working with and Arduino nano and according to this, I can append strings to numbers by doing: `stringThree = stringOne + 123;` but when I do:

```
sensorValue = analogRead(A0);
String x1 = "{\"Volt\":"+sensorValue;
Serial.print(x1);

```

I get this unwanted output!

> =gëÙrïË:\_³ß»þ™¹Æ3+Ç#ÿ¼¿.Õ\[Oû/g¯\>ïÿ1þ†lú0

but doing this it works fine.

```
sensorValue = analogRead(A0);
String x1 = "{\"Volt\":";
x1 += sensorValue;
Serial.print(x1);

```

> "Volt":646

why?

# Answer
> 4 votes
In the first example you are adding an integer to the address of a string literal and then converting it to a `String`.

In the second example you are converting a string literal to a `String` and then appending an integer.

The key point here is *string literal*. The compiler just sees it as an address in flash memory. It's down to the functions you use with that address that define it as a string. So when you add an integer to it you are just adding an integer to the address, which of course changes the address. So then when you go to convert whatever is at that address to a `String` you end up with garbage.

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


title: Multi Level Button Menu

text:
# Question
Title: Multi Level Button Menu
Have been working on a Button Menu for a while now and can't break thru to the 3rd level, which in theory would give access to levels 4/5/6/etc. It's layed out long hand, I'll neaten the code up after its working. Could you pls have a look and see if you can access level 3.... Also if there is an alternative for ***multi level menus***, happy to look at those also, just after something that works, have tried dozens that i have found on the web.....either no sketch with the video(how i hate that) or sketch just doesn't work period. Thanks in advance Doug

```
    /*
Description : Simple Menu function on LCD
          Button Function:
            Up/Down - change Menu Page
            Select - enter page
            Left - Exit

Link: http://youtu.be/cMqif5ICS5M

+++++++++++++++++++++++++++++++++++++++++++++++++++*/
*/
#include <LiquidCrystal_I2C.h> //from newliquidcrystal library
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

int keypad_pin = A0;
int keypad_value = 0;
int keypad_value_old = 0;

bool menu2 = false;
char btn_push;

int selection1 = 0;
int selection2 = 0;

int mainMenuPage = 1;
int mainMenuPageOld = 1;
int mainMenuTotal = 4;

int levelMenuPage = 1;
int levelMenuPageOld = 1;
int levelMenuTotal = 4;

void setup()
{
  Serial.begin(9600);
lcd.begin(20, 4);  //Initialize a 2x16 type LCD

MainMenuDisplay();
delay(1000);

}
void loop()
{
MainmenuBtn();

if((btn_push == 'S')&&(menu2 == false))//enter selected menu
{
  Serial.println("i'm here");
    WaitBtnRelease();
    switch (mainMenuPage)
    {
        case 1:
          MenuA();
          break;
        case 2:
          MenuB();
          break;
        case 3:
          MenuC();
          break;
        case 4:
          MenuD();
          break;
    }

      MainMenuDisplay();
      WaitBtnRelease();
  }
  else
{
   if((btn_push == 'S')&&(menu2 == true))//enter selected menu
{
  LevelmenuBtn();
    WaitBtnRelease();
    switch (levelMenuPage)
    {
        case 1:
          MenuA2();
          break;
        case 2:
          MenuB2();
          break;
        case 3:
          MenuC2();
          break;
        case 4:
          MenuD2();
          break;
    }

      LevelMenuDisplay();
      WaitBtnRelease();
  }

  delay(10);
}
}
//--------------- End of loop() loop ---------------------
void MainmenuBtn()
{
  btn_push = ReadKeypad();
WaitBtnRelease();
if(btn_push == 'U')
{
    mainMenuPage++;
    if(mainMenuPage > mainMenuTotal)
      mainMenuPage = 1;
      Serial.println(mainMenuPage);
}
else if(btn_push == 'D')
{
    mainMenuPage--;
    Serial.print(mainMenuPage);
    if(mainMenuPage == 0)
      mainMenuPage = mainMenuTotal;
      Serial.println(mainMenuPage);
}

if(mainMenuPage != mainMenuPageOld) //only update display when page change
{
    MainMenuDisplay();
    mainMenuPageOld = mainMenuPage;
}
}
void LevelmenuBtn()
{
  btn_push = ReadKeypad();
WaitBtnRelease();
if(btn_push == 'U')
{
    mainMenuPage++;
    if(levelMenuPage > levelMenuTotal)
      levelMenuPage = 1;
      Serial.println(levelMenuPage);
}
else if(btn_push == 'D')
{
    levelMenuPage--;
    Serial.print(levelMenuPage);
    if(levelMenuPage == 0)
      levelMenuPage = levelMenuTotal;
      Serial.println(levelMenuPage);
}

if(levelMenuPage != levelMenuPageOld) //only update display when page change
{
    LevelMenuDisplay();
    levelMenuPageOld = levelMenuPage;
}
}
void MainMenuDisplay()
{
lcd.clear();
lcd.setCursor(0,0);
switch (mainMenuPage)
{
    case 1:
      lcd.print("1. Menu A");
      break;
    case 2:
      lcd.print("2. Menu B");
      break;
    case 3:
      lcd.print("3. Menu C");
      break;
    case 4:
      lcd.print("4. Menu D");
      break;
}
}
void LevelMenuDisplay()
{
lcd.clear();
lcd.setCursor(0,0);
switch (levelMenuPage)
{
    case 1:
      lcd.print("1. Menu A2");
      break;
    case 2:
      lcd.print("2. Menu B2");
      break;
    case 3:
      lcd.print("3. Menu C2");
      break;
    case 4:
      lcd.print("4. Menu D2");
      break;
}
}
void MenuA()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu A");
 menu2 = true;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu A here
 selection1=1;
 Serial.print("Selection1=");
 Serial.println(selection1);
}
}
void MenuA2()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu A2");
menu2 = false;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu A here
 selection2=1;
 Serial.print("Selection2=");
 Serial.println(selection2);
}
}
void MenuB()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu B");
menu2 = true;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu B here

 selection1=2;
 Serial.print("Selection1=");
 Serial.println(selection1);
}
}
void MenuB2()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu B2");
menu2 = false;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu B here
 selection2=2;
 Serial.print("Selection2=");
 Serial.println(selection2);
}
}
void MenuC()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu C");
menu2 = true;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu C here
 selection1=3;
 Serial.print("Selection1=");
 Serial.println(selection1);
}
}
void MenuC2()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu C2");
menu2 = false;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu C here
 selection2=3;
 Serial.print("Selection2=");
 Serial.println(selection2);
}
}
void MenuD()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu D");
menu2 = true;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu D here
 selection1=4;
 Serial.print("Selection1=");
 Serial.println(selection1);
}
}
void MenuD2()
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Inside Menu D2");
menu2 = false;
while(ReadKeypad()!= 'N')
{
    //Insert Task for Menu D here
 selection2=4;
 Serial.print("Selection2=");
 Serial.println(selection2);
}
}

char ReadKeypad()
{
/* Keypad button analog Value
no button pressed 1023
nul     <450
select  <400
left    <350
down    <290
up      <190
right   <50
*/
keypad_value = analogRead(keypad_pin);

if(keypad_value < 50)
return 'R';
else if(keypad_value < 190)
return 'U';
else if(keypad_value < 290)
return 'D';
else if(keypad_value < 350)
return 'L';
else if(keypad_value < 400)
return 'S';
else if(keypad_value < 450)
return 'N';

}

void WaitBtnRelease()
{
  while( analogRead(keypad_pin) < 600){}
}

```

# Answer
> 3 votes
Ok...nobody bought into this and I understand why...menus have been done to death, but not being one to quite I have answered my own question. Here is a simple, fool proof button menu, that i think has NO limit in depth. I have just tested this before posting, so if you don't get it to work, check your wiring. instructions at the bottom of the sketch.

```
    /* Rebuilt by Doug 07/02/2017 Australia.
 * This is a bare bones menu using buttons to navigate and select, there are no special libraries,
 * I am using an I2C LCD2004, but any display will work with minor mods. This has been translated from,
 * I believe Slovakian, that was fun, stripped down and modified for button control, I have found that
 * buttons are less picky than rotary encoders, even the good ones, just my experience.
 * I believe that I have removed all unnecessary script, but I may have missed some.
 * look at the last 2 --page()-- sections for instruction on extending down even further, I don't think
 * that there is a limit to how many levels you can have, how many do you really need.
 * The original sketch is from: Stanislav Petrek of Slovakia, you can find sketch on YouTube comments.
 * https://www.youtube.com/watch?v=gIP29m12wjQ&t=41s
 * Have fun with the translation  ;-}
 * The last thing I did before posting was to relaod and test this sketch, so it works.
 */
#include <LiquidCrystal_I2C.h> //from newliquidcrystal library
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

// menu system
int poz = 0; //  cursor position on actual page
int poz_max = 1;
int poz_min = 0;

int pozOld = 0;
int pozNew = 0;

int page = 0; //  actual page
int page_max = 1;
int page_min = 0;

int press = 0;
int press_max = 1;

int keypad_pin = A0;                      //analoge A0 to sense button values.
int keypad_value = 0;
int keypad_value_old = 0;

//bool menu2 = false;
char btn_push;
//****************************************************************setup*****************************************
void setup() {
Serial.begin(9600);
lcd.begin(20, 4);
lcd.clear();
lcd.home();
}
//************************************************************loop************************************************
void loop() {
MainmenuBtn();
if (btn_push == 'S') //enter selected menu
{
press++;
delay(250);
if (press > press_max) {
  press = 0;
}
}
// page select
switch (page) {

case 0:
  page0();
  break;
case 1:
  page1();
  break;
case 2:
  page2();
  break;
case 3:
  page3();
  break;
case 4:
  page4();
  break;
case 5:
  page5();
  break;
}
}
//****************************************************up/down************************************************
void MainmenuBtn()
{
btn_push = ReadKeypad();
WaitBtnRelease();
if (btn_push == 'U')
{
poz++;
if (poz > poz_max) {
  poz = poz_max;
}
}
else if (btn_push == 'D')
{
poz--;
if (poz < poz_min) {
  poz = poz_min;
}
}
pozNew = poz;
if (pozNew != pozOld) { //only update display when page change
pozOld = pozNew;
}
}
//*************************************************************read buttons***********************************
char ReadKeypad()
{
/* Keypad button analog Value
no button pressed 1023
*********************adjust these values to suit your keypad***********************
nul     >400
select  <400
left    <350
down    <290
up      <190
right   <50
*/
keypad_value = analogRead(keypad_pin);
if (keypad_value < 50)
return 'R';
else if (keypad_value < 190)
return 'D';
else if (keypad_value < 290)
return 'U';
else if (keypad_value < 350)
return 'L';
else if (keypad_value < 400)
return 'S';
else if (keypad_value > 400)
return 'N';
}
//********************************************************button release*************************************
void WaitBtnRelease()
{
while ( analogRead(keypad_pin) < 600) {}
}
//*******************************************************Front Page 0*******************************************
void page0() {
poz_min = 0;
poz_max = 3;
press_max = 1;

lcd.setCursor(0, 0);
lcd.print("Pg1 Pg2 Pg3 Pg4     ");
lcd.setCursor(0, 2);
lcd.print("                    ");
lcd.setCursor(0, 3);
lcd.print("                    ");

switch (poz)
{
case 0:
  lcd.setCursor(0, 1);
  lcd.print("---                 ");
  if (press == 1) {
    press = 0;
    poz = 0;
    page = 1;
  }
  break;
case 1:
  lcd.setCursor(0, 1);
  lcd.print("    ---             ");
  if (press == 1) {
    press = 0;
    poz = 0;
    page = 2;
  }
  break;
case 2:
  lcd.setCursor(0, 1);
  lcd.print("        ---         ");
  if (press == 1) {
    press = 0;
    poz = 0;
    page = 3;
  }
  break;
case 3:
  lcd.setCursor(0, 1);
  lcd.print("            ---     ");
  if (press == 1) {
    press = 0;
    poz = 0;
    page = 4;
  }
  break;
}
}
//*************************************************Pages 1*****************************************
void page1() {
poz_min = 0;
poz_max = 2;
press_max = 1;

lcd.setCursor(0, 0);
lcd.print("Page1               ");
lcd.setCursor(0, 1);
switch (poz) {

case 0:
  lcd.print("Page1 Case0         ");
  if (press == 1) {
    press = 0;
  }
  break;
case 1:
  lcd.print("Page1 Case1         ");
  if (press == 1) {
    press = 0;
  }
  break;

case 2:
  lcd.print("Page1 Case2    exit ");
  if (press == 1) {
    press = 0;
    page = 0;
    poz = 0;
  }
  break;
}
}
//*************************************************Pages 2*****************************************
void page2() {
poz_min = 0;
poz_max = 2;
press_max = 1;

lcd.setCursor(0, 0);
lcd.print("Page2               ");
lcd.setCursor(0, 1);
switch (poz) {

case 0:
  lcd.print("Page2 Case0         ");
  if (press == 1) {
    press = 0;
  }
  break;
case 1:
  lcd.print("Page2 Case1         ");
  if (press == 1) {
    press = 0;
  }
  break;

case 2:
  lcd.print("Page2 Case2  exit   ");
  if (press == 1) {
    press = 0;
    page = 0;
    poz = 1;
  }
  break;
}
}
//*************************************************Pages 3*****************************************
void page3() {
poz_min = 0;
poz_max = 2;
press_max = 1;
lcd.setCursor(0, 0);
lcd.print("Page3               ");

switch (poz)
{
case 0:
  lcd.setCursor(0, 1);
  lcd.print("Page3 Case0         ");
  if (press == 1) {
    lcd.setCursor(0, 1);
    lcd.print("                    ");
    //navi();
  }
  break;

case 1:
  lcd.setCursor(0, 1);
  lcd.print("Page3 Case1         ");
  if (press == 1) {
    press = 0;
  }
  break;

case 2:
  lcd.setCursor(0, 1);
  lcd.print("Page3 Case2  exit   ");
  if (press == 1) {
    press = 0;
    page = 0;
    poz = 2;
  }
  break;
}
}
//*************************************************Pages 4*****************************************
void page4() {
poz_min = 0;
poz_max = 1;
press_max = 1;

lcd.setCursor(0, 0);
lcd.print("Page4               ");
lcd.setCursor(0, 1);
switch (poz) {

case 0:
  lcd.print("Page4 Case0  branch ");
  if (press == 1) {
    press = 0;
    page = 5;                                   //branches to page5() menu
    poz = 0;                                    //at position 0 on button 'S' press
    break;

  case 1:
    lcd.setCursor(0, 1);
    lcd.print("Page4 Case1  exit   ");
    if (press == 1) {
      press = 0;
      page = 0;
      poz = 3;
    }
    break;
  }
  }
}
//*************************************************Pages 5*****************************************
void page5() {
poz_min = 0;                      //see void MainmenuBtn()
poz_max = 1;                      //see void MainmenuBtn()
press_max = 1;                    //used when you have multiple selection within a section-increase number
                                  //see  original script for example
lcd.setCursor(0, 0);
lcd.print("Page5               ");
lcd.setCursor(0, 1);
switch (poz) {

case 0:
  lcd.print("Page5 Case0         ");
  break;

case 1:
  lcd.setCursor(0, 1);
  lcd.print("Page5 Case1  exit   ");
  if (press == 1) {                 //variable set to '1' when the 'S' key is pressed
    press = 0;
    page = 4;                         //this is the page() that you return to after the 'S' button is pressed
    poz = 1;                          //this is the 'case' number that you will return to for that page
  }
  break;
}
}

```

I have only inserted print statements where operational code can be placed, to keep it universally open. To reduce the size of the Global variables use the \>\>lcd.print(F("TEXT"));\<\< method, it works really well. Also works on Serial.print....Something for you to fiddle with.

---
Tags: arduino-uno
---


title: Inputting list of data

text:
# Question
Title: Inputting list of data
Sorry if this question has been asked but I can't seem to find an answer because I don't really know if I'm phrasing the question correctly.

I'm trying to control a grid of LED to light up in a specific sequence that is based on a long list of data (and loops over time). Is there any way to bring in the data automatically? (vs individually coding the digitalWrites and delays) I think I found a reference project a few days ago but I lost it.

Thanks!

# Answer
Your question is vague so I have made some assumptions, I hope they are right.

The first is I have assumed you are relatively in experienced at programming, I hope that's right otherwise the rest of this may seem patronising.

You have a number of LEDs arranged in a grid (lets say 3x3 to make life easy). You are asking is there an alternative to doing this:

```
// Step 1
digitalWrite (LED1, HIGH);
digitalWrite (LED4, HIGH);
digitalWrite (LED8, HIGH);
delay (100);
digitalWrite (LED1, LOW);
digitalWrite (LED4, LOW);
digitalWrite (LED8, LOW);
// Step 2
// And so on...

```

Yes there are, and there are many, I think this is probably going to be the easiest to start with.

**Coding the data in a 2D array.**

An array is a fixed length list of values of the same type. One obvious use for an array is to hold the pin numbers for you LEDS, rather than having LED0 through to LED8.

```
#define LED0 2
#define LED1 3
// and so on

```

Alternative array version

```
//  Define the number of elements in the array
#define MaxLEDs 9
// Define the array
const int LEDPins[MaxLEDs] = {2, 3, 4, 5, 6, 7, 8, 9, 10};

```

I have declared the array as `const` because the values in it aren't going to change. The array is going to hold integers (because that's what `digitalWrite()` takes as a pin number) and there are 9 of them. Rather than use the literal 9 I have defined a constant because I know that value is going to be used elsewhere in the code and this means it is easier to change the number of LEDs.

So how does this help you? Well you can define an array of 'steps' and each step has a list of which LEDs are switched on. As your code loops through the steps it turns the specified LEDs, waits and then turns them off. The simplest way to encode the data would be for each 'step' element to be an array of Boolean values (each true value indicates a light that should be on during this step). I have chosen Booleans because it will use the least amount of space, which is always an issue on an Arduino. Depending on the number of steps and LEDs you may need to look at alternative storage methods, like just the LEDs that are on, but it will do for now.

```
const bool theSteps[MaxSteps][MaxLEDs] =
{
    {false, false, false, false, false, false, false, false, false}
  , {false, true , false, false, true , false, true , false, false}
  , {false, false, true , true , false, false, false, true , false}
  , {true , false, false, false, false, true , true , false, false}
};

```

You still have to code the data within the program, but its much smaller

```
//  Define the number of elements in the array
#define MaxLEDs 9
// Define the array
const int LEDPins[MaxLEDs] = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };

const bool theSteps[MaxSteps][MaxLEDs] =
{
    { false, false, false, false, false, false, false, false, false }
    ,{ false, true , false, false, true , false, true , false, false }
    ,{ false, false, true , true , false, false, false, true , false }
    ,{ true , false, false, false, false, true , true , false, false }
};

#define StepDelay 100

void setup()
{
}

void loop()
{
    for (int onOff = 0; onOff < 2; ++onOff) // Turns the LED on and off
    {
        for (int step = 0; step < MaxSteps; ++step)
        {
            for (int led = 0; led < MaxLEDs; ++led)
            {
                if (theSteps[step][led])  // If the LED should be on
                {
                    digitalWrite(LEDPins[led], (onOff < 1) ? HIGH : LOW);
                }
            }
        }
        if (onOff < 1)
            {
                  delay(StepDelay);
            }
    }
}

```

I'm afraid I haven't tested any of this code (it might not even compile) but the theory is right and it should give you a shove in the right direction.
> 0 votes

---
Tags: led
---


title: "undefined reference to" - C++

text:
# Question
Title: "undefined reference to" - C++
Hi fellow programmers,

I started to program Arduino a little deeply and popped out the following error when I was writing a class to read the pulses of a Hall effect flow rate sensor:

```
SensorDeVazao.cpp.o: In function `SensorDeVazao::Resetar()':
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp.o:SensorDeVazao.cpp:141: more undefined references to `SensorDeVazao::SensorHandle' follow
collect2: error: ld returned 1 exit status

```

The code is divided in two files, a \*.h and a \*.cpp, so it is uncircumstantial to paste the code here (pos-edited: the codes are the following: \*.h: codepad.org/UyLfik6W \*.cpp: codepad.org/5KJmraCC). But I will explain the context:

SensorHandle is a static object of the own class SensorDeVazao (Brazilian Portuguese to FlowRateSensor) and it is used in an glue function used by the attachinterrupt to read the pulses I've mentioned previously. The function claimed in the error log ("Resetar", Brazilian Portuguese for reset) don't use the variable "SensorHandle". Last but not least, the message shown in the second line appears subsequently multiple times in the error window.

I hope, I provided all the informations to help you solve this issue. Thank you for the attention.

PS.: Sorry if this is a duplicated post. If yes, please forward it in the comments below.

# Answer
> 6 votes
Without seeing the actual code (BTW why can't you add it? Is it top-secret?) I can't be sure, but usually this happens when you don't define a variable but just declare it. Example:

```
// File myclass.h
class A {
public:
  static int i;
};

// File myclass.cpp
void myfunc() {
    A::i = 0;
}

```

If you actually declare it the error should go away:

```
// File myclass.h
class A {
public:
  static int i;
};

// File myclass.cpp
int A::i = 0;

void myfunc() {
    A::i = 0;
}

```

Remember that the class definition (so the class {}) can go in a header file, but the variables definition MUST go in a source file (so the .cpp one) AND if you have multiple source files you have to put this in ONLY ONE file (usually the file where you implement the functions).

This only applies to static variables.

EDIT: Further explanation.

You should understand the difference between declaration and definition of a variable.

Definition is just stating "there exist a variable called i, which is an integer"; for instance the statement `extern int i;` defines a variable. All the variables listed in a class are only defined there.

Declaring a variable is one more step: it tells the compiler to reserve the space in memory (this operation is called allocation) and so to physically create the variable. Always keep this in mind.

Little example. Let's say you have a library, using files lib.h and lib.cpp, and files A.cpp and B.cpp both referencing the library (they have a statement saying `#include "lib.h"`). When writing a library without a class you usually write global variables in this way:

```
// header file: lib.h
extern int i;

// source file: lib.cpp
int i;

```

(note: it is better to always define an initialization value, so for instance `int i = 0;`). The two files (A and B) both have the line `extern int i;` in they, which means "there exist a variable called i, and someone else is allocating the space for it. Result: the compiler will link all those definitions to the same memory location, thus actually sharing the variable. If you wrote `int i;` in the header file each cpp file would have its i variable allocated, so each would point to a different block of memory.

Now, for the classes. If you write

```
class A {
public:
    int a;
    static int b;
}

```

you have two variables. A gets instantiated when you instantiate an object, so does not have any problems. But b... well, b is just defined, never declared. So there is no place in memory where b actually resides (the reference is undefined).

To deal with this, you have to manually declare it in a cpp file, with the syntax `int A::b;`. This way you are reserving some space for that variable

# Answer
> 1 votes
An explanation of what is happening:

When you define a class you indicate what variables will be in it.

When you then instantiate the class (`MyClass c;`) the variables within the newly instantiated object get allocated.

Static variables never get instantiated. After all - which instance of the class should instantiate them when you create one? And if you never create one? So it's simple: static variables *never* get created by the class definition or anything else. It is up to *you* to provide the storage space for that variable, which means statically allocating it in your C++ code as has been demonstrated.

---
Tags: c++, class
---


# Question
Title: Splitting a float into bytes for storage in FRAM (like EEPROM)
I'm trying to write floats to I2C FRAM (like I2C EEPROM) but without result. I tried with this function but I lose all number after the decimal. Thank's for replying.

This for writing:

```
float floatNumber = 123.123;
byte floatPt1 = 0;
byte floatPt2 = 0;
byte floatPt3 = 0;
byte floatPt4 = 0;
byte b1 = (floatNumber);
byte b2 = (floatNumber >> 8);
byte b3 = (floatNumber >> 16);
byte b4 = (floatNumber >> 24);

```

This is for reading:

```
long floatRicomposto = 0;
floatPt1 = fram.read8(3);
floatPt2 = fram.read8(4);
floatPt3 = fram.read8(5);
floatPt4 = fram.read8(6);
//float RECOMPOSITION
floatRicomposto = (uint32_t) floatPt1 <<  0
  | (uint32_t) floatPt2 <<  8
  | (uint32_t) floatPt3 << 16
  | (uint32_t) floatPt4 << 24;

```

# Answer
> 1 votes
I solved it with the use of UNION:

```
//---------------------------------------------------------
union Scomp_float {
  // si utilizza union x float
  float temp;
  char byte_s[4];
} S_float;

//---------------------------------------------------------
//-------------------------FLOAT--------------------------------
float mioFlo = 123456.29;
byte f0 = 0;  // contengono i byte del float
byte f1 = 0;
byte f2 = 0;
byte f3 = 0;
S_float.temp = mioFlo;
f0 = S_float.byte_s[0];
f1 = S_float.byte_s[1];
f2 = S_float.byte_s[2];
f3 = S_float.byte_s[3];
Serial.println(f0);
Serial.println(f1);
Serial.println(f2);
Serial.println(f3);
fram.writeEnable(true);
fram.write8(7, f0);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(8, f1);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(9, f2);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(10, f3);
fram.writeEnable(false);
S_float.byte_s[0] = fram.read8(7); // si ricompone il float
S_float.byte_s[1] = fram.read8(8);
S_float.byte_s[2] = fram.read8(9);
S_float.byte_s[3] = fram.read8(10);
float masterFloat = S_float.temp;
Serial.println(masterFloat);
//-------------------------FLOAT--------------------------------

```

# Answer
> -1 votes
A pointer can be used to easily decompose and reconstitute any multi byte type, like a float.

---
Tags: eeprom, float
---


# Question
Title: Arduino Ground Current and DC power jack
I have a project where I'm providing power via the DC jack to my Arduino then accessing the DC power via the VIN pin. According to this http://forum.arduino.cc/index.php?topic=453955.0 I am ok to draw up to 1A from the VIN pin. I have measured 400ma out of VIN, so ok on that front.

But according to this http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations I can draw max 400ma, So I'm a bit confused, which is the correct amount of power VIN can supply if the Arduino is being powered via the DC jack?

If I take the first thread as correct and assume it's ok to draw up to 1A from the VIN pin (from the DC power jack), is it ok to ground that current on the Arduino GND pin ? if VIN can supply up to 1A then I assume that it's ok to ground up to 1A, is this correct?

All help appreciated

# Answer
Going by the schematic here there is an M7 diode (D1) between the power jack and the VIN pin on a Uno (you don't actually say which board you're using, I'm guessing based on the first link).
The datasheet here indicates that the maximum forward current for a M7 diode is 1.0 A. However different manufacturers datasheets seem to disagree as to whether that is a sustained DC current or only rectified current (so 50% load implying ~500mA constant load).
Either way you are looking at a potential 1.1 V drop across the diode so your VIN will be below the supply voltage by up to that much.

If you want to live dangerously you can always replace D1 with a piece of wire (or put the wire across it). You will lose reverse voltage protection on the DC jack, using a supply with it backwards will blow things up, but your current will then be limited by how much current the connector pins and PCB trace can cope with before they melt.
> 2 votes

---
Tags: arduino-uno, power, electronics
---


title: Anything wrong with this code?

text:
# Question
Title: Anything wrong with this code?
Sorry for any grammar mistakes. It's my second language.

I had a little test with my Arduino Uno R3 I connected 2 buttons to power , GND using 10k resistors and pins 2 and 4. I connected piezo to power and ground.

When you pressed a button1 then you should hear 'c' tone, but when I pressed the second button nothing happend and I don't understand why?

Here is my code below:

```
const int buttonPin2 = 4;
const int buttonPin1 = 2;
const int piezopin =  6;

int buttonState1 = 0;
int buttonState2 = 0;

void setup() {

  pinMode(piezopin, OUTPUT);
  pinMode(buttonPin2,INPUT);
  pinMode(buttonPin1, INPUT);
}

void loop() {

  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);

  if (buttonState1 == HIGH) {
    tone(6,261.63,500);

  } else {

  }
  if (buttonState2 == HIGH) {
    tone(6,392.00,500);
  } else {

  }

```

# Answer
> 1 votes
Try calling `noTone()` after the tone is played. This is a kind of "reset" for the pin.

Also, you forgot a `}` at the end of your code.

If these didn't solve your code, then it most probably is an electric problem.

---
Tags: button
---


title: How do I find my 1N 4007 diodes?

text:
# Question
Title: How do I find my 1N 4007 diodes?
I am a beginner to Arduino, and a relative beginner to electronics in general. I have the official Arduino Starter Kit. I've looked through my bag of components looking for a black diode but was unable to find it among all of the LEDS & the other black components.

# Answer
While the ArduinoStarterKit page at arduino.cc lists “5 Diodes \[1N4007\]” as part of it, and has a picture where 5 diodes apparently appear slightly left of center in the top row, several other pictures that come up in a google images search for *official Arduino Starter Kit* apparently don't show the diodes. Eg, as at arduino starter kit. But 4 Best Starter Kits for Arduino Beginners does show them.

Note, unless you are working with medium to high AC voltages (eg above 50 V) you can substitute 1N4001 - 1N4004 which have lower PIV ratings but also slightly lower forward voltage drop. For many beginning projects, 1N4148 signal diodes will be adequate and perhaps less expensive.
> 1 votes

# Answer
1N4007 are usually black with a white stipe indicating the cathode. Use a magnifying glass and you should be able to see the marking.
> 1 votes

# Answer
They are stuck next to a string of resistors.
> 1 votes

# Answer
This is image of 1N4007 diodes. I think now you can find them easily.
> 1 votes

---
Tags: components
---