title: Multiple SPI device

text:
# Question
Title: Multiple SPI device
I want to connect Ethernet board `(W5100 HR911105A)` to `Arduino Leonardo` with SPI and I also want to connect SD reader. When I test these boards separately everything working. But when I connect them on the same board the program fails at `Ethernet.begin();`

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

#define SS_SD_CARD  4
#define SS_ETHERNET 10

const char CONFIG_FILE[] = "system.cfg";

byte C_MAC[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress S_IP(192,168,0,19);
IPAddress C_IP(192, 168, 0, 177);
const uint16_t  S_PORT = 8090;

EthernetClient client;

void setup() {
  Serial.begin(9600);
    while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
    pinMode(SS_SD_CARD, OUTPUT);
    pinMode(SS_ETHERNET, OUTPUT);

    digitalWrite(SS_SD_CARD, HIGH);
    digitalWrite(SS_ETHERNET, HIGH);

    digitalWrite(SS_SD_CARD, LOW);
    SD.begin(SS_SD_CARD);
    digitalWrite(SS_SD_CARD, HIGH);

    Serial.println("Setup ethernet");
    digitalWrite(SS_ETHERNET, LOW);
    if (Ethernet.begin(C_MAC) == 0) {
      Serial.println("Failed to configure Ethernet using DHCP");
      Ethernet.begin(C_MAC, C_IP);
    }
    delay(100);
    Serial.println("connectin...");
    bool result = client.connect(S_IP, S_PORT);
    Serial.println("connected");
    digitalWrite(SS_ETHERNET, HIGH);
}

void loop() {
  Serial.println("loop...");
  delay(1000);
}

```

I tried on Leonardo and Mega 2560.

# Answer
Some card reaaders (as well as display boards with built-in sd socket) use 10-kOhm resistors in series to the CS, DIN and CLK lines, to perform a cheap 5V to 3.3V level translation. This is really not the best solution, especially in terms of speed (we verified that typically this limits the maximum SPI speed to about 1 MHz).

Other cards readers (such as this one http://modtronix.com/mod-sdcard-l5.html), just use 10 k-Ohm resistors as pull-up to 3.3V. Therefore you're connecting all the SD card lines to the Leonardo board, which is 5V level. This will cause serious issues to the SD card or to the leonardo board. If your card reader falls in this second case, I suggest you to insert a resistor divider (1k + 1.5k) in series to each input lines of the SD card: DIN, CLK, CS. In the following schematics I just show for the CLK line, of course you have to repeat this three times. A much better idea would be a level translator IC.

simulate this circuit – Schematic created using CircuitLab
> 3 votes

# Answer
If you have a similar SD card reader like below (or same but with micro SD card), than I had exactly the same problem.

It works as single device on SPI, but not together with another SPI device.

You can either use a SD recorder proto board, or use a microcontroller that has multiple SPIs.

An example of the SD recorder I used and works with another SPI device on one SPI port.

Cons: bigger, more expensive Pro: has a RTC and proto space.
> 2 votes

# Answer
i suspect the reason is due to how the inputs/outputs are designed, the W5100 appears to be a 3v3 board with 5V compatible inputs, as does the link you posted to the SD reader, however depending on how these inputs/outputs are designed can mean they won't "play nice" with other boards on the same bus even though SPI is designed to do that.

depending on where the problem lies there are a few potential solutions, if (as i suspect) the problem is the output from the devices back to the arduino (ie you can write to them but not read from them) which you could confirm by connecting all lines in parallel, but only connecting one of the serial lines back to the arduino and check that it works, then swap the serial to the other device and check that. assuming that both devices work in this configuration you only need to fix the return signal. the simplest way of doing this would be to use two tri state buffers.

so the return signal is only connected to the arduino when that devices select line is active. and high impedance (disconnected) otherwise, programatically disconnecting one device from the bus.
> 1 votes

---
Tags: c++, ethernet, spi, arduino-leonardo, sd-card
---


title: lcd not display

text:
# Question
Title: lcd not display
is it my coding wrong or my board have problem because my lcd does not display anything. here my coding

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

// set the LCD address to 0x27 for a 20 chars 4 line display
// Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x27, 6, 2, 3, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C add 27 / 3F

void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600); //
  lcd.begin(16,2);         // initialize the lcd for 16 chars 2 lines, turn on backlight
  lcd.backlight();

}

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{

  lcd.setCursor(0, 0);
  lcd.print("HELLO");

  delay(200);

  lcd.setCursor(0, 1);
  lcd.print ("HI");

  delay(2000);

  lcd.clear();

  delay(2000);

  lcd.setCursor(0, 0);
  lcd.print("NICE");

  delay(200);

  lcd.setCursor(0, 1);
  lcd.print ("GOOD ");

  delay(2000);

  lcd.clear();

  delay(2000);
}

```

this is how i wirring it. what should i do?

# Answer
the black bars indicate that the lcd isn't correctly initialized.

check the hardware / connection and make sure that your software initializes it correctly.
> 1 votes

# Answer
Well, I have the hardware, so I tested OP's configuration. It didn't work for me either. Same OP's problem.

The cause is the I2C address we are using (0x27). That's not my LCD address, probably neither your address. It's 0x3F in my case.

I discovered it I2CScanner, a short sketch that lists all I2C devices connected at that moment. So, run it (with the LCD connected) and watch with Serial Monitor for the address of your LCD.

Then replace all references to 0x27 (like `lcd(0x27, 16, 2)`) with your real address. Just change one value for the other.

This is I2CScanner

```
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknown error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(5000);           // wait 5 seconds for next scan
}

```
> 1 votes

# Answer
The first thing you have to do is run the examples from the library. If that doesn't works, check your connections and components.

If example works, it have to be your sketch (programing problem).

Good practice: write short sketchs that test only one component in your project. Example: your project use a LCD, a temp sensor, and a button, you wrote three short tests. If something goes wrong with your project, you can use the test sketchs to identify where the problem is
> -1 votes

---
Tags: programming, i2c, lcd
---


# Question
Title: Sainsmart Omron 12V optocoupled 2 channel relay problem
I know that there are plenty of questions related to relays, but I have to ask. I am trying to sort out the issue and spend hours reading but cannot make progress.

I have SainSmart 2-Channel 12V Relay Module for Arduino and wired it according to picture.

Arduino UNO R3 board is powered from 12V plug external power supply. I take that 12V to power JD-VCC on relay (from VIN). Arduino 5V is used to power optocoupler circuitry.

I want to use to power 12/24/220V devices (on picture I wired 6V battery for troubleshooting).

So, when I set PIN7 to LOW i would expect that fan spins up. LED on relay goes RED, so I expect it is sign that relay is activated. However, fan does not power on. When I bring PIN7 to HIGH, I hear click; LED goes OFF. I assume it deactivated relay. All the time I have 6V on voltmeter.

What I am doing wrong? I really tried to find answer around, but either I do not see or it is not so obvious.

Thank you,

# Answer
Lets troubleshoot this circuit:

1. The circuit diagram you put in your question shows a wire creating a short across the relay coil. Check this, as this will definitely stop your fan from spinning. However, I assume this is an error in the diagram.
2. The picture on the website shows a jumper link between VCC and JD-VCC. Make sure this is removed.
3. Check that the fan works when you power it directly from the 6V battery. The fan may work only at a higher voltage or run off of AC voltage. Also, the battery could be flat - measure its voltage when it is under a small load.
4. Drive the input circuitry directly off of 5V. That is connect `VCC` to 5V and then directly connect `IN1` to GND. Open circuit the `IN1` input to turn it off. Check that this direct driving opens and closes the relay contacts.
5. Check the 12V supply. Does the voltage drop significantly when the relay pulls in or out? Does it have enough current? `"Each [relay] needs 15-20mA Driver Current"` Measure it using your DMM in ammeter mode.
6. Check your wiring is correct. It sounds simple, but you will be surprised by how many times the wiring is the cause of the problem.
7. Measure the resistance of the relay contacts in both the open and closed states. Arcing or poor manufacturing can be causes for the contacts to not function as intended.
> 1 votes

# Answer
~~Looking at what I assume is the same module on the Sainsmart website it looks like the relays are 5V. That means the 12V you have pumped into them has made the Magic Smoke™ escape.~~

~~Throw them away, buy some new ones, and next time don't put in more than twice the voltage it needs.~~
> 0 votes

# Answer
Remove the wire from the collector of your transistor and 12VDC, it should work fine. It is possible you blown the opto coupler and transistor.
> 0 votes

---
Tags: relay
---


# Question
Title: How to record steps a stepper motor takes and how to rotate it backward and forward with analog input?
I am trying to control a stepper motor's movements with a pressure sensor input (0 to 5 V digital). For example, if the input is 4 V then the stepper motor should move forward 4 steps. If the input is 3 V then it should come backward 1 step. Please suggest a command in Arduino to keep record of the previous sensor value and steps taken by stepper motor.

This is the code I have written for simple rotation of the motor:

```
const int stepPin = 8;
const int dirPin = 9;
int sensorValue=A0;
int i;

void setup() {
  Serial.begin(9600);
  pinMode(sensorValue, INPUT);
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
}

void loop() {
  sensorValue = analogRead(A0);
  float voltage = sensorValue * (5.0 / 1023.0);
  if(voltage==1) {
    digitalWrite(dirPin, HIGH);
    for(int x = 0; x < 200; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(5000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(5000);
    }
    delay(1000); // One second delay
  }
  digitalWrite(dirPin, LOW);
  for(int x = 0; x < 200; x++) {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
  }
  delay(1000);
  while(1);//only once
}

```

# Answer
I analyzed your code written in the comment and assuming that it works I prepared a modification that should prevent the motor from moving when the sensor is pressed the same way all the time. The noise values you have to adjust yourself. Make it as low as you can.

I cannot test this code, because I don't have your hardware. Treat it as pseudo code.

```
#include <Stepper.h>
// change this to the number of steps on your motor
#define STEPS 200
#define NOISE 0.1

Stepper stepper(STEPS, 8, 9);
int previous = 0;
void setup() {
  // set the speed of the motor to 30 RPMs
  stepper.setSpeed(100);
}

void loop() {
  // get the sensor value
  float val = analogRead(A0);

  float difference = previous - val;

  if(difference < -NOISE || difference > NOISE)
  {
    stepper.step(val - previous);
    previous = val;
  }
}

```
> 1 votes

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


# Question
Title: Arduino Mega and other modules power consumption
I have an Arduino Mega 2560 to which I have connected:

* Arduino GSM Shield 2
* Waveshare 10 DOF IMU sensor
* Waveshare NEO-7M-C (B) GPS module
* HC-05 ZS040 Bluetooth module

I am feeding my Arduino a 12V current via the VIN pin, yet both the GSM shield and the GPS module are misbehaving due to low power working conditions. All the modules work perfectly fine individually, or in any combination that does not have both the GSM and the GPS module, as they consume the most power.

My question is how high a voltage would be necessary in order for all of the modules to function correctly and how this voltage should be connected to the Arduino.

# Answer
> 3 votes
You can't fix it with more voltage. The board you are using (schematic here) uses a linear voltage regulator. All increasing the voltage does is make the regulator run hotter.

You could try running from around 7V, this will minimize the heat dissipation in the regulator and may allow you to pull more current through it but I suspect you've simply hit the design limits of the power supply circuits.

Instead of using the Arduino's built in power supply to convert from 12V to 5V you could try using an external 5V supply with a greater current capability connected directly to the Arduino 5V rail.

# Answer
> 0 votes
**You should not try to power your arduino with more than 12 V**. The barrel jack connector can take between 7 and 12 V and from there steps it down to the proper voltage for the Arduino (5V). Anything being powered by the arduino is limited to how much current it can output, so if you have too many modules, you may need to have a separate power supply for those. If you do this, there several things you need to consider:

1. **What voltage does each module need?** (This is probably 5V, but you should check the datasheets or any documentation you have)
2. **How much power does it consume?** You might find this in documentation, but you can also calculate it yourself: P = I\*V Once you know how much power each module/sensor consumes, you know how much your power supply needs to supply.

If you use a separate power supply for any of your modules/sensors, make sure the ground pin is also tied to Arduino's ground.

# Answer
> 0 votes
Power applied to the VIN pin is regulated down to 5V by the on-board regulator on the Mega. The minimum voltage is about 6.2V because of the regulator dropout (that is, the regulator needs at least 1.2V above it's 5V output in order to operate.) 9-12V is recommended.

Applying a higher and higher voltage will not provide any more power to the Mega and it's peripherals/shields. Instead, the excess power is dissipated in the regulator as heat.

If you experience low-power situations, the solution is to power the peripheral devices from a separate regulator than the one built-in to the Mega, which is really intended to power the Mega board/processor and maybe 1 shield.

You could obtain a high-current (3A or more) 5V supply, and connect the peripherals' power inputs to it, as well as power the Arduino in via the 5V pin (leaving VIN disconnected!). Be sure to tie the grounds of all peripherals and the arduino and power supply together.

Be sure also to pay attention to the voltages required by the peripheral modules, as it's common now to find modules that are rated for 3.3V and would be damaged by 5V. This is probably not the case for you, since your system is working sometimes.

# Answer
> 0 votes
The Arduino GSM shield 2 demands 700mA-1000mA current. It is recommended to power the board with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current when the modem is in heavy use.

The modem can pull up to 2A of current at peak usage, which can occur during data transmission.

The GPS module takes only 35mA, so the fault is in the GSM shield.

# Answer
> 0 votes
arduino nano(5v usb)(3.3v). arduino uno(12v dc jack)(5v).

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


title: Wifi with ESP8266 and Arduino sketches

text:
# Question
Title: Wifi with ESP8266 and Arduino sketches
I have a NodeMcu Lua ESP8266 ESP-12E which i want to use to control to a relais via Wifi network.

The first step was to write an Arduino Sketch which scans networks and connects to the network. However, even the standard example from the examples menu didn't work (c.f.,https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino) .

To rule out hardware problems I tried the LUA version from the list API doc (see below), which worked.

```
 -- print ap list
function listap(t)
      for k,v in pairs(t) do
        print(k.." : "..v)
      end
end

wifi.sta.getap(listap)

```

Using a firmware build from http://nodemcu.com/index\_en.html

I gave the INO version another try and it seemed to work as well. However, it turned out it only works if the previous firmware has been the firmware from http://nodemcu.com/index\_en.html

To I need to include a library or something ?

Thanks in advance, Cafebabe

# Answer
(By googling) I figured out the problem and a work-around. **But not an executable solution.** The problem seems to be that the RF module is not properly initialised when the device is powered on or awakes from reset.

Sadly there seems to be no manual mode to switch on the RF module.

However, I found a workaround. First I made the connection to enable deep sleep, for that, we need to tie the `RST` pin to `D0`/`GPIO 16` on the ESP8266.

Then I added the following code to setup

```
extern "C" {
  #include "user_interface.h"
}

void setup(){
  if (resetInfo->reason != REASON_DEEP_SLEEP_AWAKE) {

      ESP.deepSleep(10, WAKE_RF_DEFAULT)
  }

```

Basically whenever the system comes into setup from something else than deep sleep, the system goes to deep sleep and when powering back on the RF module is enabled.
> 1 votes

---
Tags: wifi, nodemcu
---


# Question
Title: I2C FRAM read/write is very slow. Taking over 500 microseconds per read, almost 500 per write
I've used the example code for the Adafruit I2C FRAM breakout board, but I've made it even simpler by just writing the same thing to each byte location and then reading them all off, doing nothing with the data.

I can tell it works because I can read off any byte and get the expected value, but the problem is that it works way too slowly. writing and reading 512 bytes takes almost a full half a second. This just won't work for my application, but I suspect there's something fundamentally wrong with what I'm doing.

I tried calling `Wire.setClock(400000);`, which supposedly is the maximum speed my Nano can drive an I2c slave at, but no matter what argument I input, the operation takes the same amount of time (498616 microseconds, within about +/- 20 microseconds).

I also tried calling `Wire.begin(); TWBR = 10;`, because I read that somewhere. But again, I get no difference. Here's my whole code- It's pretty simple

```
#include <Wire.h>
#include "Adafruit_FRAM_I2C.h"

/* Example code for the Adafruit I2C FRAM breakout */

/* Connect SCL    to analog 5
Connect SDA    to analog 4
Connect VDD    to 5.0V DC
Connect GROUND to common ground */

Adafruit_FRAM_I2C fram = Adafruit_FRAM_I2C();
uint16_t          framAddr = 0;

byte p = 55;   //any old value- just write the same thing into all locations

void setup(void) {
    Serial.begin(153600);
    //Wire.begin();
    //TWBR = 10;
    //Wire.setClock(400000);

    if (fram.begin()) {
        Serial.println("Found I2C FRAM");
    }
    else {
        Serial.println("I2C FRAM not identified ... check your connections?\r\n");
    }

}

void loop(void) {

    int i = 0;

    long a = micros();

    for (i ; i < 512; i++){  //write 512 bytes to the FRAM board
        fram.write8(i, p);

    }

    for (i = 0 ; i < 512; i++) {  //read 512 bytes from the FRAM board
        fram.read8(i);

    }

    long b = micros();

    Serial.println(b - a);
    Serial.println("");
}

```

# Answer
* You are running at 400000 bits per second, or 200000 per half second you say it takes.
* You have about 1000 transactions (actually 1024 but for simplicity I will call it 1000)
* 200000/1000 = 200 bits per transaction.
* Wire is blocking and not very efficient. So say it is actually only transmitting 25% of the time.

That's 50 bits per transaction. Now I don't know the protocol that chip uses, but if it's like the SPI chips it would need 5 bytes per transaction - 1 for the I2C address, 3 for the FRAM address, and 1 for the byte. With start, ack, etc call it 10 bits per byte.

That makes 50 bits per transaction.

So yes, half a second to write then read it all is perfectly possible.

The slowness stems from the fact that you are working a byte at a time instead of larger blocks of data in one transaction.

---

Now I am at my computer I can take a look at the datasheet and get some more accurate numbers.

A write of a single byte requires 4 bytes in a transaction. That's 4 bytes, 1 start, 4 ack and 1 stop bit. So (4x8)+1+4+1 = 38 bits.

A read of a single byte, with "repeated start", requires 5 bytes per transaction, with 2 start, 4 acks, 1 nack and 1 stop. That's (5\*8)+2+4+1+1 = 48 bits.

So for a read and write it's 38+48 = 86 bits.

Therefore you'd require 86\*512 I2C clock cycles to transfer all 512 bytes in both directions - that's 44032 clock cycles.

At 400,000 bits per second it is 44032/400000 = 0.11 seconds, or 110ms of the time spend transferring data, not counting the time it takes to actually process and prepare the data, fill registers, look for status flags, etc.

If it is taking half a second then at 400,000 bits per second you have 44032 / (400000/2) * 100 = 22% of the time it's actually transmitting or receiving data over I2C.

So not a bad guestimate of 25% transmission in my original surmising.
> 3 votes

---
Tags: arduino-nano, i2c
---


# Question
Title: Issue with If statement and boolean logic
I'm trying to control motor based on rain sensor and my own build anemometer. It should only controlling motor clockwise/CW for open the roof if there are no rain (indicated by value above 900) AND the wind speed below 4 km/h. If there are raining (analog value below 650) and/or wind speed above 4 km/h the motor should spin counterclockwise/CCW. I succeed to rotate the motor CCW if rain and/or high wind speed happen, but when the motor hit the limit switch for stopping the motor, motor only stop for maybe 2 seconds and then back rotating CW (open the roof), even the wind still above 4 km/h. The roof should be open only when there is no rain (analog value above 900) and the wind speed below 2 km/h. Here is my If Statement logic program:

```
if ((analogRead(rain) < 650 || (Wind > 4)){
  motor_closed();
}

else if (analogRead(rain) < 650 && (Wind > 4)){
  motor_closed();
}

else if (analogRead(rain) < 650 && (Wind < 2)){
  motor_closed();
}

else if (analogRead(rain) > 900 && Wind > 4){
  motor_closed();
}

else if (analogRead(rain) > 900 && Wind < 2){
  motor_open();
}

```

Did I make mistake when using `&&` boolean operator? Or its something else?

# Answer
> 1 votes
I ran a test with your original code, with rain and wind varying over all the range:

```
(rain, wind) -> action
------------------------
(600, 1) -> motor_closed
(600, 2) -> motor_closed
(600, 3) -> motor_closed
(600, 4) -> motor_closed
(600, 5) -> motor_closed
(650, 1) ->
(650, 2) ->
(650, 3) ->
(650, 4) ->
(650, 5) -> motor_closed
(700, 1) ->
(700, 2) ->
(700, 3) ->
(700, 4) ->
(700, 5) -> motor_closed
(750, 1) ->
(750, 2) ->
(750, 3) ->
(750, 4) ->
(750, 5) -> motor_closed
(800, 1) ->
(800, 2) ->
(800, 3) ->
(800, 4) ->
(800, 5) -> motor_closed
(850, 1) ->
(850, 2) ->
(850, 3) ->
(850, 4) ->
(850, 5) -> motor_closed
(900, 1) ->
(900, 2) ->
(900, 3) ->
(900, 4) ->
(900, 5) -> motor_closed
(950, 1) -> motor_open
(950, 2) ->
(950, 3) ->
(950, 4) ->
(950, 5) -> motor_closed

```

So your logical expression reduces to this:

```
if (analogRead(rain) < 650 || Wind > 4) {motor_close();}
else if (analogRead(rain) > 900 and Wind == 1) {motor_open();}

```

It's that what you want?

What's that "limiting switch"? May be it's a physical problem (like installing sensor **under** de roof)

# Answer
> 0 votes
Personally I like to force precedence in my `if` statements to ensure that things always work precisely as I intend. Group your logical predicates with brackets:

```
if ((analogRead(rain) < 650) || (Wind > 4)) {
    motor_close();
} else if ((analogRead(rain) > 900) and (Wind < 2)) {
    motor_open();
}

```

Using intermediate variables would make it more readable:

```
bool tooWindy = (Wind > 4);
bool notWindy = (Wind < 2);
bool tooRainy = (analogRead(rain) < 650);
bool notRainy = (analogRead(rain) > 900);

if (tooWindy || tooRainy) {
    motor_close();
} else if (notWindy && notRainy) {
    motor_open();
}

```

Giving names to the logical conditions makes it far more obvious what is going on:

* If it is too window **or** it is too rainy then close the roof.
* Otherwise, if it's not too windy **and** it's not too rainy then you can open the roof.

And of course you have the time when it's between too rainy and not too rainy, or between too windy and not too windy, in which case nothing should happen. This is called *hysteresis* and is good to have since it stops the roof from opening and then immediately wanting to close.

You could also improve the logic of the system even more and implement a small Finite State Machine:

```
enum {
    CLOSED, OPENING, OPEN, CLOSING
};

int state = CLOSED;

switch (state) {
    case CLOSED:
        if ((analogRead(rain) > 900) && (Wind < 2)) {
            motor_open();
            state = OPENING;
        }
        break;

    case OPENING:
        if (digitalRead(limit_open) == HIGH) {
            motor_stop();
            state = OPEN;
        }
        break;

    case OPEN:
        if ((analogRead(rain) < 650) || (Wind > 4)) {
            motor_closed();
            state = CLOSING;
        }
        break;

    case CLOSING:
        if (digitalRead(limit_close) == HIGH) {
            motor_stop();
            state = CLOSED;
        }
        break;
}

```

In that you only attempt to open the roof (and even check to see if you should open the roof) if the roof is actually closed. Similarly for checking for and closing the roof - it only happens when the roof is actually open. Nothing happens in the way of checks while the roof is in the process of opening or closing, so it has to complete its open or close operation first before any more decisions are made as to whether the roof should be open or closed.

# Answer
> 0 votes
> Did I make mistake when using && boolean operator? Or its something else?

use brackets liberally.

rather than

```
if (x > 65 && y < 10)

```

instead,

```
if ((x > 65) && (y < 10))

```

---
Tags: programming, arduino-nano, motor
---


# Question
Title: Establishing an MQTT connection using Arduino Mega and ESP8266
As the title says, I want to send MQTT messages to a server using ESP8266 with an Arduino Mega as controller, but so far, every library that I have found is based on Ethernet. I don't want Ethernet, I want WiFi, so those solutions don't work for me. I have tried using PubSubClient library, but the problem is that to create an instance (`PubSubClient client(?????)`), I have to set a client. What should I put in there? Is there another library I must use?

# Answer
You require an ESP8266 library that implements the Arduino standard Client & Server classes (or at minimum the Client class).

Personally I'd program the ESP8266 directly to make it perform the MQTT request itself (using the libraries bundled with the ESP8266 core). Have the Arduino tell it what to send through some protocol you make yourself over UART.
> 2 votes

# Answer
you have the AT firmware in the esp8266? use WiFiEsp library

or if you can change the esp8266 firmware, you could try JeeLabs esp-link
> 1 votes

---
Tags: esp8266
---


# Question
Title: Connect arduino with C# Desktop application wireless using esp8266
I am using wifi module esp8266 , what is easiest way to communicate arduino with desktop application and make a wireless communication between them. Please refer any useful resources

# Answer
Either use TCP or UDP to communicate. With TCP one end will be the server and will open a socket (your choice) and the other end will connect to it (much like communicating with a web server). With UDP both ends will open a socket and send discrete packets backwards and forwards.

How you would do either of those in C# is outside the scope of this website.

The ESP8266 has AT commands that perform the task for you - chiefly `AT+CIPSTART`.

The simplest to understand is probably TCP communication where you can just follow any of the myriad of website based examples. However instead of communicating with a website using HTTP you will be communicating with your own server software written in C# using your own custom designed protocol.

A simpler option may be to use a real web server as a "man in the middle" to which both the ESP8266 and your C# program communicate. That website could become a database back-end for your program.

Of course, what you decide to do depends entirely on how complex your program is and what data it is you want to transfer.
> 1 votes

---
Tags: arduino-uno, esp8266, c#
---


# Question
Title: Waking Arduino from sleep by holding button for more than 3 seconds
I am working on a battery powered Arduino project, where I need to put a standalone Arduino in sleep mode (to save some battery).

My aim is to put Arduino in sleep mode by holding a button for 3 seconds or more on pin 2 (hardware interrupt) and wake it up by holding the same button by 3 seconds or more.

I can put the Arduino to sleep by holding button more than 3 seconds, but I can't wake it from it by holding the button for 3 seconds.

Below is my code:

```
#include <avr/sleep.h>
const int led1 = 44;
const int led2 = 45;
const int led3 = 46;
const int usbState = 12;
float pressLength = 0;
const int button = 2;
int optionOne = 100;
int optionTwo = 3000;

void setup() {
  pinMode(button, INPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(usbState, INPUT);
  Serial.begin(9600);
}

void loop() {
  while (digitalRead(button) == LOW) {
    delay(100);
    pressLength = pressLength + 100;
    Serial.print("ms-");
    Serial.println(pressLength);
  }
  if (pressLength >= optionTwo) {
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    sleepNow();     // sleep function called here
  } else if (pressLength >= optionOne) {
    digitalWrite(led1, HIGH);
    digitalWrite(led2, HIGH);
    digitalWrite(led3, HIGH);
    while (1) {} //Keeps LEDS HIGH
  }
}

void sleepNow() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable(); // enables the sleep bit in the mcucr register
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
  sleep_mode(); // here the device is actually put to sleep!!
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
  while (digitalRead(button) == LOW) {
    delay(100);
    pressLength = pressLength + 100;
    Serial.print("ms-");
    Serial.println(pressLength);
  }
  if (pressLength >= optionTwo) {
    SleepNow(); //Back to sleep fucntion
  } else if (pressLength >= optionOne) {
    sleep_disable();
    // first thing after waking from sleep: disable sleep...
    resetFunc();//Resetting
  }
}

void wakeUpNow() {
  // 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(* resetFunc)(void) = 0;

```

Please help. Thanks.

# Answer
> 4 votes
You won't manage it without external circuitry.

The problem is the Arduino has to be awake to know you held the button for 3 seconds. You can only wake immediately you press the button. However you could then sleep again if the button is released within 3 seconds.

For external circuitry, you would need to arrange to charge (or discharge) a capacitor slowly through the button so that it reaches a threshold after 3 seconds and that threshold triggers the input to the Arduino. A HIGH input on the Arduino is 0.6×Vcc, so 3.3V for a 5V Arduino. If you arrange it that the capacitor reaches 3.3V after being charged for 3 seconds the input will see it at the right time.

simulate this circuit – Schematic created using CircuitLab

In this circuit, R1 and C1 form an RC network that charges the capacitor through the switch. C1 and R1+R2 form an RC network that discharges the capacitor all the time, so it is discharged when you release the button.

Discharge time will be slightly longer than charge time owing to the addition of R1 + R2.

To calculate the charge time, you can use T=RC which is how long (in seconds) it takes to charge the capacitor up to 63.2% of the supply voltage. That's fractionally over the 60% that the HIGH threshold is, so that's fine.

If you want T=RC to equal 3 seconds, you can rearrange the formula to suit your components. For instance if you have a 1000µF capacitor available you can rearrange to R=3/0.001 = 3kΩ. So a common 3.3kΩ resistor and 1000µF capacitor would give you (3300 × 0.001) 3.3 seconds.

R2 wants to be small enough that it doesn't slow down discharge too much, yet high enough that it doesn't draw too much current. Using about 10% of R1 is reasonable (330Ω), so with a 3.3 second charge time that resistor would increase the discharge time by 0.33 seconds.

This method is basically a very extreme form of debouncing.

---
Tags: arduino-uno, arduino-mega, interrupt, sleep
---


# Question
Title: RFID does not respond after Ethernet.begin(mac, ip) initialization
Good day, I have this problem with my simple project. I have a database with all RFID number of employee. What I want to do is to use an rfID to check if it is registered in the database. If it is, it would return a value of 1 else would be a value of 0.

I tried with arduino HanRun Ethernet shield. I was able to get a response from the php web server to the serial monitor. Tried the seeedrfid it successfully get the rfcard number. However, when i tried to combine the two, it would hang on Ethernet.begin(mac, ip) initialization. My code is below.

```
#include <Ethernet.h>
#include <SoftwareSerial.h>
#include <SeeedRFID.h>

#define RFID_RX_PIN 10
#define RFID_TX_PIN 11

SeeedRFID RFID(RFID_RX_PIN, RFID_TX_PIN);

char state = '0';
char c;
byte mac[] = {0x60, 0xF8, 0x1D, 0xBA, 0x1D, 0x52};
IPAddress ip(192, 168, 20, 228);

EthernetClient client;

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

  Ethernet.begin(mac, ip);
  Serial.print("My IP Address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {

  long rfID;
  // put your main code here, to run repeatedly:

  if (RFID.isAvailable()) {
    rfID = RFID.cardNumber();
    Serial.println(rfID);
  }
}

```

Serial.println(rfID) is not executed unless I remove the Ethernet.begin(mac, ip). Can anybody point me to the right direction?

# Answer
> 1 votes
The Arduino Ethernet shield uses pins 4, 10,11,12,13. You have a conflict with the RFID pins.

---
Tags: ethernet, rfid
---


# Question
Title: Write to serial only if the state of a light sensor changes
I need to know the times when an LED strip turns on and turns off. The LED switch is driven by light dependent resistor. When the sun goes down the LED strip turns on. This is all happening on a circuit that I did not create nor is it Arduino driven. I need to know the times (in local time) that the LED turns on and off. I have another light dependent resistor near the LED strip and I am using the Arduino Uno to print to the serial monitor its state every second. I can listen to the serial port via Python and record the seconds via Python. No worries What I would like to do is have the Arduino code print to the serial monitor only if the state of the LED changes. For example, when the LDR turns on the LED strip, Arduino prints to the serial monitor once, then in the morning when the LED goes off, print to the serial monitor once. I am having trouble figuring out the code to do that. The LDR is not like a button since it is always reporting back analog data. Any help is appreciated.

# Answer
> 2 votes
You wrote: “*I am using the Arduino Uno to print to the serial monitor its state every second.*” This is exactly the right thing to do. Make a record of the analog readings for a few days, then plot the readings as a function of time.

Once you have a nice plot, take a close look at it. You should be able, by reading the plot, to decide on a threshold value that you can use to tell whether the LEDs are on or off. Or, better yet, two thresholds in order to have some hysteresis.

Then you can write something like this:

```
const uint8_t LDR_PIN = ...;
const uint16_t THRESHOLD_LOW = ...;
const uint16_t THRESHOLD_HIGH = ...;

uint8_t state = LOW;

void loop()
{
    uint16_t reading = analogRead(LDR_PIN);
    if (state == LOW && reading >= THRESHOLD_HIGH) {
        Serial.println("Reading is now HIGH.");
        state = HIGH;
    } else if (state == HIGH && reading < THRESHOLD_LOW) {
        Serial.println("Reading is now LOW.");
        state = LOW;
    }
}

```

# Answer
> 0 votes
If you have already set the resistor to print to `Serial` every second, then it is simple to modify. Your code is probably like this:

```
void loop() {
// something something
Serial.println(analogRead(resistorPin));
// other other
}

```

and you want something like this:

```
int lastValue,newValue;
int treshold=200; // or some other empirical value,
// analogRead() returns 0..1024, so it should be safely inside
void loop() {
// something something
newValue=analogRead(resistorPin);
if (newValue-lastValue > treshold) {
    Serial.print("Value increased to ");
    Serial.println(newValue);
    lastValue=newValue;
    };
if (lastValue-newValue > treshold) {
    Serial.print("Value decreased to ");
    Serial.println(newValue);
    lastValue=newValue;
    };
// other other
}

```

the `treshold` value should be set so the event is triggered if substantial change in value happend (so probably those LEDs went on/of) but not trigger when there is a smal change (like cloud going on sky).

Eventually you can also print the time, at which the event happened, using something like http://playground.arduino.cc/Code/DateTime or http://playground.arduino.cc/Code/Time or any other library suiting your needs. You may also consider to use some real time module like https://www.pololu.com/product/2770 or https://www.adafruit.com/product/264 or https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/overview or any other RTC module you like/have.

# Answer
> 0 votes
An LDR doesn't have a "state", being a resistor that varies continuously, and inversely with the light intensity. The LED strip has distinct states: lit and not lit. It sounds like you want your code to deduce the LED state from the sensor value. You'll need to define lighting states based on the the LDR readings, and those readings won't be consistent; they'll vary from measurement to measurement of the same lighting conditions and they'll be affected by changes in the ambient lighting. If you can exclude ambient light falling on the LDR, the job will be easier. @Edgar\_Bonet described a way to ranges of LDR readings corresponding to 'lit' and 'not lit'

When a moving average of LDR readings, or some number of consecutive LDR readings falls within the range contrary to the state your code been keeping for the LED lighting, it should change the state and print.

If ambient lighting changes are unavoidably affecting the LDR, you'll definitely need to keep some sort of moving average and watch for a large difference between a small number of averaged readings and the longer-term moving average used to correct for ambient. This is a kind of auto-zeroing and it can lead to its own errors: sensing the room lights being turned on or off, cloud shadows, or a person or animal passage throwing a shadow, can all cause false change-of-state detection.

Update:

I'd add that you might compare the LDR output to 3 ranges: \[0 - MAXDARK\], \[MINLIGHT - 1023\], and "neither" - the gray zone in between. This is analogous to how the digital input-pin receivers in the MUC decide whether a digital signal (which is inherently analog) is HIGH or LOW. You'll have to experiment with the values of MAXDARK and MINLIGHT to find the right values for your environment.

Then you you'd print, once, whenever the LDR signal solidly enters either the MAXDARK or MINLIGHT zones, and not again until after the signal has solidly exited that zone, or equivalently, solidly entered the gray zone.

"Solidly" is probably something like NCONSECUTIVE averaged samples. Again, you'll have to find a value for NCONSECUTIVE that is both reliable and responsive. Too low a value may give you several time-stamps for the same event; too high a value will delay how quickly you detect the event (which might be totally irrelevant for a twice-a-day event).

# Answer
> 0 votes
> I need to know the times (in local time) that the LED turns on and off. .. I am having trouble figuring out the code to do that.

simple.

1. attach a pin to the circuit's output that turn on / off the led.
2. set up your arduino to read the state or state changes of that pin. this can be done via interrupts or polling.
3. based on the state of the pin, determine if the led is on or off, and record the current time.

step #1 can be done with light sensors (on the led's light output). but that can be slightly trickier.

> The LDR is not like a button since it is always reporting back analog data.

you can set up the ldr to read it like a button.

---
Tags: arduino-uno, serial, sensors, button
---


title: RFID-RC522 not working, red led is on

text:
# Question
Title: RFID-RC522 not working, red led is on
I am working with RFID-RC522 and Arduino UNO. I have check pin configurations again and again tried different libraries. It is not reading card and red led on RC522 is consistently on.

# Answer
> 1 votes
Here's a picture of the card reader I have. If yours looks identical, then this library should work: https://github.com/ljos/MFRC522

The auth\_read\_write.ino sketch worked for me. Before you install the library, I recommend removing any other MFRC522 libraries from your arduino/library folder.

The only thing I did differently was used a 74HC4050 running at 3.3V between the Arduino and card reader. Some people claim you can connect the reader directly to the Arduino. I didn't want to take a chance of burning out the card reader so I used the 74HC4050.

Here's how I connected it:

```
Component markings and connections

|-------------------------------------------|
|   SPI    |  UNO  | 74HC4050  | RFID-RC522 |
|----------|-------|-----------|------------|
| SDA (SS) |  10   |     7     |            |
| SDA (SS) |       |     6     |    SDA     |
| SCK      |  13   |     5     |            |
| SCK      |       |     4     |    SCK     |
| MOSI     |  11   |     3     |            |
| MOSI     |       |     2     |    MOSI    |
| MISO     |  12   |           |    MISO    |
| IRQ      |  N/C  |    N/C    |    N/C     |
| GND      |  GND  | 8,9,11,14 |    GND     |
| RST      |   5   |           |    RST     |
| 3.3V     |       |     1     |    3.3V    |
|-------------------------------------------|

```

---
Tags: arduino-uno, rfid
---


# Question
Title: Grounding for arduino, measuring phase controllled 240V
I would like to measure a phase controlled 240Vac waveform as a digital PWM input for an arduino. The signal would look something like this:

My intent was to use a zener clipping circuit to limit the positive portion of the waveform to 5V, and measure that signal. However, I want to make sure I'm properly grounding these items. This is what my proposed circuit looks like, with all components inside a metal chassis.

I feel like ideally I would isolate this waveform from the system controller/light with a 1:1 transformer, but I'm unsure if that is feasible given its irregularity. Can I safely connect the arduino ground to the system's neutral, or am I barking up the wrong tree?

Thanks!

# Answer
You shouldn't really connect the mains direct to the Arduino like that - even with a zener. The potential for disaster is somewhat large.

Instead you should galvanically isolate the mains from the Arduino. I would use something as simple as an opto-isolator:

simulate this circuit – Schematic created using CircuitLab

Make sure that R1 is rated for at least 339V and can dissipate enough power (1W). The resistance of R1 needs to be small enough that the opto-isolator triggers properly, yet large enough that you don't need a great honking heater of a resistor to cope with the power. 150K seems a reasonable compromise.

D2 is needed to prevent the LED In the opto-isolator from being reverse biased with 339V in the reverse-swing portion of the waveform.

You can incorporate your zener as well if you want to "push down" the waveform to get a lower cross section of it (clip off the upper portion) instead of just reducing its amplitude:

simulate this circuit

In this R1 is the same as the resistor you were planning to use before. The added R3 resistor is to limit the current through the LED (drop the 5V to the LED forward voltage at a suitable current for the LED).
> 0 votes

# Answer
your circuit will work, and can be simplified a little bit further. But it will work.

it is safer to use isolation, however. there are multiple ways to go about doing it.

the key here is to detect zero crossing, and start counting from there.
> 0 votes

---
Tags: arduino-uno, pwm, electronics, electricity, voltage-protection
---


# Question
Title: How can I swap a servo with a stepper motor?
I'm looking for a way to swap servo 1 with a stepper motor to achieve a single direction circular motion with stops and delay. Instead, now I have the servo going back and forth to repeat the action.

This is the code I'm currently using to drive the servo:

```
void loop() {
  topServo.write(115);
  delay(500);

  for(int i = 115; i > 65; i--) {
    topServo.write(i);
    delay(2);
}

```

This is a schematic of my project:

simulate this circuit – Schematic created using CircuitLab

Can anyone help me to configure this? or point me into the right direction.
Any help would be greatly appreciated!

# Answer
Firstly, I'm going to assume that you got a ULN2003 Motor driver board something like this along with your 28-BYJ48 stepper motor.

Secondly, I would always recommend using a separate power supply for your stepper motors. Even a small stepper motor like the 28-BYJ48 can draw up to 320mA, (160mA per winding).

---

I've used the following code to test a setup using a 28-BYJ48 stepper motor and an Arduino. The connections to the driver board (IN1 - IN4) are mapped to pins 8-11 on the Arduino in this case. The code will cause the stepper to rotate 1 full revolution in one direction, pause for 1 second and then rotate one full revolution in the other direction.

(I've often found this simple piece of code really handy for troubleshooting!)

```
#include <Stepper.h>

const int stepsPerRev = 2048

// initialise the stepper library on pins 8, 9, 10 & 11
Stepper myStepper(stepsPerRev, 8,10,9,11);

void setup() {
  // set the speed
  myStepper.setSpeed(4);

}

void loop() {
  // step one revolution in one direction:
  myStepper.step(stepsPerRev);
  delay(1000);

  // step one revolution in the other direction:
  myStepper.step(-stepsPerRev);
  delay(1000);

}

```
> 2 votes

---
Tags: sensors, arduino-nano, servo, stepper
---


# Question
Title: Can not receive data from UART with stepper motor
I am using an Arduino Mega2560 While my motor is moving I can not receive anything from the UARTs. When the motor ends movement, I receive data from UART.

How can I make my motor move without stopping the reception of data from UART?

# Answer
> 1 votes
If you look at AccelStepper.cpp code of the library you're using, you'll notice that runToNewPosition() is:

```
void AccelStepper::runToNewPosition(long position)
{
    moveTo(position);
    runToPosition();
}

```

which, in turns calls:

```
// Blocks until the target position is reached
void AccelStepper::runToPosition()
{
    while (run())
    ;
}

```

In turn, run() returns false only when the position is reached, as shown here:

```
boolean AccelStepper::run()
{
    if (_targetPos == _currentPos)
    return false;

    if (runSpeed())
    computeNewSpeed();
    return true;
}

```

As you can see, your program is blocked until the position is not reached.

Data can be still received by the serial port (until buffer is exceed), but you won't be able to read it until that while ends.

To make the motor running without blocking the program, you should implement the AccelStepper functions in the loop function, in a non-blocking way.

In particular, (I only help you to set the position to 1100. You'll make the effort to bring it back to 0, with small modifications), in `rotate_motor()` call only:

```
stepper1.moveTo(1100);

```

Then in the loop, write somewhere:

```
stepper1.run();

```

EDIT: Hint for having the motor moving forward and then backward as in your original code: Add a state variable (say you call it "`m`"), where you store if you need to move forward (e.g. 2), backward (e.g. 1) or stop (0). Then, before calling `stepper1.run()`, check if you actually must move (`if (m != 0)`). When you call the `stepper1.run()` method, check if it returns `false`. In this case it means it reached the position, then you must change the value of m accordingly.

---
Tags: arduino-mega, motor, uart, stepper
---


# Question
Title: Troubleshooting an Arduino Computer Program
I am trying to make a serial monitor print something based on when a button is pushed.

When the button is not pushed, the variable storing it equals 1.
When the button is pushed, the variable equals 0.
When I have an if statement like this, why does it print what I want when I have one where the zero is, but not when it is like that and the button IS pressed.

Thanks

```
int led = 2;
const int buzzer = 3;

int upButton = 5;
int downButton = 7;
int enterButton = 6;

int up = 1;
int down = 1;
int enter = 1;

bool homeActivated = true;
bool appsActivated = false;

int homeLocation = 1;
int appsLocation = 1;

bool homePrinted = false;
bool appsPrinted = false;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode (upButton, INPUT);
  pinMode (enterButton, INPUT);
  pinMode (downButton, INPUT);
  Serial.println("Initializing");
  delay(2000);
}

void loop() {
  up = digitalRead (upButton);
  enter = digitalRead (enterButton);
  down = digitalRead (downButton);

  //move up and down
  if (up = 0)
  {
    if (homeActivated = true)
    {
      homeLocation + 1;
      Serial.println("Scrolled Down 1");
      delay(1500);
      homePrinted = false;
    }
    else if (appsActivated = true)
    {
      appsLocation + 1;
      Serial.println("Scrolled Down 1");
      delay(1500);
      appsPrinted = false;
    }
  }

```

# Answer
> 0 votes
You need to learn basic C syntax.

`=` is assignment, not comparison.

For comparison you use `==`

---
Tags: serial, code-review
---


# Question
Title: Is there a way to keep a program on the Arduino after uploading new sketches?
I am looking for a way to keep a program on my Arduino Nano 3.0, after uploading new sketches on it. I would like to have a program on it that will control th screen and buttons at it. The user will choose one of the programs displayed on the screen and execute/pause/stop them. These programs will be uploaded on the Arduino, while the previous programmes stay.

If you are familliar with the Lego Mindsdorm microcontroller, you probably know waht I am looking for.

Is there a way to do that.

# Answer
> 1 votes
I'm not familiar with Lego Mindstorm, but I think I understand what you want and I am certain there is a way to do it, but I don't think it will be easy or even practical and I can't tell you exactly how to do it.

I'm pretty certain there will be a way to load a 'module' into memory and then make the program call that address. I haven't got a clue how you would do it though, sorry. GCC doesn't have a concept of DLLs like window does, but it does have shared libraries. Or you might look at just reading a block of memory in.

Other approaches might be to have all the 'programs' as functions within you main program and call them depending on the user's input. You can only do this if the 'programs' are small enough.

If you can refactor your 'programs' to extract the common code into functions and then have a data file (which could be read at runtime) that called the functions for each of your programming. Basically invent your own higher level programming language. This wouldn't work if your code was very different and you could factor it down to a small enough number of functions.

Would it be possible to just have a number of hex files (compiled programs?) all of which have the common screen/button handler in and then have the special code for the appropriate program. These could all be stored on an SD card and then loaded into memory by a second Arduino (sounds plausible to me, I'm sure someone will tell me whats wrong with that idea.)

An alternative based on the inverse of the above solution would be to have one Arduino to control the screen/buttons and it programs a second Arduino with the specialist code that is connected to the rest of your kit.

# Answer
> 1 votes
You want something like this using the serial monitor:

```
if((homeMenuActivated) == true)
{
  Serial.println ("Program Number 1");
}

```

I am kind of glad you asked this, as I am working on a similar program with arduinos that can do the same thing you want.

# Answer
> 0 votes
The Arduino paradigm uses two programs on the target. The boot loader and the application. The processor is agnostic WRT this differentiation and runs the entire code set as one large application.

To put a 2nd application on an embedded processor is feasible. However, you would have to be intimately knowledgeable about how Arduino SDK works as well as the boot loader as you would have to create new features to relocate code normally found at fixed locations. A rather involved task.

Instead, consider simply adding your utility code to your application code in the Arduino SDK and replace the utility code already on the processor with the new image.

# Answer
> 0 votes
> Is there a way to do that.

sure.

one way to do it is to use a pin to indicate which program you want to execute.

```
uint8_t execution_switch=0;  //execution switch. 0->run setup0()/loop0(), 1->run setup1()/loop1()

void setup(void) {
  pinMode(EXECUTION_SWITCH, INPUT_PULLUP); //execution switch as input + pullup
  execution_switch=(digitalRead(EXECUTION_SWITCH)==LOW)?0:1;
  if (execution_switch==0) setup0(); else setup1();
}

void loop(void) {
  if (execution_switch==0) loop0(); else loop1();
}

```

you can easily change it to accommodate multiple programs / multiple switch pins, or real time switch, ....

---
Tags: programming, arduino-nano, sketch
---


# Question
Title: Super-fast USB communication; how is it possible?
On Arduino forums, there's a post where someone improved the USB communication and made it super-fast. I don't understand how he did this, and I'm trying to recreate this, but failing.

## My test code

I made a simple program on Python for testing; here it's:

```
import serial
import sys
import datetime

ser = serial.Serial(
   port = 'COM9',
   baudrate = 26*115200, #biggest number acceptable by python
   parity = serial.PARITY_NONE,
   stopbits = serial.STOPBITS_ONE,
   bytesize = serial.EIGHTBITS
)

if ser.isOpen() == False :
   ser.open()
   if ser.isOpen() == False :
      print("Can't open serial port")
      sys.exit(1)

start = datetime.datetime.now()
s = b'abc'*10000
ser.write(s)
total_len = len(s)
end = datetime.datetime.now()
speed = total_len/(end - start).total_seconds()/1e6
print("Speed: " + str(speed) + " MB/s")

```

And I made a simple Arduino program to read:

```
char buf[500];

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

void loop() {
  if (Serial.available() > 0) {
     Serial.readBytes(buf, 500);
  }
}

```

With this, my best result was `0.2 MB/s` with my Arduino mega. However, on that post, they reached 12 Mbit/s = 1.5 MB/s!!!!! This is insane!

## Atemmpting to achieve their result:

Apparently Arduino libraries are different than before, so just taking their code and putting it in my `arduino\avr\cores\arduino` directory doesn't work. So I started trying to edit the code myself. I'm a C++ dev, so supposedly this should be doable... but...

## The problem I faced

So eventually, the problem I faced was that there are two Serial communication modes (apparently) UART and CDC. The code from the forum uses CDC, while my Arduino IDE uses UART. I tried enabling CDC using:

```
#define USBCON

```

but this lead to the error:

```
error: #error "Targets with both UART0 and CDC serial not supported"

```

At this point I don't know how to continue, as I'm not a hardware expert. But I'd like your opinion on this whole thing:

1. Is it possible to get these speeds? How?
2. If it's, why is it not in the default Arduino library?
3. In case there's no easy answer for the other questions, is switching from UART to CDC easy, so that I could continue my testing?

# Answer
> 2 votes
> Is it possible to get these speeds? How?

Not without a 32-bit Arduino with a USB interface.

> If it's, why is it not in the default Arduino library?

Because you can't use it on an 8-bit Arduino without a USB interface.

> In case there's no easy answer for the other questions, is switching from UART to CDC easy, so that I could continue my testing?

Yes, get a 32-bit Arduino with a USB interface such as the Arduino Due that the poster of that thread used.

---
Tags: serial, arduino-ide, usb, uart, code-optimization
---


# Question
Title: Angular velocity of a dc motor controlled by a potentiometer
I created a setup in which a potentiometer controls a dc motor, with current flow through the dc motor controlled by an H-bridge. The principle is as follows: With the potentiometer dial set to the mid-point, the motor is off. Rotating the potentiometer clockwise would cause the motor to rotate in one direction, with speed dictated by the displacement of the potentiometer from the mid-point: the greater the displacement from mid-point, the greater the speed of rotation of the motor. If the potentiometer is rotated anti-clockwise, away from mid-point, the motor would rotate in the opposite direction from before; again, with speed dictated by the extent of displacement of the potentiometer from mid-point.

The loop has three functions, where HB\_12EN is to enable the drivers, HB\_1A is the first driver input, and HB\_2A is the second driver input (H-Bridge pins 1, 2 and 7, respectively) as per this datasheet: http://www.ti.com/lit/ds/symlink/sn754410.pdf

To summarise their functions: HB\_12EN allows voltage to be applied to the the device controlled by the H-Bridge (in this case a motor), and is pulse-wave-modulated. HB\_1A and HB\_2A control the flow of current through the motor, setting its angular velocity. HB\_1A set HIGH and HB\_2A set LOW directs current one way through the motor, and HB1A set LOW and HB\_2A set HIGH directs current the other way through the motor.

The loop is:

```
//OUTPUTS
int const HB_12EN = 9; //pwm pin
int const HB_1A = 2;
int const HB_2A = 3;

//INPUTS
int const POT_MOT = 0; //A0, analog 0

//GLOBAL VARIABLES
unsigned int pot_val = 0; //ADC value from potentiometer
unsigned int grp_num = 1;

pot_val = analogRead(POT_MOT);
grp_num = setMotSwitch(HB_12EN, HB_1A, HB_2A, pot_val, grp_num);
setMotSpeed(HB_12EN, pot_val, grp_num);

```

The two (non-library) functions are:

```
unsigned int setMotSwitch(int const motor_reg, int const first_motor, int const sec_motor, unsigned int pot_value, unsigned int group_num) //grp 0: 0-383; grp 1: 384-639; grp 2: 640-1023
{
  if (pot_value >= 0 && pot_value < 384)
  {
    if (group_num != 0)
    {
       digitalWrite(motor_reg, LOW);
       digitalWrite(first_motor, HIGH);
       digitalWrite(sec_motor, LOW);
       group_num = 0;
    }
  }
  else if (pot_value > 383 && pot_value < 640)
  {
    if (group_num != 1)
    {
      digitalWrite(motor_reg, LOW);
      digitalWrite(first_motor, LOW);
      digitalWrite(sec_motor, LOW);
      group_num = 1;
    }
  }
  else if (pot_value > 639 && pot_value <= 1023)
  {
    if (group_num != 2)
    {
      digitalWrite(motor_reg, LOW);
      digitalWrite(first_motor, LOW);
      digitalWrite(sec_motor, HIGH);
      group_num = 2;
    }
  }
  else
  {
      digitalWrite(motor_reg, LOW);
      digitalWrite(first_motor, LOW);
      digitalWrite(sec_motor, LOW);
      group_num = 0;
  }
  return group_num;
}

void setMotSpeed(int const motor_reg, unsigned int pot_value, unsigned int group_num)
{
  unsigned int mot_speed = 0;
  if (group_num == 0)
  {
    mot_speed = map(pot_value, 0, 383, 255, 0);
    mot_speed = constrain(mot_speed, 0, 255);
    analogWrite(motor_reg, mot_speed);
  }
  else if (group_num == 1)
  {
    if (pot_value > 500 && pot_value < 523)
    {
      digitalWrite(motor_reg, HIGH); //braking
    }
    else
    {
      digitalWrite(motor_reg, LOW);
    }
  }
  else if (group_num == 2)
  {
    mot_speed = map(pot_value, 640, 1023, 0, 255);
    mot_speed = constrain(mot_speed, 0, 255);
    analogWrite(motor_reg, mot_speed);
  }
}

```

I tried to proceed as follows: As the potentiometer would produce an ADC input with 1024 states, I divided those 1024 states in to 8 groups, the first three groups, covering the first 384 states (0-383) correspond to a dc motor direction (let's say anticlockwise), representing different speeds of rotation (ignoring issues of many-to-one mapping). The middle 2 groups, 256 states (384-639), correspond to a stationary motor. The last three groups, 384 states (640-1023), correspond to motor rotation in the other direction (in this example, clockwise). The ADC inputs have to be translated in to analog outputs with 256 possible states (0-255), so I map each range as appropriate; for 0-383, the mapping has to be reversed, so an input of 383 corresponds to an input of 0. The middle range (384-639) is stationary, but I tried to make a small "sub"-range in the middle a "braking range", I believed this is achieved by setting both H-bridge inputs to LOW. The 640-1023 range mapping is 640 to 0 and 1023 to 255.

Hopefully that makes sense. It seems to work, the issue I am having is that the motor seems to achieve a greater speed in one direction compared to the other: the maximum rotation speed produced in the motor is greater when the potentiometer is at its maximum in one direction compared to the other. I am pretty sure the code above gives an "even" mapping from the potentiometer to the motor for both directions. Is this, then, something to do with hardware?, and is it something to be anticipated in these kinds of setups?

Any help would be appreciated. If anyone has any advice on the best way to combine a potentiometer -or similar- input with a motor output let me know. The "braking" functionality is also a little confusing.

# Answer
> 1 votes
Personally I wouldn't bother with "groups". Just do simple maths:

```
int velocity = analogRead(POT_MOT) - 512;

```

`velocity` now gives you a value from -512 to +511.

```
bool dir = (velocity >= 0);

```

`dir` is now `true` for a positive value (0 is considered positive) or `false` for negative.

```
velocity = abs(velocity);

```

`velocity` is now made positive if it is negative.

So you now have two variables: `dir` which sets the direction, and `velocity` which sets the speed.

Now you can "offset" it:

```
velocity = map(velocity, 0, 512, -128, 255);

```

`velocity` is now changed to fit into the range -128 to 255. Anything above 0 is a valid speed, anything below is the "dead zone" and stops the motor.

```
if (velocity <= 0) {
    // If it's negative or zero stop
    digitalWrite(motor_reg, LOW);
    digitalWrite(first_motor, LOW);
    digitalWrite(sec_motor, LOW);
} else {
    if (dir) { // Pot was positive
        analogWrite(motor_reg, velocity);
        digitalWrite(first_motor, LOW);
        digitalWrite(sec_motor, HIGH);
    } else { // Pot was negative
        analogWrite(motor_reg, velocity);
        digitalWrite(first_motor, HIGH);
        digitalWrite(sec_motor, LOW);
    }
}

```

Adjust the negative value in the map to change the size of the "dead zone".

# Answer
> 0 votes
i would break out this into three or at least two parts:

1) a call to change the speed of the motor; 2) a call to read the potential meter setting; 3) a call to convert the potential meter setting into motor speed, optional.

the code would look like this:

```
  pot_setting = potsetting_read(); //read pot setting
  speed_setting = pot2spd(pot_setting); //convert pot setting to motor speed
  motor_setspeed(speed_setting); //set motor speed

```

it is not difficult to figure out each of the three functions.

the more challenging of the three, to a newbie, is the one that sets the motor speed. there are many ways to do it, and I personally prefer to use timer interrupts.

the basic construct is to sequentially go through a set of pin states, where the duration of each state transition is controlled by a timer interrupt. by changing how fast that timer interrupt takes place, you change the speed in which the pins transition their states, thus motor speed.

---
Tags: motor, potentiometer
---


# Question
Title: Simplest/best way to control a set of 8-10 PWM signals from a smartphone
As part of a larger project, I would like to be able to control a set of 8-10 PWM signals remotely, from a smartphone at a distance of 10 meters or more. I will probably convert the PWM signals to analog voltages, and reduce their voltage swings to more like 0-1v, using a resistor divider and RC filter; they will drive high impedance loads in the remainder of the project. I’d write an app for the smartphone allowing user control over the duty-cycle of each PWM signal (and thus the analog signal levels).

It seems to me that the way to go is Arduino, interfaced to the phone with Bluetooth. I'd need one of the higher end Arduinos to get enough PWM signals (the basic ones like Uno only have 6 PWM outputs). Software-generated PWMs are probably not high-frequency enough, as I’d like the filtered analog signals to be as ripple-free as possible. There seem to be several ways to interface Bluetooth to Arduino, such as the HC-05.

If people here concur with this approach, I shall move this question to the Arduino forum.

\`

# Answer
> 1 votes
HC-05 is rated to about 9m so it wouldn't necessarily meet your requirement. The ESP8266 (example of one implementation called the Node MCU) can output PWM on any of the 0-16 pins. It can easily implement a web server which would let you control your outputs via 8026.11 (wifi). It also means you don't need to build anything for the phone/ tablet/ PC just use a web browser. The duty cycle could be set through the web server on the ESP. The ESPs are around the same price as an Arduino.

I've used the HC-05 with an arduino. It works very well, though not very far. For the Android side I used app inventor which is extremely easily to use for bluetooth.

---
Tags: pwm, wireless
---


title: Detect when RFID card is absent

text:
# Question
Title: Detect when RFID card is absent
I am trying to build a mobile device that turns itself on when removed from its usual location. I am attempting to do this with an Adafruit PN532 RFID reader and a MiFare card. Using the sample code I can detect when the card is present

```
success= nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
Serial.println("Scanning");
if (success){
  Serial.println("FOUND");
}

```

However, when I try to detect the absence of the card using the following code it will tell me "Present" over and over (since its in the Loop) while the RFID card is present but when it is removed it stops printing "Present" but never prints "Card Gone"

```
success= nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
    Serial.println("Present");
    if (!success){
      Serial.println("Card Gone");
    }

```

Is this a function of how Im using ! or is there something else at play here? I have found very few suggestions regarding detecting the absence of an RFID card and none of them seem to provide any useful answer. Most suggest some other hardware methodology as the solution. That is not the type of answer Im interested in for the moment. I would simply like to figure out why my code is incorrect.

# Answer
> 2 votes
First, your code isn't structured properly. It should be:

```
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

if (success)
  Serial.println("Present");
else
  Serial.println("Card Gone");

```

From what I could find in the library, the reason you aren't getting either the 'Card Gone' or 'Present' message when there is no card is because `nfc.readPassiveTargetID()` is a blocking function. It will wait forever until a tag is detected, at which point it returns to the caller. When you bring a card within the reader's range, the function returns quickly and `loop()` runs smoothly, giving you the 'Present' message over and over again. When you remove the card however, on the next call of `nfc.readPassiveTargetID()`, the function tries to locate a card but finds none and then it keeps trying and does not return. So `loop()` never gets past that point, until you bring a card within range again.

To detect the presence or absence of something, an observer must observe for some *pre-determined period of time* before making a decision. So, I suggest you get the latest version of this library which gives you the option of adding a milliseconds `timeout` argument to `nfc.readPassiveTargetID()`. That way, you can specify how long you want the function to try detecting a card before concluding there is no card and returning.

Alternatively, you could use your existing function as is but in `setup()` you need to set the maximum number of re-tries before the `nfc.readPassiveTargetID()` returns. This is done with `setPassiveActivationRetries()`. Any argument from 0x00 to 0xFE indicates a finite number of tries, while 0xFF is to wait forever:

```
nfc.setPassiveActivationRetries(0x9A); // for example
nfc.SAMConfig();  // this comes next

```

Good luck.

# Answer
> 0 votes
You can edit the .cpp file and add a timeout. I did this to remove the blocking scan. Search for TIMEOUT in the Adafruit\_PN532 source code.

---
Tags: arduino-uno, rfid
---


# Question
Title: Problems Writing and Clearing 24FC512 EEPROM using Arduino Uno
# Solution:

Majenko properly pointed out that I was trying to write across page boundaries and either overwriting or skipping blocks of the EEPROM when I did. This updated write function checks for a page boundary and splits the write into two writes if it is going to write over one.

```
void writeEEPROMPage(long eeAddress)    {
  int writes = incr;
  bool overflow = false;

  //check for page overrun, adjust writes to fill page and set flag if overrun
  if((eeAddress % 128 + incr) > 127)    {
    writes = 128 - eeAddress % 128;
    overflow = true;
  }
  Wire.beginTransmission(EEPROM_ADR);

  Wire.write((int)(eeAddress >> 8)); // MSB
  Wire.write((int)(eeAddress & 0xFF)); // LSB
  //Write bytes to EEPROM
  Wire.write(rwBuffer, writes); //Write the data
  Wire.endTransmission(); //Send stop condition
  eeAddress += writes;

  if(overflow)  {
    delay(5);
    Wire.beginTransmission(EEPROM_ADR);

    Wire.write((int)(eeAddress >> 8)); // MSB
    Wire.write((int)(eeAddress & 0xFF)); // LSB

    //Write remaining data to new page
    Wire.write(rwBuffer + writes, incr - writes);

    Wire.endTransmission();
    eeAddress += incr - writes;
  }
}

```

# Problem:

I am currently working on a project to record sensor readings to a 24FC512 512kb I2C EEPROM and have been teaching myself to read and write properly to this chip using an Arduino Uno. I am having a problem: when I write too many bytes in one I2C cycle, some bytes of data are skipped and not written.

In theory, I believe I should be able to write up to a 128-byte page to the EEPROM and the buffer in the Arduino Wire library should allow me to write up to 32 bytes (including address) in one transmission without modification. However, when I write more than a certain number of bytes, typically 16, and then read back the data from the EEPROM, I notice that the write commands seem to have skipped part of the write.

For instance, when trying to clear pages of 20 bytes at a time using 0xF0 to fill the space I get this result in the first few lines in blocks of 20:

```
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  11  22  33  44  55  66  77  88
+12 lines of F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  55  66  77  88  99  AA  BB  CC
+12 lines of F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  99  AA  BB  CC  DD  EE  FF  00
+5 lines of F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  11  22  33  44  55  66  77  88

```

The section that has not been cleared matches the original pattern in that location. When I reduce the page size to 16 bytes, the problem goes away and everything is written correctly. The uncleared pattern is also periodic after the first three lines, running 12 lines, error, 12 lines, error, 5 lines, error for the rest of the data. When tried with 30 bytes per transmission, it's periodic by 3-8-3 when organized in lines of 30. In all cases the errors have been at the end of each page of transmission.

This has become very frustrating because I'd like to get the data written to the EEPROM in as little time as possible so I can get a good sensor sample rate (currently 24 bytes per sample) and have time to run other functions. Ideally I'd be able to write every 5 ms to increase the sampling rate to the maximum supported by the EEPROM, so I need to solve this problem.

Here is the code I am using to clear and read the contents of the EEPROM. The variable incr holds the size of the writes I want to make, and pin 12 decides whether the program will read the EEPROM (high) or clear the EEPROM (low). I write data to the EEPROM with the commented out array to run my tests. It is based on example programs for EEPROM from Sparkfun.

```
#include <Wire.h>

#define EEPROM_ADR 0x54

const int incr = 30;
byte rwBuffer[] = {
  0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
  0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
  0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
  0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0
};

void setup() {
  pinMode(13, OUTPUT);
  pinMode(12, INPUT);
  Wire.begin();
  Wire.setClock(400000);
  long currentSpot = 0;
  if (digitalRead(12)) {
    dumpEEPROM();
  } else {
    while (currentSpot < 64000) {
      writeEEPROMPage(currentSpot);
      currentSpot += incr;
      delay(7);
    }
  }
}

void loop() {
  digitalWrite(13, !digitalRead(13));
  delay(500);
}

void writeEEPROMPage(long eeAddress) {
  Wire.beginTransmission(EEPROM_ADR);
  Wire.write((int)(eeAddress >> 8)); // MSB
  Wire.write((int)(eeAddress & 0xFF)); // LSB
  //Write bytes to EEPROM
  Wire.write(rwBuffer, incr); //Write the data
  Wire.endTransmission(); //Send stop condition
}

void dumpEEPROM() {
  long i;
  int j, readnum, timer = 0;
  Serial.begin(115200);
  timer = millis();
  for (i = 0 ; i < 64000 ; i += incr) {
    //Read all bytes from EERPOM
    readnum = readToBuffer(i);
    for (j = 0; j < incr; j++) {
      if (rwBuffer[j] < 0x10)
        Serial.print("0");
      Serial.print(rwBuffer[j], HEX);
      Serial.print("  ");
    }
    Serial.println();
  }
  timer = millis() - timer;
  Serial.print("Full data dump took ");
  Serial.print((float)timer / 1000, 3);
  Serial.println(" seconds.");
  Serial.end();
}

int readToBuffer(long address) {
  int i = 0;
  Wire.beginTransmission(EEPROM_ADR);
  Wire.write((int)(address >> 8)); // MSB
  Wire.write((int)(address & 0xFF)); // LSB
  Wire.endTransmission();
  Wire.requestFrom(EEPROM_ADR, incr);
  for (i = 0; i < incr && Wire.available(); i++) {
    rwBuffer[i] = Wire.read();
  }
  return i;
}

```

# Answer
> 0 votes
You are trying to do a page write across a page boundary.

> The write control byte, word address and the first data byte are transmitted to the 24XX512 in the same way as in a byte write. But instead of generating a Stop condition, the master transmits up to 127 additional bytes, which are temporarily stored in the on-chip page buffer and will be written into memory after the master has transmitted a Stop condition. After receipt of each word, the seven lower Address Pointer bits are internally incremented by one. If the master should transmit more than 128 bytes prior to generating the Stop condition, the address counter will roll over and the previously received data will be overwritten. As with the byte write operation, once the Stop condition is received, an internal write cycle will begin

You are sending blocks of 30 bytes (`incr = 30`). You have 128 byte pages.

* 128 / 30 = 4.267 writes per page. The 5th write spans pages. But, in a big bold NOTE in the datasheet:

> Page write operations are limited to writing bytes within a single physical page, **regardless** of the number of bytes actually being written. Physical page boundaries start at addresses that are integer multiples of the page buffer size (or ‘page size’) and end at addresses that are integer multiples of \[page size – 1\]. If a Page Write command attempts to write across a physical page boundary, the result is that the data wraps around to the beginning of the current page (overwriting data previously stored there), instead of being written to the next page as might be expected. It is therefore necessary for the application software to prevent page write operations that would attempt to cross a page boundary.

So you write 4 blocks to the first page, then the 5th block fills in the end of the first page *then goes back to the start of that page and overwrites what has already been written earlier*. Your next page then starts part way through the next block skipping a chunk that you cannot now get to.

You must either do your writes in blocks of an integer division of 128 (so 16 bytes is the largest you can do) or manually detect a page boundary and split your block write into two separate writes - one to finish filling the first page and the next to start filling the next page.

# Answer
> 0 votes
Right after each `Wire.endTransmission();` you need to insert a `delay(5);`. The errors you see could be write-related, and/or read related too. You have to let the EEPROM chip process the address request before you start dumping/reading.

---
Tags: arduino-uno, i2c, eeprom
---


title: How to "break" a function we made?

text:
# Question
Title: How to "break" a function we made?
This is code about a keypad lock. The user can unlock the device by entering the secret code. To lock it again they press "#" or "\*".

I want to let the green LED turn on for about 0.5 seconds then return to the first line of the loop: `char key = keypad.getKey();`.

The problem is that this code makes the green LED turn on forever after we enter the correct secret code or until we enter "#" or "\*".

```
void loop() {
  char key = keypad.getKey();
  if (key=='*'||key=='#') {
    position = 0;
    setLocked(true);
  }
  if (key==secretCode[position]) {
    position ++;
  }
  if (position ==3) {
    setLocked(false);
  }
  delay(100);
}

void setLocked(int locked) {
  if (locked) {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  } else {
    digitalWrite(redpin, LOW);
    digitalWrite(greenpin, HIGH);
    delay(500);
  }
}

```

# Answer
I may be missing something, but couldn't you just modify your `setLocked` function?

```
void setLocked(int locked) {
  if (locked) {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  } else {
    digitalWrite(redpin, LOW);
    digitalWrite(greenpin, HIGH);
    delay(500);
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  }
  return;
}

```
> 2 votes

# Answer
I was looking at your `loop()` and it have some problems, like not counting how many digits did the user input and locking upon receiving a single "#" a

Here is some better way:

```
char secretCode[] = "1234";
char inputCode[] = "xxxx";
int position = 0;

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

void loop() {
  char key = keypad.getKey();

  if (key == '*' || key=='#') {
    int i = 0;
    //  With 4 input digits, now we compare against secret code.
    while (i < sizeof(inputCode) && inputCode[i] == secretCode[i]) {
      i++;
      }
    //  Set locked only if 4 digits are the same.
    setLocked(i == sizeof(inputCode));
    //  Reset input code array.
    position = 0;
  } else {
    //  Key adding digits to the input code.
    inputCode[position++] = key;
    if (position == sizeof(inputCode)) {
      position = 0;
    }
  }
  delay(100);
}

void setLocked(int locked) {
  if (locked) {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  } else {
    digitalWrite(redpin, LOW);
    digitalWrite(greenpin, HIGH);
    delay(500);
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  }
  return;
}

```
> 2 votes

# Answer
The problem is that when the device is unlocked with the correct code, you turn the green LED on wait for 0.5 seconds and then you don't turn it off again. So the simple answer would be sempaiscuba's answer.

Personally, I like the fact that the red LED indicates that the device is locked and the green LED indicates that it is unlocked.

The problem that I see with your code is that if the user enters an incorrect number, it doesn't reset, allowing any amount of wrong numbers until it sees the right number. This means that I could come along and press the keypay randomly and after a while I would have pressed every digit in the secret code and it would unlock.

Think of the problem as a state machine. You start with 0 digits correct (ie `position==0`). If at any time the user presses an incorrect digit (or the * or #), the state machine will reset back to 0 digits correct state. If the user enters the first digit correctly then it progresses to the 1 digit correct state (ie `position==1`). And so on until all of the digits are correct and the device is unlocked. Due to the simplicity of this state diagram it can be accomplished using a few if statements.

```
int position = 0;
char secretCode[] = "7890";
char inputCode[] = "????";      // This can be any character and just acts as a placeholder
boolean newKey = false;

void setup()
{
    setLocked(true);
}

void loop()
{
    char key = keypad.getKey();

    // Only process when a new key has been pressed
    if ((key != NO_KEY) && newKey)
    {
      newKey = false;  // Don't enter this if statement again if the key is being held down (used for debounce)

      if ((key == secretCode[position]) && (position < 3))
      {
          // The correct key has been pressed
          position ++;
          if (position == 3)
          {
            // Correct code has been entered (all 4 digits)
            setLocked(false);
          }
      }
      else
      {
        // It must be a wrong key (including * & #)
        // Or the device is unlocked and the user is locking it again.
        setLocked(true);
      }
    }
    else
    {
        // Key has been released (used for debounce)
        newKey = true;
    }
}

void setLocked(boolean locked)
{
    if (locked)
    {
        position = 0;
        digitalWrite(redpin, HIGH);
        digitalWrite(greenpin, LOW);
    }
    else
    {
        digitalWrite(redpin, LOW);
        digitalWrite(greenpin, HIGH);
    }
}

```

Once unlocked, all you have to do is press any key to lock it again.

Resources: http://playground.arduino.cc/Code/Keypad
> 0 votes

---
Tags: arduino-leonardo, code-review
---


title: GPS and Arduino

text:
# Question
Title: GPS and Arduino
I am working on a project with an Arduino Uno. I want to know if the latitudes and longitudes can be input to the Arduino for the Arduino to move to that particular location. If it's possible then which sensors or actuators are to be used? Please also mention some references for me to read and collect the required information.

# Answer
OK, notwithstanding Majenko's excellent suggestion in the comments above, I played around with Arduino and GPS, so I can probably offer a few pointers.

---

**First, GPS**:

All the GPS modules that I have played with give out a series of standard strings of information or "sentences". These sentences are defined by the National Marine Electronics Association (NMEA) protocol. You are going to want to spend some time learning how to use this information.

The most commonly used string in an NMEA sentence is **$GPRMC**. From this you can extract date, time and position. But there is a lot more useful information in an NMEA sentence, so do your research.

When you have decided which GPS module you want to use, just use Google to search for sample Arduino code specific to that module. That should be enough to get you started.

---

**On the subject of GPS Modules:**

There are many available. Just Google search for "Arduino GPS module".

They vary in price from a few GB pounds to well over a hundred GB pounds. It all depends on what you need from it, and what you can afford. Personally, I got very good results from cheap (~ £5 GB) Neo-6M modules (like the one shown here) with some mobile robots I was experimenting with.

Now, I've just typed "*Neo-6m GPS Arduino*" into Google, and one of the first sites was this Instructable, which has more than enough information to get you going with this combination.

---

**Path planning**

Yes, you could give a robot a GPS and a target location and have it plan a route and move to the new location.

Sounds easy doesn't it?

It isn't.

It really, *really* isn't!

Path planning is a complicated discipline. There is an introductory course on Computational Motion Planning available (free to audit last time I looked) on Coursera if you are interested. It's part of a Robotics "Speciality", so depending on your existing skills, you might want to work through the modules in sequence.

\[If you do decide to do all the modules in the Speciality, I shared my notes for some of the modules via my Scribd account. Some of these also contain elements on motion planning. (***Be warned***, some of them also contain a lot of maths!)\]

The best practical advice I can give is to start small.

I tested my robots in a local park, over distances measured in tens, rather than hundreds of metres. I then introduced obstacles (trees) in a different part of the park, and things got a whole lot more interesting! (Not least, of course, because GPS really doesn't like trees! So you have to use other sensors when the robot isn't receiving data from the GPS ...).

And if you think that's complicated, just wait until you introduce "moving obstacles", like people, dogs, cars, bicycles, ...!

---

Hopefully that will give you some pointers to get you started. When you hit problems with your code (and you're almost certainly going to hit problems with your code!), sites like this will be a godsend.

I really wish Arduino: SE had been around back when I was banging my head against the proverbial wall trying to work out why my code wasn't doing what I expected it to!
> 2 votes

# Answer
See this site, for a practical example:

http://www.instructables.com/id/Arduino-Powered-Autonomous-Vehicle/
> 1 votes

---
Tags: arduino-uno, programming, arduino-ide, gps, coding-standards
---


title: Linux SSH command for Arduino Console

text:
# Question
Title: Linux SSH command for Arduino Console
I have a Leonardo with a Yun shield, and I would like to be able to control the arduino with a windows form app, but thats besides the point for now at least. Currently, I am using putty and the commands Telnet Localhost 6571. However, I would like to avoid doing that and I was wondering if anybody new how to communicate with the arduino from port 22 at the yun's IP, rather than connecting to the yun and then to the remote local machine. That or I am missing something entirely!

This is the code I am using to try and access the console port of the Leonardo:

```
namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            //connect to arduino
            ConnectionInfo ConnNfo = new ConnectionInfo("10.1.1.211", 22, "root", new AuthenticationMethod[] { new PasswordAuthenticationMethod("root", "123456789") });
            using (var sshclient = new SshClient(ConnNfo))
            {
                sshclient.Connect();
                //connect to console port of arduino
                TcpClient tcp = new TcpClient("localhost", 5671);
                sshclient.Disconnect();
            }
            Console.ReadKey();
        }
    }
}

```

Thank you

# Answer
The console port is only listening on 127.0.0.1 (for security), so only the Yun itself can connect to the console.

You can weaken security and open the port up to the entire local network by editing the file `/usr/lib/python2.7/bridge/console.py` and change the value `127.0.0.1` to `0.0.0.0`.

Any machine on your local network will then be able to connect directly to port 6571.
> 1 votes

---
Tags: arduino-yun, web-server, ide, linux
---


# Question
Title: Default sketch working but arduino is not recognizing
I have an arduino UNO and when I connected the device through the USB to the PC (with windows 7 64 bit),

The default blinking sketch, which comes shipped with it, is working,

but the device recognition sound is not playing.

and the device driver installation dialog never appeared and no arduino entry in the device manager.

And when I tried to upload a successfully compiled sketch from the ide 1.8.4 ,

It just says, 'problem uploading to board' More verbosely, **' avrdude: can't open device""\\.\COM1": the system cannot find the file specified'**

The device is getting power and running the sketch, But device is not recognized, maybe it is connected charge only, can I install the drivers manually?

Thanks in advance for any help.

# Answer
Hahaha! I figured it out! The USB connector on the board's side was loose connected! It didn't felt like more pressable & when I pressed it enough, it firmly fitted.

When it loose connected, the board connects power only.

The drivers were installed automatically & it showed under COM6. I've got sketches running in no time. I' ve tried a lot of knight rider patterns with a bunch of RGB LEDs then ;-)

Thank you @Majenko and the arduino stack exchage for your kind replies.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How do I connect an Adafruit headphone jack to an Arduino 101?
I just purchased Adafruit headphone jack and I want to know how to connect it to an Arduino 101. I'm trying to use a breadboard to play a sample tone melody from the Arduino libraries, which I want to hear with my iPhone headphones.

I have been looking online for instructions on how to do this, but found nothing. Please advise.

Thank you!

# Answer
First you need to confirm that the socket will actually work with your headphones. Make sure that the ground connection of the headphones (either the sleeve or the ring right next to the sleeve, depending on the type of headphones) is serviced by a connection.

Second you need to wire one or both of the tip and the first ring to the Arduino's output that you are using to generate audio. This should be done through a capacitor to block the DC voltage and only pass the AC waveform.

simulate this circuit – Schematic created using CircuitLab

Ideally, though, you should first pass the signal through a small headphone amplifier otherwise you risk drawing too much current out of the Arduino's GPIO pin.
> 1 votes

---
Tags: audio
---


# Question
Title: Arduino Nano + RFID RC522 + Ethernet shield W5100
I have this Arduino Nano, Ethernet shield W5100 and RC522 as card reader. They are sharing pins D13, D12, D11, D10 is SS pin for W5100 D8 is SS pin for RC522. Problem is with pin D12, like it doesn't share it.

For example if I unplug D12 from W5100 RC522 reader works, if I wire it back it doesn't work anymore. W5100 works no matter if RC522 is wired or not, so problem would be somehow with pin D12.

Does anybody have some ideas, what I'm doing wrong right here?

# Answer
> 3 votes
I had almost exactly this situation with one of my projects.

The problem is that some Serial Peripheral Interface (SPI) devices don't properly put the MISO pin into high-impedance when SS is pulled high. I eventually resolved this by placing a tri-state buffer in the MISO line for each of the SPI devices.

I used a 74HC125 (4-channel tri-state buffer).

This is the page on Better SPI Bus Design in 3 steps that finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).

---
Tags: arduino-nano, spi
---


title: Coding for a stop button

text:
# Question
Title: Coding for a stop button
I'll like to code for a game, and it'll come with a stop option that allows the player to exit/restart the game.

How should I code for that stop button? Do I put it in a separate while loop under the void loop?

# Answer
One of the easiest ways to restart your game is to use the inbuilt reset line. The Arduino Uno/Due/M0/101 has a physical reset button next to the USB connector. For some of the other baords like the Arduino Mega, it is closer to the chip in the middle of the board.

The reset line is held high by a pull up resistor. This button shorts the reset pin to Gnd, resetting the microcontroller.

Once reset, the microcontroller starts up again as if it has just been powered on. This has the advantage of saving on adding code to handle the game being reset.
> 2 votes

# Answer
There are lots of possible approaches. One possibility would be to set up your code something like this:

```
enum { STOPPED, PLAYING } flag;

void setup() {
  // setup stuff ...
  flag = STOPPED;
}

void loop() {
  while (flag == STOPPED)
  {
    // wait for start button
    if (start button pressed)
    {
      // initialise the game ...
      flag = PLAYING;
    }
  }

  while (flag == PLAYING)
  {
    // play the game
    if (stop button pressed)
    {
      flag = STOPPED;
    }
  }
}

```
> 1 votes

# Answer
If you code your loop without delay() or busy loops then it is pretty easy:

```
void loop(){

    if(DigitalRead(RESET_BUTTON)){
       // Reinitialize game state

    }

    //rest of game logic.

}

```
> 0 votes

---
Tags: programming
---


title: Transfer byte-buffer with ENC28J60

text:
# Question
Title: Transfer byte-buffer with ENC28J60
How do I transfer a series of byte\[256\]-buffers to a server with an ENC28J60 Ethernet adapter? I get blocks of `uint8_t` from an Arducam camera module and I'd like to transfer them to a host. Does somebody have an idea how to solve that? I asked a previous question regarding that topic but now new issues arrived.

This is how the array is filled:

```
uint8_t temp = 0, temp_last = 0;
byte buf[256];
length = myCAM.read_fifo_length();
while (length--) {
  temp_last = temp;
  temp =  SPI.transfer(0x00);
  if ((temp == 0xD9) && (temp_last == 0xFF)) {
    buf[i++] = temp;
    is_header = false;
    i = 0;
  }
  if (is_header == true) {
    //Write image data to buffer if not full
    if (i < 256)
      buf[i++] = temp;
    else {
      i = 0;
      buf[i++] = temp;
    }
  }
}

```

# Answer
> 0 votes
Assuming you are using the EtherCard library you can send a UDP packet with:

```
ether.sendUdp(packet_data, length, srcPort, hisip, dstPort );

```

Assuming you have already set up your source port and have the destination IP address and port in `hisip` and `dstPort`.

The prototype for the function is:

```
void sendUdp (char *data,uint8_t len,uint16_t sport, uint8_t *dip, uint16_t dport);

```

The example `udpClientSendOnly.ino` with the library shows you UDP sending in action.

---
Tags: arduino-uno, ethernet, web-server, data, buffer
---