# Question
Title: Managing timer intervals using millis at random intervals
I am doing a project which needs to meet the following specifications.

> On receiving an SMS arduino will start switching 1st relay on after some time duration(say 30 Seconds) relay 1 will be turned off and it will now turn on 2nd relay for (say 20seconds) so on 1\>2\>3\>4.

The problem im facing is managing the time intervals between the switching process,i did think of using millis() i.e **(currentMillis-previousMillisx\>Intervalx)** as in blinkWithoutDelay ,how ever this will work only once as i dont not know when will the next SMS come to the system ,if the user decides to send the message after 1hour currentMillis-previousMillisx will always return true so i cannot keep the motor on for (Say 30 seconds) and same will happen with all 4 cases.

If there is any alternative logic for this problem please suggest me or can i just add RTC for my project to manage time easily

Thank You

# Answer
> 2 votes
Well, you need a sort of tracking for your active relay, don't you? So you just have to reset that tracking variable and the previousMillis variables and you are done.

Some code (note: untested and moreover I don't know how you are receiving the SMS)

```
// The intervals for the different relays
const byte Intervals[] = {30, 20, 10, 5};

// The current state. 0 means relay 1 on,
// 1 means relay 2 on, 2->3 and 3->4, while
// 4 means no relay activated
byte currentState = 4;

unsigned long previousMillis;

void loop()
{
    if (received_sms)
    {
        currentState = 0;
        previousMillis = millis();
        digitalWrite(RELAY1, HIGH);
        // Maybe turn off all the other relays?
    }

    if (currentState < 4)
    { // Active state: check if we should advance
        unsigned long currentInterval = ((unsigned long)Intervals[currentState])*1000;
        while ((millis() - previousMillis) >= currentInterval)
        { // Advance to the next step
            switch(currentState)
            {
                case 0: // Advance from state 0 to 1
                    digitalWrite(RELAY1, LOW);
                    digitalWrite(RELAY2, HIGH);
                    // Maybe turn off all the other relays?
                    previousMillis += currentInterval;
                    currentState = 1;
                    break;
                ...
                // cases 1, 2, 3
                ...
                default:
                    // It should never reach this
                    previousMillis = millis();
                    currentState = 4;
                    break;
            }
        }

    }
}

```

# Answer
> 1 votes
I do not really understand your problem. More specifically, “currentMillis-previousMillisx will always return true” does not make sense, as it is not a boolean expression (it's `unsigned long`).

Anyway, the technique shown in blinkWithoutDelay is the way to go. Here is my (untested) version:

```
const int relay_count = 4;  // we have 4 relays
const int relay_pins[relay_count] = {2, 3, 4, 5};
const unsigned long durations[relay_count] = {30000, 20000, 15000, 10000};
bool sms_received();  // you implement this one

void loop()
{
    static int current_relay = -1;  // meaning: no active relay
    static unsigned long last_switch;
    unsigned long now = millis();

    // If no relay is active, wait for an SMS.
    if (current_relay == -1) {
        if (sms_received()) {
            // Switch on first relay.
            current_relay = 0;
            digitalWrite(relay_pins[current_relay], HIGH);
            last_switch = now;
        }
    }

    // Otherwise, switch relays when it is time to do so.
    else if (now - last_switch >= durations[current_relay]) {
        digitalWrite(relay_pins[current_relay], LOW);
        if (++current_relay == relay_count) {
            current_relay = -1;  // no active relay
        } else {
            digitalWrite(relay_pins[current_relay], HIGH);
            last_switch = now;
        }
    }
}

```

BTW, you did not specify what should happen if you receive an SMS while one of the relays is active. I assume the SMS are only acknowledged when no relay is active. Otherwise you would have to change the code.

# Answer
> -1 votes
You could use timer interrupts. I've (successfully) used the TimerOne library. There are countless other libraries that allow you to use timer interrupts easily. "Start" the timer when you receive the SMS message. You could use a pair of boolean flags to keep track of the two relays with one timer.

---
Tags: arduino-uno, timers, rtc, millis
---


title: 3-wire strain gauge - HX711 Issue

text:
# Question
Title: 3-wire strain gauge - HX711 Issue
I have two, three-wire load sensors (https://cdn.sparkfun.com//assets/parts/4/5/9/5/10245-01.jpg) hooked up in a half wheatstone bridge (I think), with two 1K resistors. Using a multimeter, I am reading small voltage changes when applying pressure to either strain gauge, when measured on between the pins A+ and A- on the HX711 ADC amp, however my Arduino serial output shows all 0's when using a variety of code examples (for example, this one: http://www.dfrobot.com/wiki/index.php/Weight\_Sensor\_Module\_V1#Sample\_code).

My concern is that my circuit is not setup correctly as I am fairly novice, however everything I have researched about wheatstone bridges, and half wheatstone bridges seems fairly straightforward, and seems to match my circuit. Any guidance/advice on the attached breadboard circuit diagram would be extremely helpful.

# Answer
In your diagram, the fixed 1KΩ resistors both tie to +5V at one set of ends, and their other ends tie to A+ and A-. The strain gauges are from A+ to ground and A- to ground.

In a typical scale, where several strain gauges are similarly loaded, that topology will produce about zero volts between A+ and A-. By contrast, the following topology (from: blog.l3l4.com) produces higher voltages for higher loading. (Diagram uses S+, S- rather than A+, A-)

(I realize your question shows some voltage changes when sensors are separately loaded, so this answer might not be relevant to your current problem.)
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: RF24 Stalls Arduino Program with powerDown
I have an ATtiny85 and an Arduino Uno both using NRF24L01 chips to communicate with one another. The ATtiny85 is powered by a CR2032 coin cell. I am using tmrh20's fork of the RF24 library which can be found here. Here's the problem I'm encountering:

Under the current code posted, the Uno will receive about 80 packets of data (80 packets times 2 seconds per packet is about 160 seconds of time) before the ATtiny will simply stop sending, and the Uno receives no more data. I can tell that it's the ATtiny, because I've got a DMM hooked up to it. Normally, my DMM tells me that the ATtiny is drawing less than 0.005mA of current, but at the instance of the stall the DMM reads approximately 1.4 mA of current draw, which makes sense because under normal conditions with no sleep the ATtiny draws about 1mA, and the radio not in power down mode and not transmitting draws 0.4mA.

I've spent quite some time trying everything from setting the clock speed to a different value (it's at 1MHz) to changing the power amplifier value. The only thing I've tried that makes an impact is getting rid of the powerUp and powerDown function calls. Once these are removed everything works perfectly transmission-wise, except the only issue is that the whole system is drawing 0.4mA constantly, which is too much.

I don't think the coin cell is a problem considering the system works when the powerUp and powerDown calls are removed. Here's my code:

Reciever:

```
#define CE_PIN 7
#define CSN_PIN 8

#include <SPI.h>
#include "RF24.h"

RF24 radio(CE_PIN, CSN_PIN);

byte address[11] = "SimpleNode";
unsigned long payload = 0;

void setup() {
  while (!Serial);
  Serial.begin(115200);
  radio.begin(); // Start up the radio
  radio.setAutoAck(1); // Ensure autoACK is enabled
  radio.setRetries(15,15); // Max delay between retries & number of retries
  radio.openReadingPipe(1, address); // Write to device address 'SimpleNode'
  radio.startListening();
  Serial.println("Did Setup");

}

long counter = 0;

void loop(void){
  if (radio.available()) {

    radio.read( &payload, sizeof(unsigned long) );
    if(payload != 0){
        Serial.print("Got Payload ");
        Serial.print(payload);
        Serial.print(" - ");
        Serial.println(counter);
        counter++;
    }
  }

}

```

Transmitter:

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

const int sleepSecs = 2;

//Radio
#define CE_PIN 3
#define CSN_PIN 3 //Since we are using 3 pin configuration we will use same pin for both CE and CSN
#include "RF24.h"
RF24 radio(CE_PIN, CSN_PIN);
byte address[11] = "SimpleNode";
unsigned long payload = 0;

void setup() {
  //Setup radio
  radio.begin(); // Start up the radio
  radio.setAutoAck(1); // Ensure autoACK is enabled
  radio.setRetries(15,15); // Max delay between retries & number of retries
  //RF24_PA_MIN, RF24_PA_LOW, RF24_PA_HIGH and RF24_PA_MAX
  radio.setPALevel(RF24_PA_HIGH);
  radio.openWritingPipe(address); // Write to device address 'SimpleNode'

  //Setup sleep
  setup_watchdog(6);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); //Power down everything, wake up from WDT
  sleep_enable();
}

volatile int watchdog_counter = 0;

ISR(WDT_vect) {
  watchdog_counter++;
}

void loop() {
  sleep_mode(); //Go to sleep!

  if(watchdog_counter >= sleepSecs)
  {
    ADCSRA |= (1<<ADEN);
    radio.powerUp();
    watchdog_counter = 0;

    payload = 123456;
    radio.write(&payload, sizeof(unsigned long) ); //Send data to 'Receiver' every second

    radio.powerDown();
    ADCSRA &= ~(1<<ADEN); //Disable ADC, saves ~230uA
  }
}

//Sets the watchdog timer to wake us up, but not reset
//0=16ms, 1=32ms, 2=64ms, 3=128ms, 4=250ms, 5=500ms
//6=1sec, 7=2sec, 8=4sec, 9=8sec
//From: http://interface.khm.de/index.php/lab/experiments/sleep_watchdog_battery/
void setup_watchdog(int timerPrescaler) {

  if (timerPrescaler > 9 ) timerPrescaler = 9; //Limit incoming amount to legal settings

  byte bb = timerPrescaler & 7;
  if (timerPrescaler > 7) bb |= (1<<5); //Set the special 5th bit if necessary

  //This order of commands is important and cannot be combined
  MCUSR &= ~(1<<WDRF); //Clear the watch dog reset
  WDTCR |= (1<<WDCE) | (1<<WDE); //Set WD_change enable, set WD enable
  WDTCR = bb; //Set new watchdog timeout value
  WDTCR |= _BV(WDIE); //Set the interrupt enable, this will keep unit from resetting after each int
}

```

# Answer
A delay after the `powerUp()` made the program work for longer, but it still stalled. More delays after `write()` only exacerbated the issue. The only thing that I've done to get this to work is to put the sending code in the watchdog ISR itself. However, this is limited to only around 4 seconds max per sent packet because this is the watchdog's max value, but that's OK for my application.

This leads me to believe that somehow the watchdog is interfering with sending, so possibly disabling it and reenabling after sending could have some effect if anyone else is having this problem.
> 0 votes

# Answer
After looking at the RF24 header file, I suggest you call `radio.stopListening()` right before you call `write()`. Also add a delay of 5 ms after `write()`. It would be nice to know the exact point at which the program got stuck; add `digitalWrite(13, HIGH)` inside the IF block, after `powerDown()` and again outside the block, immediately after `sleep_mode()`, but with a LOW argument instead, so you can know if the problem is that the AVR stops waking up at some point or if its the radio methods that is blocking, for some reason.
> 1 votes

---
Tags: attiny, nrf24l01+, wireless
---


# Question
Title: How to alter joystick values with Arduino Uno?
I'm trying to use an Arduino Uno to read values from a 2-axis joystick analogue input, and alter these values. Rather than the true joystick values, I arithmetically convert the values at neutral to range between 0 - 5, with 'neutral', i.e. when the joystick isn't being pushed, being at roughly 2.5 for each axis. These joystick values currently output to a live text file, to be graphed in real-time. One function I'm trying to implement is that when the joystick value is greater or less than a defined value (e.g. in the code, greater than 4.55, or less than 0.5) that the Arduino sets that point to be the new 'neutral' position (i.e. 2.5), however my code at the moment isn't working and I'm not sure how to go about attempting this.

Any insight would be most appreciated!

Cheers

```
const int buttonPin = 2;
const int successPin = 13;

int buttonState = 0;

void setup()
{
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
pinMode (buttonPin, INPUT);
pinMode (successPin, OUTPUT);
while (digitalRead(buttonPin) == LOW) {};
}

void loop () {

int sensorValueY = analogRead(A0);
int sensorValueX = analogRead(A1);

//arithmetic operation that maps output values from 0 - 5 instead of 0 - 1023
float voltageX = sensorValueX * (5.0 / 1023.0);
float voltageY = sensorValueY * (5.0 / 1023.0);
Serial.print(voltageX);
Serial.print(" , ");
Serial.print(voltageY);

if (voltageX >= 4.55) {
  voltageX == 2.5;
  successPin==HIGH;
  delay(1);
  successPin==LOW;
}

if (voltageX <= 0.5) {
  voltageX ==2.5;
  successPin==HIGH;
  delay(1);
  successPin==LOW;
}

if (voltageY >=4.55) {
  voltageY == 2.5;
  successPin==HIGH;
  delay(1);
  successPin==LOW;
}

if (voltageY <= 0.5) {
  voltageY ==2.5;
  successPin==HIGH;
  delay(1);
  successPin==LOW;
}
Serial.println();

}

```

# Answer
```
if (voltageX >= 4.55) {
  voltageX == 2.5;
  successPin==HIGH;

```

The last two lines (and all similar ones later) are wrong. `==` is for **comparing**, `=` is for **assigning**. So change it to:

```
if (voltageX >= 4.55) {
  voltageX = 2.5;
  successPin = HIGH;

```

You did that in a lot of places, so fix that up and get back to us.

---

```
const int successPin = 13;
...
  successPin = HIGH;

```

Assuming you fix the compare to an assign you will get an error message here. You define successPin as 13, and then try to change it to 1 (which is what HIGH is defined as). Do you mean, to write to that pin? Like this?

```
digitalWrite (successPin, HIGH);

```

You will need to change all those as well. And if you are hoping to see an LED on the pin flash, 1 ms is quite a small interval.
> 1 votes

---
Tags: arduino-uno, serial, c++
---


title: RFID tag "location identification"

text:
# Question
Title: RFID tag "location identification"
Can an RFID tag be used to identify a room? For example, I walk into a room, and the RFID receiver tells me that I am in say, the living room. Would it be possible for a tag to ping back the signal from a distance of 10ft? Or is there a similar technology like RFID that can extend to a much greater range?

# Answer
> 0 votes
There are newer long range RFID solutions. You can do a google search on "Ultra Long-Range UHF Wireless RFID Sensors" for more information, but almost all of these systems are still proprietary (i.e. I'm not aware of any hobbyist breakout-boards based around UHF tags yet).

The Disney MagicBands are an exact use-case of your question: Their magic bands use a combination of 13MHz RFID tags, and a new UHF active tag (it requires a small battery). They use them to collect data on how people flow through their Walt Disney World facility. What bathrooms see the most activity, and when, for example. There is actually a pretty decent amount of information available about the technology used in the Disney Magicbands if you're curious about the technology.

---
Tags: rfid
---


# Question
Title: Use ESP8266 as WiFi client connected to Arduino Pro Mini
So i'm trying to use the PubSubClient Library on my arduino mini pro, but I'm connecting to the internet via wifi using an ESP8266.

Using a mini means I have to use software serial to connect to the ESP, but I've ran into a problem. I can't find anywhere such as `ESPWiFiClient` to use with the examples from the PubSubClient library where they use `EthernetClient`.

Is there any available libraries that can emulate EthernetClient with an ESP module over software serial?

# Answer
Ditch the Pro Mini. Upload your Arduino code to the ESP directly. There's a GitHub repo with the details. ESP for Arduino IDE has a ton of libraries. I'm sure you'll find it there.

But if you're bent on using the Pro Mini, you'll have to use AT commands over serial to control it or flash a custom firmware into the ESP using Lua or something. And Pro Mini can use its hardware serial just like a Uno does.
> 1 votes

---
Tags: wifi, esp8266, softwareserial, arduino-pro-mini, software
---


title: Memory organisation of MIFARE 1K

text:
# Question
Title: Memory organisation of MIFARE 1K
I'm trying to use a MIFARE 1K RFID card with RC522 RFID reader/writer for my college project. I'm trying to understand about memory organization of MIFARE 1K.A documentation() that supplied with a RFID Arduino library() says like this. I will very appreciate if someone explain me this portion clearly.

> The MIFARE Classic 1K offers 1024 bytes of data storage, split into 16 sectors; each sector is protected by two different keys, called A and B. Each key can be programmed to allow operations such as reading, writing, increasing valueblocks, etc. MIFARE Classic 4K offers 4096 bytes split into forty sectors, of which 32 are same size as in the 1K with eight more that are quadruple size sectors. MIFARE Classic mini offers 320 bytes split into five sectors. For each of these card types, **16 bytes per sector** are reserved for the keys and access conditions and can not normally be used for user data. Also, the very first 16 bytes contain the serial number of the card and certain other manufacturer data and are read only. That brings the net storage capacity of these cards down to 752 bytes for MIFARE Classic 1k, 3440 bytes for MIFARE Classic 4k, and 224 bytes for Mini. It uses an NXP proprietary security protocol (Crypto-1) for authentication and ciphering.

Accordind to above quote,

> For each of these card types, **16 bytes per sector** are reserved for the keys and access conditions and can not normally be used for user data. Blockquote

Explain how to divide 1024 bytes like this.It has 16 sectors.So,total memory should be 16\*16=256 bytes.This is impossible. Please explain this.

# Answer
You're reading (and doing your sums) backwards.

You have 1024 bytes of data space.

That data space is split into 16 sectors, so 1024 / 16 = 64 bytes per sector.

Each sector has 16 bytes reserved for keys etc, so each sector has 64 - 16 = 48 bytes of user data space.

48 bytes of user data space per sector multiplied by 16 sectors is 768 bytes.

Incidentally 1024 - 768 = 256, which is what you were calculating before. What you calculated was the amount of the 1024 bytes that is reserved *in total* for the keys and access controls.
> 5 votes

# Answer
Divide 1024 bytes into 16 sectors -

```
1024 bytes / 16 sectors = 64 bytes per sector

```

The first 16 bytes of each sector are used for 'management' and thus reserved. This leaves -

```
64 - 16 = 48 bytes (per sector) for general storage

```
> 2 votes

# Answer
There is also an excellent graphic of the various mifare card layouts, that someone has put together: https://upload.wikimedia.org/wikipedia/commons/thumb/3/39/MiFare\_Byte\_Layout.png/220px-MiFare\_Byte\_Layout.png
> 0 votes

---
Tags: rfid
---


title: sketch uploading give error?

text:
# Question
Title: sketch uploading give error?
```
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x20
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x20

```

# Answer
> 0 votes
This Instructables post has a list of potential causes for this error. Is this a new board? What board are you using? Is it a genuine Arduino board or a clone? Have you been able to upload to the board previously?

# Answer
> 0 votes
Have you changed the atmega328 chip? If you have the new one may not have a bootloader or it may have one for a different board. Select every board option. Duemillemova maybe? If you still have no luck, you might have over written your bootloader. Try burning the bootloader again. Instructables shows you how.

---
Tags: arduino-uno
---


# Question
Title: Error when trying to write analog and digital signals from different pins (Arduino UNO)
I'm using the Arduino UNO and started noticing some funny behavior when I was trying a few basic projects. Specifically when trying to write an analog signal through one of the PWM pins, then a digital signal through another.

Using some LED's connected to a few different permutations of pins 8-13, I found that when I have an analog output set for one of the pins (in this case 9, 10, or 11 as they're the only one's of the set capable of PWM) and then try to output a digital signal from a different pin to another LED the digital signal seems much weaker. That is, the LED shines very very dim.

The pins 2-7 work fine. Does the behavior described above indicate anything wrong with the arduino? are those pins potentially damaged, or is there something I'm not understanding here?

My code:

```
void setup()
{}

void loop()
{
   analogWrite(9, 255);
   delay(1000);
   analogWrite(9, 0);
   delay(2000);
   digitalWrite(8, HIGH);
   delay(1000);
   digitalWrite(8, LOW);
   delay(2000);
}

```

# Answer
I tested your code and it does indeed behave the way you said. But that is because you have not declared any pins as output.

`analogWrite` does this for you automatically in the library, however `digitalWrite` does not. This is because sending a digital pin `HIGH` when it is `INPUT` turns on the internal pull-up resistors. These are around 50k. Thus you will only see very dim output on the LED. Add this line to `setup`:

```
 pinMode (8, OUTPUT);

```

(And preferably pin 9 as well, just in case you decide to change to digital writes later).
> 4 votes

# Answer
The pin groups your describe are on different ports of the chip which have different current sourcing ratings. I'm sure you'll find an even brightness using similar LEDs on all pins and using a 1K res in series with each led to limit current. Also , to ensure the sourcing transistors are ON within the chip, be sure to declare the pins as output when required.
> 0 votes

---
Tags: arduino-uno, pins
---


# Question
Title: Connection bluetooth master and slave with Android
I send a date from my android to arduino without problem, but also i want send date from arduino to android later of received the date from android.

I have time trying it, but i can not yet, help me. My codec of arduino

```
char enter;
#include <SoftwareSerial.h>
SoftwareSerial conect(10,11);

void setup()
{
 pinMode(8,OUTPUT);
 conect.begin(9600);
 digitalWrite(8,LOW);
}

void loop()
{
 if(conect.available()>0)
  {
   enter=conect.read();
   if(entrada=='1')
   {
    digitalWrite(8,HIGH);
    conect.print("1");
   }
 }
}

```

And in the side from android this is my handler for drive the the date that arrive.

```
 Handler mhandler=new Handler(){
    @Override
    public void handleMessage(Message msg)
    {
        super.handleMessage(msg);
        switch (msg.what)
        {
            case CONECTADO:
                //ManejarDatos msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                break;
            case MENSAJELEYENDO:
                byte[] readBuf = (byte[])msg.obj;
                String string = new String(readBuf,0,msg.arg1);
                Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
                break;
        }
    }
};

```

And on my class for read and write i have this

```
private class ManejarDatos extends Thread
{
    private final OutputStream salidadatos;
    private final BluetoothSocket sockk;
    private final InputStream entradadatos;
    public ManejarDatos(BluetoothSocket socke1)
    {
        sockk=socke1;
        OutputStream temporalsalida=null;
        InputStream temporalentrada=null;
        try
        {
            temporalentrada=socke1.getInputStream();
            temporalsalida=socke1.getOutputStream();
        }catch (IOException e){}
        salidadatos=temporalsalida;
        entradadatos=temporalentrada;
    }
    public void run()
    {
        byte[] espera;
        int esperaalmacen;
        while (true) {
            try {
                espera=new byte [1024];
                esperaalmacen=entradadatos.read(espera);
                mhandler.obtainMessage(MENSAJELEYENDO,esperaalmacen,-1,espera)
                        .sendToTarget();
            }catch (IOException e){break;}
        }
    }
    public void escribe(byte[] bytes)
    {
        try {
            salidadatos.write(bytes);
            //handler.obtainMessage(MENSAJE_SALIDA,-1,-1,bytes).sendToTarget();
        }catch (IOException e){
            //Log.e(TAG, "....Error al enviar dato" + e.getMessage() + "...");
        }
    }
    public void cancel()
    {
        try{
            sockk.close();
        }catch (IOException e){}
    }

}

```

When i push button, send a date to arduino, here my codec of button(i send 1 for bluetooth)

```
        Enviar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String salida="1";
            msjre.escribe(salida.getBytes());
        }
    });

```

# Answer
> 0 votes
What is `entrada`? Replace `entrada` with `enter` in your arduino code and try again. Also try this `run()` code instead:

```
public void run()
{
    byte[] espera = new byte[1024];
    int esperaalmacen;
    while (true) {
        try {
            esperaalmacen=entradadatos.read(espera);
            mhandler.obtainMessage(MENSAJELEYENDO,esperaalmacen,-1,espera)
                    .sendToTarget();
        }catch (IOException e){break;}
    }
}

```

# Answer
> 0 votes
First try

if(conect.available()\>0) { enter=conect.read(); if(1) { digitalWrite(8,HIGH); conect.print("1"); } } }

If that works, think about what entreda is and that exactly you're trying to do there.

---
Tags: arduino-uno, bluetooth, softwareserial, hc-05
---


# Question
Title: analogRead function not working in MATLAB
I am new to Arduino and I am trying to control it through MATLAB. I have downloaded the arduino IO package and installed it.I am using MATLAB 2014a.I have a LED and I change its brightness by changing the PWM voltage as follows :

```
a=arduino('COM3');
brightness_step = (5-0)/20;
   for i = 1:20
      writePWMVoltage(a, 11, i*brightness_step);
      val=a.analogRead(0);
      display(val)
      pause(0.1);
   end

   for i = 1:20
      writePWMVoltage(a, 11, 5-i*brightness_step);
      val=a.analogRead(0);
      display(val)
      pause(0.1);
   end
clear a

```

Everything works great except for the analogRead part which throws the following error : **No appropriate method, property, or field analogRead for class arduino.**

What am I doing wrong?

# Answer
> 1 votes
That function is part of legacy code.

> NOTE: This solution (formerly known as "Arduino IO Package") is no longer supported. It is recommended that you use Arduino support packages that are developed and supported by MathWorks:
>
> Use this legacy support only if one of the following is true:
>
> **\- You are using MATLAB R2013b or earlier (but not earlier than R2011a).**

You are using 2014a, so its probably the reason `analogRead` isn't working. Get the more recent package and use this function instead:

# Answer
> 0 votes
Sorry, I don't have MatLab to verify this but try this in the two places you call a.analogRead(0);

```
val=analogRead(a,0);

```

This is based on what appears to be the classdef for the arduino object.

---
Tags: arduino-uno, matlab
---


# Question
Title: Arduino non-blocking software PWM LED fader not working
I am trying to write a simple software PWM to fade some LEDs because I don't have enough PWM I/O Ports.

The code evaluates how long you want the LED to fade, and breaks it down into a number of steps. During each step, it will evaluate the period the LED should be on.

I have the following code:

```
class Led{
  public:
    Led(int pin);
    void setup();
    // void updateFadeDirection();
    void updateBrightness();

  private:
    int _pin;
    unsigned long _currentTime;
    unsigned long _startTime; // Very beginning of fade period
    unsigned long _fadePeriod; // How long to fade on and off
    int _fadeStep; // current fade step i.e. 1/255
    int _fadeSteps; // How many steps to take until full brightness
    int _fadeDirection; // low to high or high to low?
    float _T_on; // Amount of time to turn LED on
    float _T_fadeStep; // Amount of time per step increment of brightness
    unsigned long _stepTime; // Start of current step period

    bool _evaluated;
};

Led::Led(int pin){
  _pin = pin;
}

void Led::setup(){
  pinMode(_pin, OUTPUT);
  _startTime = micros();
  _fadePeriod = 2*1000000; //microseconds(us)
  _fadeStep = 50; // start at 0 brightness here
  _fadeSteps = 100;
  _fadeDirection = 1;

  _T_fadeStep = _fadePeriod/_fadeSteps; // i.e. 2000000us/100steps = 20000us/step of brightness
  _T_on = (_fadeStep/_fadeSteps) * _T_fadeStep; // i.e. 20/100 * 20000us = 4000us on

  _stepTime = micros();
  delayMicroseconds(200);
}

void Led::updateBrightness(){
  _currentTime = micros();

  if(_currentTime - _startTime < _fadePeriod){
    if (_currentTime - _stepTime > _T_on){
      digitalWrite(_pin, LOW);
    } else {
      digitalWrite(_pin, HIGH);
    }

    if(_currentTime - _stepTime >= _T_fadeStep){
      // _fadeStep++;
      _stepTime = _currentTime;
      _T_on = (_fadeStep/_fadeSteps) * _T_fadeStep;
    }
  }
  else{
    digitalWrite(_pin, HIGH);
  }
}

Led LED0(0);

void setup() {
  LED0.setup();
}

void loop() {
  LED0.updateBrightness();
}

```

The current behaviour when powered on is the single LED will be turned off, then will turn on after 2 seconds.

In particular, it never seems to enter the `else` part

```
  if (_currentTime - _stepTime > _T_on){
    digitalWrite(_pin, LOW);
  } else {
    digitalWrite(_pin, HIGH);
  }

```

The problem is that the LED will never hit `HIGH` until the outer `else` is triggered.

I believe it has to do with `_T_on` being an `int` and the timestamps being `unsigned long` and me not casting it.

The expected behaviour is 2 seconds of dimmed (50%) light, and then a full 100% when it hits the outer `else`.

# Answer
As @ott-- has mentioned, because of the `int` datatype, `_fadeStep`/`_fadeSteps` will always evaluate to 0.

Here's the updated code along with some timing tweaks:

```
float fadeSteps = 150; // How many steps to take until full brightness

class Led{
  public:
    Led(int pin, float fadeStep=0);
    void setup();
    // void updateFadeDirection();
    void updateBrightness();

  private:
    int _pin;
    unsigned long _currentTime;
    unsigned long _startTime; // Very beginning of fade period
    unsigned long _fadePeriod; // How long to fade on and off
    float _fadeStep; // current fade step i.e. 1/255
    int _fadeDirection; // low to high or high to low?
    unsigned long _T_on; // Amount of time to turn LED on
    unsigned long _T_fadeStep; // Amount of time per step increment of brightness
    unsigned long _stepTime; // Start of current step period

    bool _evaluated;
};

Led::Led(int pin, float fadeStep){
  _pin = pin;
  _fadeStep = fadeStep;
}

void Led::setup(){
  pinMode(_pin, OUTPUT);
  _startTime = micros();
  _fadePeriod = 2000000; //microseconds(us)
  _fadeDirection = 1;

  _T_fadeStep = _fadePeriod/2/fadeSteps; // i.e. 2000000us/100steps = 20000us/step of brightness
  _T_on = (_fadeStep/fadeSteps) * _T_fadeStep; // i.e. 20/100 * 20000us = 4000us on

  _stepTime = micros();
}

void Led::updateBrightness(){
  _currentTime = micros();
  if (_currentTime - _stepTime > _T_on){
    digitalWrite(_pin, LOW);
  } else {
    digitalWrite(_pin, HIGH);
  }

  if(_currentTime - _stepTime >= _T_fadeStep){
    _fadeStep += _fadeDirection;
    _stepTime = _currentTime;
    _T_on = (_fadeStep/fadeSteps) * _T_fadeStep;
  }

  if(_fadeStep >= fadeSteps-1) {
    _fadeDirection = -1;
  } else if(_fadeStep <= 1) {
    _fadeDirection = 1;
  }
}

Led LED0(0);
Led LED1(1,fadeSteps/5);
Led LED2(2,2*fadeSteps/5);
Led LED3(3,3*fadeSteps/5);
Led LED4(4,4*fadeSteps/5);

void setup() {
  LED0.setup();
  LED1.setup();
  LED2.setup();
  LED3.setup();
  LED4.setup();
}

void loop() {
  LED0.updateBrightness();
  LED1.updateBrightness();
  LED2.updateBrightness();
  LED3.updateBrightness();
  LED4.updateBrightness();
}

```

Some refactoring is needed to be more modular, but will fade (using software PWM) LEDs asynchronously on every digital OUT port on an attiny85. Can also set the starting brightness so that you can make an LED fading chaser.
> 1 votes

---
Tags: arduino-uno, led, pwm, attiny
---


title: expected ';' before '{' token error

text:
# Question
Title: expected ';' before '{' token error
I am trying to figure out what I did wrong in my sketch. In my void loop(), at the very bottom of the sketch, my if/else statement keeps compiling with the above error. Originally, it was an if/else if/else statement. I had the current else's an else if and the Update in my else. Someone had corrected me on it and i removed the code and made the proper changes and the error started. Now, just for the sake of my sanity I went ahead and put the ';' at the end of my else, which I know is wrong, just to see if it compiled, which it did. I ran the sketch and sure enough it broke the operation. I cannot figure out what it is looking for. Any help would be appreciated.

```
    //ASHPD Barrel Version 4.0.2 (adding pulse) Created By Gixxerfool 01.11.2016

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

// Pattern types supported:
enum  pattern {NONE, CHASE, PULSE};

#define orange 255,128,0
#define blue 0,0,255

char targetColor = '0,0,255';

// NeoPattern Class
class NeoPatterns : public Adafruit_NeoPixel
{
  public:

    // Member Variables:
    pattern  ActivePattern;  // which pattern is running

    unsigned long Interval;   // milliseconds between updates
    unsigned long lastUpdate; // last update of position

    uint32_t Color1;  // What color is used
    uint16_t TotalSteps;  // total number of steps in the pattern
    uint16_t Index;  // current step within the pattern

   // Constructor
    NeoPatterns(uint16_t pixels, uint8_t pin, uint8_t type)
    :Adafruit_NeoPixel(pixels, pin, type)

{

}
    // Update the pattern
    void Update()
    {
      if ((millis() - lastUpdate) > Interval) // time to update
      {
        lastUpdate = millis();
        switch (ActivePattern)
        {
          case CHASE:
            ChaseUpdate();
            break;
           // case PULSE:
            //PulseUpdate();
            //break;
          default:
            break;
        }
      }
    }

    // Increment the Index and reset at the end
    void Increment()
    {
        Index++;
        if (Index >= TotalSteps)
        {
          Index = 0;
        }
      }

    // Calculate 50% dimmed version of a color (used by ChaseUpdate)
    uint32_t DimColor(uint32_t color)
    {
        // Shift R, G and B components one bit to the right
        uint32_t dimColor = Color(Red(color) >> 1, Green(color) >> 1, Blue(color) >> 1);
        return dimColor;
    }
    // Returns the Red component of a 32-bit color
    uint8_t Red(uint32_t color)
    {
        return (color >> 16) & 0xFF;
    }

    // Returns the Green component of a 32-bit color
    uint8_t Green(uint32_t color)
    {
        return (color >> 8) & 0xFF;
    }

    // Returns the Blue component of a 32-bit color
    uint8_t Blue(uint32_t color)
    {
        return color & 0xFF;
    }

    // Initialize for a CHASE

void Chase(uint32_t color1, uint8_t interval)
    {
        ActivePattern = CHASE;
        Interval = interval;
        TotalSteps = (numPixels());
        Color1 = color1;
        Index = 0;
    }

    // Update the Chase Pattern
    void ChaseUpdate()
    {
        for (int i = 0; i < numPixels() + 1; i++)
        {
            if (i == Index)  // Scan Pixel
            {
                 setPixelColor(i, Color1);
            }
            else // Fading tail
            {
                 setPixelColor(i, DimColor(getPixelColor(i)));
            }
        }
        show();
        Increment();
    }

//Initialize for a pulse
void Pulse(uint32_t color1, uint8_t interval)
    {
      ActivePattern = PULSE;
      Interval = interval;
      TotalSteps = 256;
      Color1 = color1;
      Index = 0;
    }

    //Update the Pulse
    void PulseUpdate()
   {
   for (int h = 0; h < 256; h++)
    {
    for (int i = 0; i < 126; i++)
     {
      for (int j = 0; j > -1; j--)
      {
      if (h == Index)
      {
      setPixelColor(i, Color1);
      }
      else
      {
      setPixelColor(j, Color1);
      }
    }
    show();
    Increment();
   }
  }
}

};
// Define some NeoPatterns

NeoPatterns Ring3(16, 4, NEO_GRB + NEO_KHZ800);
NeoPatterns Ring2(12, 1, NEO_GRB + NEO_KHZ800);
NeoPatterns Ring1(7, 0, NEO_GRB + NEO_KHZ800);

// Initialize everything and prepare to start

void setup()
{
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
#if defined (__AVR_ATtiny85__)
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
  // End of trinket special code

pinMode(2, INPUT); //Sets pin 2 as an input

  // Initialize all the pixels

  Ring1.begin();
  Ring2.begin();
  Ring3.begin();

  //Set all pixels to off

  Ring1.show();
  Ring2.show();
  Ring3.show();

  ring3Wipe(Ring3.Color(blue), 50); // Wipe ring 3 in blue once
  ring2Wipe(Ring2.Color(blue), 50); // wipe ring 2 in Blue once
  ring1FadeUpBlue(Ring1.Color(blue)); //Fade in ring1 once

  //Start the idle pattern
  //Name.PatternName(Name.Color(targetColor), Interval) Changing Interval will adjust the speed of the pattern
  Ring1.Pulse(Ring1.Color(blue), 500);
  Ring2.Chase(Ring2.Color(blue), 55);//keep the interval 15ms above ring3 for synchronicity
  Ring3.Chase(Ring3.Color(blue), 40);//keep the interval 15ms below ring2 for synchronicity

}
    void ring1FadeUpBlue(uint8_t wait)
    {
   for(int j = 0; j < 255; j++)
   {
      uint32_t color = Ring1.Color(0, 0, j );  // ramp up the blue only
      for(uint16_t i=0; i < Ring1.numPixels(); i++)
      {
         Ring1.setPixelColor(i, color);
      }
      delay(7);
      Ring1.show();
   }
}
//wipes the ring2 once in blue
void ring2Wipe(uint32_t c, uint8_t wait)
{
    for(uint16_t i=0; i < Ring2.numPixels(); i++)  //This for loop runs reverse to ring3 loop
   {
      Ring2.setPixelColor(i, c);
      Ring2.show();
      delay(wait);
   }
}

//wipes the ring3 once for the color blue
void ring3Wipe(uint32_t c, uint8_t wait)
{ //uint32_t and uint8_t are the colorWipe parameters c=color wait=#of ms between pixels. larger # slows the action
    for(uint16_t i=0; i < Ring3.numPixels(); i++)
   {
      Ring3.setPixelColor(i, c);
      Ring3.show();
      delay(wait);
   }
}

// Main loop
void loop()
{
  // Update the rings.
  Ring1.Update();
  Ring2.Update();
  Ring3.Update();

  // check for button press:
  if (digitalRead(2) == LOW) // Button is pressed
  {
    Ring3.Color1 = Ring3.Color(orange);//Change the target color to orange
    Ring2.Color1 = Ring2.Color(orange);
    Ring1.Color1 = Ring1.Color(orange);
  }
  else (digitalRead(2) == HIGH)//Kicks the color back to blue after the button is let go
  {
    Ring3.Color1 = Ring3.Color(blue);//Change the target color back to blue
    Ring2.Color1 = Ring2.Color(blue);
    Ring1.Color1 = Ring1.Color(blue);
  }
}

```

# Answer
> 1 votes
The if-else construct is incorrect.

It needs to be like this:

```
if (condition)
{
    //actions
} else {
    //other actions
}

```

Which reads: if the conditions are true, then do actions, otherwise do other actions.

OR it can be like like this

```
if (condition)
{
    //actions
} else {
    if (other condition){
    //other actions
   }
}

```

Which reads: if conditions are true, then do actions, otherwise, if other conditions are true, then do other actions. Note that in this structure, if neither conditions or "other conditions" are true, then we do nothing.

So if DigitalRead can **only** be HIGH or LOW, then you don't need condition that in the "else" statement. Your code can look like this:

```
 // check for button press:
  if (digitalRead(2) == LOW) // Button is pressed
  {
    Ring3.Color1 = Ring3.Color(orange);//Change the target color to orange
    Ring2.Color1 = Ring2.Color(orange);
    Ring1.Color1 = Ring1.Color(orange);
  }
  else
  {
    // digitalRead(2) must be HIGH if it's not LOW
    //Kicks the color back to blue after the button is let go
    Ring3.Color1 = Ring3.Color(blue);//Change the target color back to blue
    Ring2.Color1 = Ring2.Color(blue);
    Ring1.Color1 = Ring1.Color(blue);
  }

```

Only if digitalRead could return another value (e.g. 3, 100, 75 etc) then you would need the other conditions in your else clause, but the code would need to look like this:

```
 // check for button press:
  if (digitalRead(2) == LOW) // Button is pressed
  {
    Ring3.Color1 = Ring3.Color(orange);//Change the target color to orange
    Ring2.Color1 = Ring2.Color(orange);
    Ring1.Color1 = Ring1.Color(orange);
  }
  else
  {
    if (digitalRead(2) == HIGH)//Kicks the color back to blue after the button is let go
    {
      Ring3.Color1 = Ring3.Color(blue);//Change the target color back to blue
      Ring2.Color1 = Ring2.Color(blue);
      Ring1.Color1 = Ring1.Color(blue);
    }
  }

```

Note: you don't actually need the braces around the second "if" statement there, but it makes the structure more clear.

# Answer
> 0 votes
This makes no sense - you can't store 7 characters in the space of one character:

```
char targetColor = '0,0,255';

```

---

You're lacking an "if" here:

```
} else (digitalRead(2) == HIGH) { //Kicks the color back to blue ...

```

---

You have numerous sign mismatches in comparisons.

---
Tags: programming, arduino-ide
---


# Question
Title: Arduino Ethernet intermittently connects to server
Here is my code:

```
#include <SPI.h>
#include <OneWire.h>
#include <EthernetV2_0.h>
#include <EthernetClientV2_0.h>
#include <EthernetServerV2_0.h>
#include <EthernetUdpV2_0.h>
#include <math.h>
#include <Client.h>
#include <WString.h>
     #include <stdlib.h>
#include <OneWire.h>
#include <stdio.h>
#include <DhcpV2_0.h>
#include <DnsV2_0.h>

int whiteLevel;
int colorLevel;
int blueLevel;
int standardLightingPattern[3] = { 200, 160, 250 };
int twilightLightingPattern[3] = { 20, 50, 100 };
int nightTimeLightingPattern[3] = { 0, 10, 40 };
int morningLightingPattern[3] = { 50, 50, 100 };
int deepNightLightingPattern[3] = { 0, 20, 80 };
int feedingLightingPattern[3] = { 20, 20, 50 };
int i;
int j;
char *buildUrlParameter(float ph, float temp1, float temp2);

// Pin Delcarations
int temperaturePins[2] = { 30,31 };
int outletPins[] = { 22, 23, 24, 25, 26, 27 };
const int whiteLedString = 44;    // connected to LDD-700HW on white strand
const int colorLedString = 45;    // connected to LDD-1000HW on color strand
const int blueLedString = 46;     // connected to LDD-1000HW on royal blue     strand

// Sensor Variables
float temps[2];
String sensorstring = "";
boolean sensor_string_complete = false;
float pH;

// Variables for URL char buffer
char outBuf[100];
char charBuf[6];
char cnctPh[6];
char cnctTemp1[7];
char cnctTemp2[7];
char urlParameter[34];
char dest1[34];

//char serverIP[] = "74,125,224,80";
//char serverIP[] = "192.168.1.107";
//char serverIP[] = "www.arduino.cc";

// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(192,168,1,199);

// fill in your Domain Name Server address here:
IPAddress myDns(8,8,8,8);

// initialize the library instance:
EthernetClient client;

char server[] = "192.168.1.107";

unsigned long lastConnectionTime = 0;          // last time you connected to the server, in milliseconds
boolean lastConnected = false;                 // state of the connection last time through the main loop
const unsigned long postingInterval = 10*1000;  // delay between updates, in milliseconds
#define W5200_CS  10
#define SDCARD_CS 4
void setup() {
   // start serial port:
 Serial.begin(38400);
 Serial3.begin(38400);
 pinMode(SDCARD_CS,OUTPUT);
  digitalWrite(SDCARD_CS,HIGH);//Deselect the SD card
  // give the ethernet module time to boot up:
   delay(1000);
  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip, myDns);
  // print the Ethernet board/shield's IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  char c;
  dimLights(standardLightingPattern);
  dimLights(nightTimeLightingPattern);

  // if there's no net connection, but there was one last time
  // through the loop, then stop the client:
  if (!client.connected() && lastConnected) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }
  // if you're not connected, and ten seconds have passed since
  // your last connection, then connect again and send data:
  if(!client.connected() && (millis() - lastConnectionTime >    postingInterval)) {
    getPh();
    getTemperature();
    httpRequest();
  }
  // store the state of the connection for next time through
  // the loop:
  lastConnected = client.connected();
}

void getPh() {
  Serial3.print("r<CR>");
  if (sensor_string_complete == true) {
   //Serial.println(sensorstring);
   if (isdigit(sensorstring[0])) {
      pH = sensorstring.toFloat();
    }
  }

 sensorstring = "";
 sensor_string_complete = false;
}

void dimLights(int lightingBrightnessArray[]) {
  analogWrite(whiteLedString, lightingBrightnessArray[0]);
  analogWrite(colorLedString, lightingBrightnessArray[1]);
  analogWrite(blueLedString, lightingBrightnessArray[2]);

}

float getTemp(int pin) {
  OneWire ds(pin);
  byte k;
  byte present = 0;
  byte type_s = 0;
  byte data[12];
  byte addr[8];
  float celsius;
  float fahrenheit;

  if (!ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(2500);
  }

  ds.reset();
  ds.select(addr);

  // start conversion, with parasite power on at the end
  ds.write(0x44, 1);

  // maybe 750ms is enough, maybe not
  delay(1000);

  present = ds.reset();
  ds.select(addr);

  // Read Scratchpad
  ds.write(0xBE);

  // we need 9 bytes
  for (k = 0; k < 9; k++) {
    data[k] = ds.read();
  }

  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {

   // 9 bit resolution default
   raw = raw << 3;

   if (data[7] == 0x10) {
     // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
    } else {
      byte cfg = (data[4] & 0x60);
      // at lower res, the low bits are undefined, so let's zero them
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms

     // default is 12 bit resolution, 750 ms conversion time
    }

    celsius = (float)raw / 16.0;
    fahrenheit = celsius * 1.8 + 32.0;
    return fahrenheit;
}

void getTemperature() {

 //get temperature 1 from display
  temps[0] = getTemp(temperaturePins[0]);
  delay(1000);

  //get temperature 2 from sump
  temps[1] = getTemp(temperaturePins[1]);
  delay(1000);

  //used for building parameters for GET request for passing DB values
  Serial.println("");
  float temp1 = temps[0];
  float temp2 = temps[1];
  //converts pH sensor char buffer to float val
  //float pH = atof(stamp_data);

  //used for debugging
  Serial.println("Returned Temp 1: ");
  Serial.println(temp1);
  Serial.println("Returned Temp 2: ");
  Serial.println(temp2);
  Serial.println("ph val:");
  Serial.println(pH);

  //build url for GET request using above parameters
  *buildUrlParameter(pH, temp1, temp2);
  Serial.println(dest1);
  //make HTTP request
   httpRequest();
}

char *buildUrlParameter(float pH, float temp1, float temp2) {
  //builds char buffer from three float values passed from
  //sensors and apends proper sensor monikers
  dtostrf(pH, 4, 2, cnctPh);
  dtostrf(temp1, 5, 2, cnctTemp1);
  dtostrf(temp2, 5, 2, cnctTemp2);
  strcpy(dest1, "ph=");
  strcat(dest1, cnctPh);
  strcat(dest1, "&T1=");
  strcat(dest1, cnctTemp1);
  strcat(dest1, "&T2=");
  strcat(dest1, cnctTemp2);

  return dest1;
}

 // this method makes a HTTP connection to the server:
   void httpRequest() {

   sprintf(outBuf, "GET http://192.168.1.107/ReefController/trunk/app/php/reef_controller_loadVals_all.php?%s HTTP/1.0", dest1);
   Serial.println(outBuf);
//Serial.println("connecting...");
 delay(1000);
  //client.connect(server, 80);

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    client.println(outBuf);
    Serial.println("connecting...");
    // send the HTTP PUT request:
    client.println("Host: localhost");
    client.println("User-Agent: arduino-ethernet");
    client.println("Content Type: application/json");
    client.println("Connection: close");
    client.println();

    Serial.println("Successfully recorded to database");
    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
    Serial.println("disconnecting.");
    client.stop();
  }
}`

```

What is happening is when my program hits httpRequest the client.connect is successful maybe 2-3 times out of 5. The PHP server is up and running fine. It will just fall into the last else and give me connection failed / disconnecting when it isn't working.... when it does work I get a response back `500 internal server error` yet the PHP script runs and records my posted values to the database. Any thoughts?

# Answer
> 1 votes
This is why I think the server returns a HTTP500:

Usually in HTTP requests you do not include the ip address, so:

`GET http://192.168.1.107/<really long part>?%s HTTP/1.0`

would become:

`GET /<really long part>?%s HTTP/1.0`

Also HTTP requests should use carriage return AND line feed to indicate the end of a line. And an HTTP request should ALWAYS end in a full blank line. You are using the HTTP1.0 protocol, so your request can be done in one line, so you can just end it with: `\r\n\r\n`. If your request would be multiple lines, every line should also end with `\r\n`.

So the result would be:

`GET /<really long part>?%s HTTP/1.0\r\n\r\n`

One `CRLF` (the `\r\n` part) to begin a new line and one more for the blank line.

As for the connection problem, I think this has to do with the fact that you need to open AND close the connection for each HTTP request. You are using the HTTP1.0 protocol which does not support multiple HTTP requests in one connection. You can send multiple HTTP requests when using HTTP1.1, but then you also have to think about the TCP keepalive and it makes your request more complicated.

Try changing your HTTP request as mentioned above and call client.connect() and a client.stop() for every HTTP request. And don't forget to tell us the results!

---
Tags: arduino-mega, c++, shields, ethernet
---


title: OV 7670 + FIFO (AL422B) with arduino

text:
# Question
Title: OV 7670 + FIFO (AL422B) with arduino
I just brought the camera OV7670 with fifo but I am unable to get the wiring of board with arduino and also I do not find any arduino library for OV7670 with fifo.

It will great if you can help to find some link which can help me.

Thanks, Somnath

# Answer
Here is a link. Use google to find more. It is not difficult.
> 1 votes

---
Tags: arduino-uno
---


title: Reverse the order of a hex string

text:
# Question
Title: Reverse the order of a hex string
I'm printing an "unsigned long" value to HEX via:

```
println(cardCode, HEX);

```

The value that I'm getting is: 69fb879d

I need it to be reversed as: 9d87fb69

I populate cardCode via the code:

```
for (i=1;i<bitCount;i++)
{
  cardCode <<=1;
  cardCode |= databits[i];
}

```

going into this my bitCount value is 32, so basically I'm populating cardCode based on 32 bits from the variable databits which is of type unsigned char.

I am absolutely crap at bitwise conversions (bit-shifting, etc.), is there a simple way to do this reversal? Is this even enough information to go on?

# Answer
Your issue seems to be byte order (big endian) and not bit order. The simplest solution to byte order swap is to use the builtin functions provided by the compiler (AVR GCC).

```
unsigned long cardCode;
...
Serial.print(__builtin_bswap32(cardCode), HEX);

```

There are two compiler builtin functions for byte order swap. One for 16-bit data and one for 32-bit data.

```
uint16_t __builtin_bswap16(uint16_t);
uint32_t __builtin_bswap32(uint32_t);

```

AVR MCUs are little endian (least significant byte first in memory). There are many devices that use big endian (most significant byte first). This is also known as network order. There are a set of functions/macros to help write portable code, especially device drivers.

```
#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

```

These are used to map data from host to network byte order and reverse. They are defined as byte swap functions for hosts with little endian byte order. Unfortunately they are not available in the GCC AVR library but easy to define.

```
#define htonl(x) __builtin_bswap32((uint32_t) (x))
...

```

Cheers!
> 5 votes

# Answer
The title of this question is "Reverse the order of a hex string" but it was actually about reversing byte order in an unsigned long int.

Here is an answer for reverse the order of a string (null terminated vector of char).

There is a standard function for that in the C string function library.

```
char* strrev(char* s);

```

Cheers!
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: HID multiCLASS RFID reader all Mifare to Wiegand 32bit
I'm using an Arduino Uno to read from a "HID multiCLASS (RP40CKPNN) reader", which is a stand-alone reader that reads cards and returns a number of bits via Weigand Data0/Data1 protocol. The "multiCLASS" readers can read both 125HZ PROX tags, and 13.57MHz mifare tags.

I have it reading and decoding 125HZ (multiple-PROX format) tags of various bit-lengths just fine, but when the reader is presented with a 13MHz card (specifically Mifare cards) the reader decodes the CSR/UID of ALL Mifare cards to 32bits. The Mifare cards come in two types, Classic (that use a 4byte UID), and Ultra (that use a 7byte UID), so I would expect 32bits for the Classic cards, and 56bits for the Ultra, but I only ever get back 32bits.

The reader's data-sheets specifically calls out that for mifare tags it should return a 32bit or 56bit CSR value based on the serial number of the card, but I've looked through lots of HID literature on this reader, and I can't find any specifics on how to change/modify its configuration.

Does anyone have any experience with these readers, and is there some trick to changing the configuration so that it returns more bits for Mifare cards?

# Answer
For this specific reader, communication is only one way, from the reader to the Arduino via Weigand protocol. Because of this, changes to the configuration for these readers is handled by proprietary RFID cards obtained from HID Global. The reader reads the card, and changes its configuration accordingly. I was able to reach out to HID Global technical support and they are sending me a card that will change the configuration to output 56bit CSN/CSR/UID for mifare cards (which will cover the 7byte UID of mifare ultra).

Thanks for the comments that helped me work this through.
> 1 votes

---
Tags: rfid
---


title: Copy content of array

text:
# Question
Title: Copy content of array
This may be an easy question, and if so im sorry, but i couldn't find out how to do this. I've programmed in python before and hoped that this would work, but it don't.

```
int myArray1[] = {0, 2, 4, 5, 7, 9, 11};
int myArray2[] = {0, 2, 3, 5, 7, 8, 10};
int myArray3[] = {0, 3, 5, 6, 7, 10};

int newArray[] = myArray2;

```

I wanted to only have to change one place in my code, which of the first three arrays i want my new array to take values from. Do anyone have any suggestions on how to do this?

# Answer
Make `newArray` be a pointer to whichever array you wish to work with. For example:

```
int myArray1[] = {0, 2, 4, 5, 7, 9, 11};
int myArray2[] = {0, 2, 3, 5, 7, 8, 10};
int myArray3[] = {0, 3, 5, 6, 7, 10};

int *newArray = myArray2;

// ... work with selected array, via newArray[] subscripting

```

Note, you may need to set an array-length variable at the same time as choosing the array.

For example:

```
int *newArray = myArray2;
int newSize = sizeof(myArray2)/sizeof myArray2[0];

// ... work with selected array

newArray = myArray3;
newSize = sizeof(myArray3)/sizeof myArray3[0];
// ... work with selected array

```

Alternately, add an array-end marker at the end of each array (eg, a negative number), or more elegantly, make all the arrays the same length.

If you want to make a new copy of the original array, such that modifying the new array won't change the old, use (eg) `memcpy()`. For example:

```
int newArray[7];
...
memcpy(newArray, myArray2, sizeof(myArray2));

```

Note that `memcpy()`'s size argument is given in bytes. Also, if you need to declare `memcpy()` \[I don't recall whether it's automatically declared in the Arduino environment\], add `#include <string.h>` up front.
> 3 votes

---
Tags: array
---


# Question
Title: Communication over I2C protocol with more than one A/D device
According to datasheet of MCP3021 A/D converter (Microchip, page 16) the MCP3021 can be accessed by proper address bits in control byte. In case of MCP3021 *5AT* the address is 101, in case of MCP3021 *4AT* the address is 100. Does than mean that to interface two MCP3021 diveces in one circuit one have to purchase two devices with *different* serial number, e.g. MCP3021 *5AT* and *4AT*?

# Answer
Yes, you need different devices for different addresses. Up to 8 addresses are possible:

> The first part of the control byte consists of a 4-bit device code, which is set to 1001 for the MCP3021. The device code is fol- lowed by three address bits: A2, A1 and A0. The default address bits are 101 (contact the Microchip factory for additional address bit options).The address bits allow up to eight MCP3021 devices on the same bus and are used to determine which device is accessed

The number after the A in the part number indicates the address:

Off the shelf you get address 5. If you want other addresses you have to order them specially from Microchip.

The device sacrifices flexibility in favour of size. If you want multiple devices on the same bus and not have to order different parts specially then you generally end up with a bigger chip with more pins to allow you to manually configure the sub-address.
> 1 votes

---
Tags: i2c
---


# Question
Title: How does serial communications work on the Arduino?
With reference to the Arduino Uno, Mega2560, Leonardo and similar boards:

* How does serial communications work?
* How fast is serial?
* How do I connect between a sender and receiver?

*Please note: This is intended as a reference question.*

# Answer
Asynchronous serial (usually referred to as serial) communications is used to send bytes from one device to another. A device could be one or more of the following:

* Arduino
* PC
* GPS
* RFID card reader
* LCD display
* Modem
* Other

---

## Clock rate and sampling of data

Unlike SPI / USB / I2C serial communications does not have a clock signal. The sampling clock is an agreed-upon sample rate (known as the baud rate). Both sender and receiver must be configured to be using the same rate or the receiver will receive meaningless data (due to the bits not being sampled at the same rate that they were sent).

The transmission is asynchronous which basically means that bytes can be sent at any time, with varying gaps between them. This graphic illustrates a single byte being sent:

The graphic above shows the letter 'F' being transmitted. In ASCII this is 0x46 (in hex) or 0b01000110 (in binary). The *least* significant (low-order) bit is transmitted first, thus in the above graphic you see the bits arriving in the order: `01100010`.

The "idle" time between bytes is transmitted as continuous "1" bits (effectively, the transmit line is held high continuously).

To indicate the start of a byte, the *Start Bit* is always indicated by pulling the line low as shown on the graphic. Once the receiver sees the start bit, it waits for 1.5 times the sample time, and then samples the data bits. It waits 1.5 times so that it:

* Skips the start bit
* Samples half-way through the next bit

If the baud rate is 9600 baud, for example, then the sample rate will be `1/9600 = 0.00010416` seconds (104.16 µs).

Thus, at 9600 baud, after receiving a start bit the receiver waits for 156.25 µs, and then samples every 104.16 µs.

The purpose of the *Stop Bit* is to ensure that there definitely is a 1-bit between each byte. Without the stop bit, if a byte ended in a zero, then it would be impossible for the hardware to tell the difference between that and the start bit of the next byte.

To produce the above output on an Uno you could write this code:

```
void setup()
  {
      Serial.begin(9600);
      Serial.print("F");
  }

void loop ()
  {
  }

```

---

## Number of data bits

In order to save transmission time (in the olden days, heh) you were allowed to specify different numbers of data bits. The AtMega hardware supports data bits numbering from 5 to 9. Clearly the less data bits the less information you can send, but the faster it will be.

---

## Parity bits

You can optionally have a parity bit. This is calculated, if required, by counting the number of 1's in the character, and then making sure that this number is odd or even by setting the parity bit to 0 or 1 as required.

For example, for the letter "F" (or 0x46 or 0b01000110) you can see that there are 3 ones there (in 01000110). Thus we already have odd parity. So, the parity bit would be as follows:

* No parity: omitted
* Even parity: a 1 (3 + 1 is even)
* Odd parity: a 0 (3 + 0 is odd)

The parity bit, if present, appears after the last data bit but before the stop bit.

If the receiver does not get the correct parity bit, that is called a "parity error". It indicates that there is some problem. Possibly the sender and receiver are configured to use different baud (bit) rates, or there was noise on the line which turned a zero to a one or vice-versa.

Some early systems also used "mark" parity (where the parity bit was always 1 regardless of the data), or "space" parity (where the parity bit was always 0 regardless of the data).

---

## 9-bit transmission

Some communication equipment uses 9-bit data, so in these cases the parity bit is turned into the 9th bit. There are special techniques for sending this 9th bit (the registers are 8-bit registers so the 9th bit has to be put somewhere else).

---

## Number of stop bits

Early equipment tended to be somewhat slower electronically, so to give the receiver time to process the incoming byte, it was sometimes specified that the sender would send two stop bits. This basically adds more time where the data line is held high (one more bit time) before the next start bit can appear. This extra bit time gives the receiver time to process the last incoming byte.

If the receiver does not get a logical 1 when the stop bit is supposed to be, that is called a "framing error". It indicates that there is some problem. Quite possibly the sender and receiver are configured to use different baud (bit) rates.

---

## Notation

Commonly, serial communication is indicated by telling you the speed, number of data bits, type of parity, and number of stop bits, like this:

```
9600/8-N-1

```

This is telling us:

* 9600 bits per second
* 8 data bits
* No parity (you might see instead: E=even, O=odd)
* 1 stop bit

It is important that the sender and receiver agree on the above, otherwise communication is unlikely to be successful.

---

## Pin-outs

The Arduino Uno has digital pins 0 and 1 available for hardware serial:

To connect two Arduinos you *swap* Tx and Rx like this:

---

## Speed

A wide range of speeds is supported (see graphic below). "Standard" speeds are usually a multiple of 300 baud (eg. 300/600/1200/2400 etc.).

Other "non-standard" speeds can be handled by setting the appropriate registers. The HardwareSerial class does this for you. eg.

```
Serial.begin (115200);  // set speed to 115200 baud

```

As a rule-of-thumb, assuming you are using 8-bit data, then you can estimate the number of bytes you can transmit per second by dividing the baud rate by 10 (because of the start bit and stop bit).

Thus, at 9600 baud you can transmit 960 bytes (`9600 / 10 = 960`) per second.

---

## Baud rate errors

The baud rate on the Atmega is generated by dividing down the system clock, and then counting up to a pre-set number. This table from the datasheet shows the register values, and error percentages, for a 16 MHz clock (such as the one on the Arduino Uno).

The U2Xn bit affects the clock rate divisor (0 = divide by 16, 1 = divide by 8). The UBRRn register contains the number the processor counts up to.

So from the table above, we see that we get 9600 baud from a 16 MHz clock as follows:

```
16000000 / 16 / 104 = 9615

```

We divide by 104 and not 103 because the counter is zero-relative. Thus the error here is `15 / 9600 = 0.0016` which is close to what the table above says (0.02%).

You will notice that some baud rates have a higher error amount than others.

According to the datasheet the maximum error percentage for 8 data bits is in the range of 1.5% to 2.0% (see the datasheet for more details).

---

## Arduino Leonardo

The Arduino Leonardo and Micro have a different approach to serial communications, as they connect directly via USB to the host computer, not via the serial port.

Because of this, you must wait for Serial to become "ready" (as the software establishes an USB connection), with an extra couple of lines, like this:

```
void setup()
  {
      Serial.begin(115200);
      while (!Serial)
      {}  // wait for Serial comms to become ready
      Serial.print("Fab");
  }

void loop ()
  {
  }

```

However, if you want to actually communicate via pins D0 and D1, (rather than by the USB cable) then you need to use Serial1 rather than Serial. You do so like this:

```
void setup()
  {
      Serial1.begin(115200);
      Serial1.print("Fab");
  }

void loop ()
  {
  }

```

---

## Voltage levels

Note that the Arduino uses TTL levels for serial communications. This means that it expects:

* A "zero" bit is 0V
* A "one" bit is +5V

Older serial equipment designed to plug into a PC's serial port probably uses RS232 voltage levels, namely:

* A "zero" bit is +3 to +15 volts
* A "one" bit is −3 to −15 volts

Not only is this "inverted" with respect to TTL levels (a "one" is more negative than a "zero"), the Arduino cannot handle negative voltages on its input pins (nor positive ones greater than 5V).

Thus you need an interface circuit for communicating with such devices. For input (to the Arduino) only, a simple transistor, diode, and a couple of resistors will do it:

For two-way communication you need to be able to generate negative voltages, so a more complex circuit is required. For example the MAX232 chip will do that, in conjunction with four 1 µF capacitors to act as charge-pump circuits.

---

## Software Serial

There is a library called SoftwareSerial that lets you do serial communications (up to a point) in software rather than hardware. This has the advantage that you can use different pin configurations for serial communications. The disadvantage is that doing serial in software is more processor-intensive and more prone to error. See Software Serial for more details.

---

## Mega2560

The Arduino "Mega" has 3 additional hardware serial ports. They are marked on the board as Tx1/Rx1, Tx2/Rx2, Tx3/Rx3. They should be used in preference to SoftwareSerial if possible. To open those other ports you use the names Serial1, Serial2, Serial3, like this:

```
Serial1.begin (115200);  // start hardware serial port Tx1/Rx1
Serial2.begin (115200);  // start hardware serial port Tx2/Rx2
Serial3.begin (115200);  // start hardware serial port Tx3/Rx3

```

---

## Interrupts

Both sending and receiving, using the HardwareSerial library, use interrupts.

### Sending

When you do a `Serial.print`, the data you are trying to print is placed in an internal "transmit" buffer. If you have 1024 bytes or more of RAM (such as on the Uno) you get a 64-byte buffer, otherwise you get a 16-byte buffer. If the buffer has room, then the `Serial.print` returns immediately, thus not delaying your code. If there is no room, then it "blocks" waiting for the buffer to be emptied enough for there to be room.

Then, as each byte is transmitted by the hardware an interrupt is called (the "USART, Data Register Empty" interrupt) and the interrupt routine sends the next byte from the buffer out of the serial port.

### Receiving

As incoming data is received an interrupt routine is called (the "USART Rx Complete" interrupt) and the incoming byte is placed into a "receive" buffer (the same size as the transmit buffer mentioned above).

When you call `Serial.available` you find out how many bytes are available in that "receive" buffer. When you call `Serial.read` a byte is removed from the receive buffer and returned to your code.

On Arduinos with 1000 bytes or more of RAM, there is no rush to remove data from the receive buffer, provided you don't let it fill up. If it fills up then any further incoming data is discarded.

Note that because of the size of this buffer there is no point in waiting for a very large number of bytes to arrive, for example:

```
while (Serial.available () < 200)
  { }  // wait for 200 bytes to arrive

```

This will never work because the buffer cannot hold that much.

---

## Tips

* Before reading, always make sure data is available. For example, this is wrong:

```
if (Serial.available ())
  {
      char a = Serial.read ();
      char b = Serial.read ();  // may not be available
  }

```

The `Serial.available` test only ensures you have *one* byte available, however the code tries to read two. It may work, if there are two bytes in the buffer, if not you will get -1 returned which will look like 'ÿ' if printed.
* Be aware of how long it takes to send data. As mentioned above, at 9600 baud you an only transmit 960 bytes per second, so trying to send 1000 readings from an analog port, at 9600 baud, won't be very successful.

---

## References
> 17 votes

---
Tags: serial, c++, hardware, softwareserial
---


# Question
Title: What if Ultrasonic sensor doesn't detect object?
I am trying to write a sketch where a function will only be triggered when the ultrasound doesn't return back. Thus when the echo pin is checked after 1 second after the trigger pin was written high, it must be low. Will it be a digitalRead function?

# Answer
What type of Ultrasonic sensor do you have?

I'll go with HC-SR04, since I've got one of those laying around here. The other ultrasonic sensors should be working in the same way.

**Before you start!**

Read the datasheet. A fast search on google with: "\[manufacturer\]\[device id\]\[device description\] datasheet .pdf" will do good.

Example: http://www.micropik.com/PDF/HCSR04.pdf

The datasheet will tell you important things/values and sometimes even interfacing examples or code. Like:

* Max input voltage
* Max current
* Pin-out diagrams
* How to interface with the device
* Min/max operating temperature

**Wiring up**

The datasheet will tell you what to connect, to which pins.

We've got 5V, Trigger (input), Echo (output), 0V (ground).

(As per datasheet)

It's best to do the wiring before you put power on it, because you can accidently short it when moving wires around.

**Interfacing**

I would recommend checking some code examples before you attempt to roll your own. Or just start from an example and edit it to your specifications.

The timing diagram shows us it needs a 10uS pulse on the trigger input. And the duration of the echo will show the distance (58 uS per cm or 148 uS per inch).

The datasheet also suggest to use over 60ms measurement cycles.

**Code**

Taking all that into account:

```
#define trigPin 13
#define echoPin 12
#define led 11
#define led2 10

const unsigned long timeout = 400*58; //Max of 400CM, adjust this to your own max.

void setup() {
  Serial.begin(115200);//Stop using 9600 as default, it's not fast.
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
}

void loop() {
  unsigned long distance;//unsigned, since we don't get negative distances.
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); //10 uS pulse.
  digitalWrite(trigPin, LOW);

  distance = round(pulseIn(echoPin, HIGH,timeout) /58);//Distance in CM's, use /148 for inches.
  if (distance == 0){//Reached timeout
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(60);//Wait 60 ms for next cycle.
}

```

To be honest, I'm not even slightly sure if this code is working. I modified this code: http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/

So that you're actually using the timeout right, and do the timing according to the datasheet.
> 2 votes

---
Tags: sensors, sketch
---


title: Shift Register Not Working

text:
# Question
Title: Shift Register Not Working
I am trying to learn how to use a shift register to control 8 LEDs but for some reason my shift register is misbehaving and none of the LEDs are lighting up. I imagine that it's a problem with my wiring? I have replicated the circuit on 123D Circuits.

```
//Pin connected to ST_CP of 74HC595
int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 12;
////Pin connected to DS of 74HC595
int dataPin = 11;

void setup() {
  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
  // count from 0 to 255 and display the number
  // on the LEDs
  for (int numberToDisplay = 0; numberToDisplay < 256; numberToDisplay++) {
    // take the latchPin low so
    // the LEDs don't change while you're sending in bits:
    digitalWrite(latchPin, LOW);
    // shift out the bits:
    shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay);

    //take the latch pin high so the LEDs will light up:
    digitalWrite(latchPin, HIGH);
    // pause before next value:
    delay(500);
  }
}

```

# Answer
From the Arduino website:

> ## shiftOut()
>
> Description
>
> Shifts out a byte of data one bit at a time. \[...\]
>
> Note: if you're interfacing with a device that's clocked by rising edges, you'll need to make sure that the clock pin is low before the call to shiftOut(), e.g. with a call to digitalWrite(clockPin, LOW).

You need to pull `clockPin` low before each `shiftOut()` call, as the documentation says.

Also, you have misunderstood the behaviour of the `latchPin`. This can be high or low at any time; it's the *change from low to high* that latches the data into the output cells.
> 1 votes

---
Tags: shift-register
---


# Question
Title: Can RX and TX be temporarily transposed on demand?
Only 2 arduinos can normally be linked via serial port because TX and RX need to be cross-linked, and connecting multiple TXs together would cause conflict.

RS485 allows multiple nodes connected in parallel on a 2 wire differential 'bus', using a TX ENABLE pin to allow one master to transmit while all other slaves listen.

I suspect it should be possible to similarly connect multiple serial RXs together to give a common listening bus, and be able to use TX ENABLE on any one node at a time to transpose its RX and TX to allow its TX to transmit to the other RXs. This might be physically done using a changeover relay swapping RX with TX, but is it possible to somehow temporarily switch the TX and RX assignments on demand by software?

I doubt the actual pin assignments can be changed in-situ, but perhaps the same results are achievable with some programming wizards sleight-of-hand trickery?

# Answer
> 1 votes
On an AVR-based Arduino, you can selectively enable the transmitter and receiver side of the UART (c.f. the datasheet of your MCU). Thus, you could in principle just connect all the TX and RX together, and make sure only one transmitter is enabled at a time, while all the others are in high impedance. If you do this, I would strongly recommend you put a current-limiting resistor in series with each TX, just in case.

For example, on an Arduino Uno (Atmega328P), you can use the following functions:

```
static inline void enable_tx()  { UCSR0B |=  _BV(TXEN0); }
static inline void disable_tx() { UCSR0B &= ~_BV(TXEN0); }
static inline void enable_rx()  { UCSR0B |=  _BV(RXEN0); }
static inline void disable_rx() { UCSR0B &= ~_BV(RXEN0); }

```

**Edit**: Beware that `Serial.begin()` enables both the transmitter and the receiver.

# Answer
> 1 votes
It sounds to me like you are misunderstanding the purpose of the TX Enable pin and you are trying to come up with some convoluted method to do exactly what TX Enable actually does.

Under normal circumstances, in RS485, the UART's RX pin is connected to the bus. When TX Enable is asserted the RX pin is disconnected and the TX pin is connected, thus allowing any node on the bus to be a transmitter and all the other nodes a receiver.

The main thing to watch out for though is that only one node is ever a transmitter at a time, otherwise you get a *collision* which means that the data is completely garbled.

The simplest way of stopping that happening is to have one node nominated as the *master* and all the other nodes as *slaves*. The *master* first initiates communication by making a request to a *slave*. The *slave* will then respond with data (it becomes the transmitter and the *master* a receiver) to send data to the master. That way the only node that is a transmitter is either the *master* making the request, or the *slave* that is responding to a request.

If you want "random" peer-to-peer communication where any node could become a transmitter at any time it becomes a whole lot more complex. There are things you should implement to try to avoid, or deal with, collisions, including monitoring the bus and only transmitting after a certain amount of idle time has been detected, reading the bus while writing to it (requires more hardware) and confirming that the data you read from the bus is the same as the data you wrote to the bus, and random delays before retrying a failed communication. That last one is probably the trickiest to get right, since random numbers on Arduinos aren't really random unless you "seed" them from a truly random source. You don't want both ends delaying for the same amount of time to retry otherwise it will never complete.

---

Since you apparently want to achieve that kind of thing but *without* using RS485, it all gets much more complex.

No, you cannot "swap" the functionality of the TX and RX pins in the Arduino. **BUT** you can do serial communication (albeit somewhat heavyweight) using pure software. Take a look at the SoftwareSerial library - you will most likely need to make modifications to that to achieve what you want.

To do it externally with hardware is possible, but the end result will most likely be more complex than just using a simple RS485 interface chip which are very inexpensive and easy to get hold of.

Yes, you could use relays (*clunky*) or buffers, or multiplexers, etc, but why would you when RS485 does what you want?

---
Tags: programming, communication
---


# Question
Title: How to make two wheels turn only for a particular amount of time?
I am trying to make a robot turn (dc motors are being used) back 180 degrees. So I used an l289n for it and made one wheel turn clockwise and vice-versa.
But as I wan't it to make only a 180 degrees turn, I wanted to set an amount of time for it to turn. Is there any other way to do the same thing, if yes, please tell, if no, help me...

# Answer
Use the delay() function.

Pseudo code as follows:

```
1) Turn clockwise motor on;
2) Turn counterclockwise motor on;
3) delay(<time>);
4) Turn CW motor off;
5) Turn CCW motor off.

```
> 1 votes

---
Tags: motor, sketch, robotics
---


title: Arduino to DAC to ADC back to Arduino?

text:
# Question
Title: Arduino to DAC to ADC back to Arduino?
My question is simple. Is the following possible?

I am using one Arduino Mega 2560 board and its SPI functionality to adjust voltages (0-4.096V) through a 12-bit DAC (MCP4822).

I would like to measure the output voltages from the DAC by feeding them through a 12-bit ADC and back to the Arduino. The DAC's output voltages that will be directly measured by the ADC will be displayed on an LCD and on LabVIEW.

Is this possible, given that both the DAC and the ADC have to be connected to the same SDI and SCK pins on the Arduino for SPI to work?

# Answer
Yes, perfectly possible. Just provide two separate CS pins to select between the two devices.
> 2 votes

---
Tags: arduino-mega, spi, digital-analog-conversion
---


# Question
Title: Take an Arduino or Teensy prototype to Mass production - Loading software onto microcontroller
I am developing an educational product that I would like to mass produce. I am not sure of the quantity yet, but I imagine we will make a few hundred PCBs at least to begin

I spoke with an electrical engineering about how to take an Arduino prototype to mass production, and he warned me that the code written in the Arduino IDE cannot be fused onto the processor. (He used the term "fuse", although I don't see this elsewhere in the forum. is this the right term?)

He said that I would probably have to take each product, and load the Arduino code on manually, plugging in each one to a computer and upload like one would when prototyping. Also, he said the other option would be to recode my Arduino sketch from scratch using an AVR code.

Can someone shed some light on this for me? How can I take Arduino prototyping code and use it in mass production?

# Answer
> I spoke with an electrical engineering about how to take an Arduino prototype to mass production, and he warned me that the code written in the Arduino IDE cannot be fused onto the processor.

That's nonsense. The output from the IDE compiler is a .hex file which is then sent via `avrdude` to program the board. If the output cannot be "fused" onto the processor how does he imagine we ever get anything done?

Possibly he is referring to changing the fuses to make it impossible to read the code back from the chip. This can be easily accomplished.

---

> He said that I would probably have to take each product, and load the Arduino code on manually, plugging in each one to a computer and upload like one would when prototyping.

You have obviously spoken to someone with no experience in Arduinos, possibly one of those engineers with an active dislike of it.

I have written code to run on an Arduino to upload sketches to another board.

You can read about it at Atmega chip stand-alone programmer to upload .hex files. The idea is you take your .hex file, put it onto an SD card and then program your target board in a few seconds.

User "Crossroads" from the Arduino forum has taken that idea and made a stand-alone board, looking like this:

You put up to 255 hex files onto the SD card. You dial-up which one you want with the rotary dial. You plug in the ICSP cable into your target board, and hit the "program" button. The whole thing takes a few seconds.

It is designed to be used "in the field". All you have to do is plug in a power-pack to supply power to it.

If you needed to protect the target boards with a fuse setting after uploading, you would modify the code in the programmer slightly to do that for you.

It would be helpful to have an ICSP header on your target boards, both for programming before deployment, and in case you find a bug and have to change it.

Failing that you might put the chips into a suitable board first (eg. with a ZIF socket), program them off-board, and then solder them on. There are lots of options for you.

---

> Also, he said the other option would be to recode my Arduino sketch from scratch using an AVR code.

I don't see why that would be necessary, in any way.
> 1 votes

# Answer
Arduino code and AVR code is essentially the same, at least once compiled it is. The only real difference is the existence of the bootloader, and that is not essential.

For quantities of a hundred or so it is probably most cost effective to manually program them via an ISP connector to the board. For larger quantities Atmel provide a mass programming service to pre-program the chips, but that costs money so the more you have done at once the cheaper it is per chip. I am not sure on Atmel's procedure off hand but others I have used just take either a .elf or .hex file which the Arduino IDE is perfectly capable of producing.

Either way you should design in an ISP connector on your board so the firmware can be upgraded in the future if needed.
> 1 votes

# Answer
Arduino code **is** AVR code. There's no real difference. The only thing is that Arduino's tend to use bootloaders, which might cause a problem. But in your case I'd advice to not use a bootloader anyways.

Since you plan to build a lot of them, you probably want to use bare ATMega chips, and not arduino boards. Bare chips don't have a bootloader to begin with.

You'd program the boards using ISP.
> 1 votes

---
Tags: programming, sketch, teensy, software
---


# Question
Title: Unable to initialize W5100 using Arduino Pro Mini
I am unable to initialize a W5100 module using an Arduino Pro Mini. I try setting the MAC and IP addresses but read invalid values thereafter.

Here is the Arduino program along with the output:

```
void setup() {
    uint8_t mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    uint8_t local_ip[] = {192, 168, 1, 100};
    Ethernet.begin(mac, local_ip);
    printMacAddress(); // OUTPUT: FF:FF:FF:FF:FF:FF
    printIpAddress(); // OUTPUT: 255.255.255.255
}

void printMacAddress() {
    uint8_t mac[6];
    W5100.getMACAddress(mac);
    Serial.print(mac[0], HEX); Serial.print(":"); Serial.print(mac[1], HEX); Serial.print(":");
    Serial.print(mac[2], HEX); Serial.print(":"); Serial.print(mac[3], HEX); Serial.print(":");
    Serial.print(mac[4], HEX); Serial.print(":"); Serial.print(mac[5], HEX); Serial.println();
}

void printIpAddress() {
    IPAddress ip = Ethernet.localIP();
    Serial.println(ip);
}

```

I read in some blog posts that the Arduino may initialize before the W5100 initialization is completed so others recommend manually resetting the W5100 after Arduino initialization. So I connected the W5100 reset pin to the Arduino digital output 4 and reset the W5100 during setup using the following code.

```
const int W5100_RESET_PIN = 4;
pinMode(W5100_RESET_PIN, OUTPUT);
digitalWrite(W5100_RESET_PIN, LOW); // Activate reset pin by asserting low
delay(5); // Wait for 5 msec
digitalWrite(W5100_RESET_PIN, HIGH); // Deactivate reset pin by asserting high
delay(300); // Wait for W5100 to initialize[/code]

```

I observed the W5100 resetting because the module LEDs flashed off and back on each time I manually reset the Arduino. However this does not fix the W5100 mac/IP initialization issue.

**How should I troubleshoot this issue?**

Here are pictures of the assembly. https://i.stack.imgur.com/cjnHE.jpg

Here is an overview of the W5100 module. http://arduino-info.wikispaces.com/Ethernet

# Answer
One of the Ethernet examples shows you should test the result of the `begin` function call, like this:

```
// start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }

```

Try displaying the return value from `begin` to see if that initialization succeeded.
> 1 votes

---
Tags: arduino-pro-mini
---


# Question
Title: Programming "Arduino" code to AT90S8515?
I found (from a previous life) an STK500 and a couple AT90S8515's in the recesses of my basement.. that I would like to put to use.

Is there a way in which I can write "arduino code" for the 8515? I know that it's basically C/C++.

I also know that the 8515 doesn't have, or support, a bootloader like the Mega series of ICs do.. so I expect that I will need to program it using the STK500.

I downloaded AVR Studio, but I will admit, I became very lost, very quickly.

Thanks for any direction!

# Answer
> 1 votes
Theoretically yes, once you write a core (1.5.x/1.6.x) for it. I'm not sure if the IDE has a configuration for the STK500, but it should be easy enough to add (since avrdude already supports it).

# Answer
> 0 votes
In Atmel Studio 7 you can create a project on Arduino Code. For instance if you have a code for an Arduino UNO, it will ask for path of the sketch(a.ino file) and ask for device here it will be Atmega 328. Now you can build the solution and it will generate code for Atmega 328. Now you can rebuild the same solution by changing the device now select AT90S8515. In my case I built the code for a Atmega328. then rebuilt it by changing device to Atmega8. It worked

---
Tags: arduino-uno, avr, atmel-studio
---


# Question
Title: Is Arduino uno SPI comunication can be also master and slave in the same time?
Is Arduino uno SPI comunication can be also master and slave in the same time?

## OR master 2 slaves in the same time?

I want to recevice data from a sensor and display on OLED (all data transfer with SPI bus)

Can I master those two device (sensor & OLED) in the same time? (with SS pin to select slave )

OR Can I be both slave(recevices the data from sensor) and master (sent data to OLED) in the same time ?

What should I do ? and How can I do?

(I read the SPI example code on the Official website , but I still have no ideal about it)

# Answer
> 1 votes
You can have several devices on an SPI bus. Each must have a chip select. The Arduino SS pin (Uno pin 10) is often used for chip select. Chip select pins should then be in output mode.

Connect the sensor and display to the SPI bus (MOSI, MISO, SCK) and use a chip select pin for each.

A driver (library) for a device connect to the SPI bus will typically assert the chip select pin and transfer commands and data. The SPI transfer is both read and write at the same time.

# Answer
> 1 votes
SPI is bi-directional, so sending data or receiving data doesn't indicate if it's a master or a slave.

The master is the one that initiates the communications, that's all. So the arduino is a master in both cases. The master send data to the OLED. The master requests data from the sensor.

---
Tags: arduino-uno, spi
---


# Question
Title: Could I use metal buttons as a capacitive button for my arduino project?
Could I use something like this as a capacitive button for my arduino project?

http://www.banggood.com/10pcs-25mm-Vintage-Round-Metal-Buttons-Craft-Scrapbooking-Sewing-Suit-Shirt-Button-p-1011485.html

If I connect it into something like this... http://www.banggood.com/MPR121-Capacitive-Touch-Sensor-Module-For-Raspberry-Pi-Arduino-p-969002.html

Would that make that button a capacitive button? Or am I totally barking up the wrong tree here?

Thanks :)

# Answer
Yes, that would work.

The only thing to watch out for is that the buttons might be plastic with a thin layer of metal on top (Chemical vapor deposition).
> 1 votes

---
Tags: arduino-uno
---