# Question
Title: Arduino throwing error while using modbus RS485 code
I have been trying to make a communication with my industrial drive. All I want to do is read a few values of drive, like current, voltage etc. For that I am using a library:

I don't understand why it's happening. When the same code I have used before and the sketch was uploaded on the board, very well.

Here's the code from an example:

```
#include <SimpleModbusMaster.h>

// led to indicate that a communication error is present
#define connection_error_led 13

//////////////////// Port information ///////////////////
#define baud 9600
#define timeout 1000
#define polling 200 // the scan rate

// If the packets internal retry register matches
// the set retry count then communication is stopped
// on that packet. To re-enable the packet you must
// set the "connection" variable to true.
#define retry_count 10

// used to toggle the receive/transmit pin on the driver
#define TxEnablePin 2

// This is the easiest way to create new packets
// Add as many as you want. TOTAL_NO_OF_PACKETS
// is automatically updated.
enum
{
  PACKET1,
  PACKET2,
  // leave this last entry
  TOTAL_NO_OF_PACKETS
};

// Create an array of Packets for modbus_update()
Packet packets[TOTAL_NO_OF_PACKETS];

// Create a packetPointer to access each packet
// individually. This is not required you can access
// the array explicitly. E.g. packets[PACKET1].id = 2;
// This does become tedious though...
packetPointer packet1 = &packets[PACKET1];
packetPointer packet2 = &packets[PACKET2];

// The data from the PLC will be stored
// in the regs array
unsigned int regs[9];

void setup()
{
  // read 3 registers starting at address 0
  packet1->id = 2;
  packet1->function = READ_HOLDING_REGISTERS;
  packet1->address = 0;
  packet1->no_of_registers = 3;
  packet1->register_array = regs;

  // write the 9 registers to the PLC starting at address 3
  packet2->id = 2;
  packet2->function = PRESET_MULTIPLE_REGISTERS;
  packet2->address = 3;
  packet2->no_of_registers = 9;
  packet2->register_array = regs;

  // P.S. the register_array entries above can be different arrays

  // Initialize communication settings etc...
  modbus_configure(baud, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS);

  pinMode(connection_error_led, OUTPUT);
}

void loop()
{
  unsigned int connection_status = modbus_update(packets);

  if (connection_status != TOTAL_NO_OF_PACKETS)
  {
    digitalWrite(connection_error_led, HIGH);
    // You could re-enable the connection by:
    //packets[connection_status].connection = true;
  }
  else
    digitalWrite(connection_error_led, LOW);

  // update the array with the counter data
  regs[3] = packet1->requests;
  regs[4] = packet1->successful_requests;
  regs[5] = packet1->total_errors;
  regs[6] = packet2->requests;
  regs[7] = packet2->successful_requests;
  regs[8] = packet2->total_errors;
}

```

Also, here is the error I am receiving upon uploading the sketch

```
This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
Arduino: 1.0.6 (Windows 7), Board: "Arduino Uno"
SimpleModbusMasterExample:110: error: 'packetPointer' does not name a type
SimpleModbusMasterExample:111: error: 'packetPointer' does not name a type
SimpleModbusMasterExample.ino: In function 'void setup()':
SimpleModbusMasterExample:120: error: 'packet1' was not declared in this scope
SimpleModbusMasterExample:127: error: 'packet2' was not declared in this scope
SimpleModbusMasterExample:136: error: invalid conversion from 'int' to 'HardwareSerial*'
SimpleModbusMasterExample:136: error: invalid conversion from 'Packet*' to 'unsigned char'
C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h:143: error: too few arguments to function 'void modbus_configure(HardwareSerial*, long int, unsigned char, long int, long int, unsigned char, unsigned char, Packet*, unsigned int, unsigned int*)'
SimpleModbusMasterExample:136: error: at this point in file
C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h: In function 'void loop()':
C:\Users\xyz\Documents\Arduino\libraries\SimpleModbusMasterV2rev2/SimpleModbusMaster.h:125: error: too many arguments to function 'void modbus_update()'
SimpleModbusMasterExample:143: error: at this point in file
SimpleModbusMasterExample:143: error: void value not ignored as it ought to be
SimpleModbusMasterExample:155: error: 'packet1' was not declared in this scope
SimpleModbusMasterExample:158: error: 'packet2' was not declared in this scope

```

# Answer
> 1 votes
The code you are using is the example provided with the SimpleModbusMaster library found on GitHub: https://github.com/angeloc/simplemodbusng

It appears that the SimpleModbusMaster library isn't installed. This can happen if you install a new version of the Arduino IDE.

To install this library:

1. Go to the link above and download the zip of the code.
2. Extract the contents and then copy the folder "SimpleModbusMaster".
3. Paste the folder into the Arduino/libraries folder located on your computer. (On my computer it is: `C:\Program Files (x86)\Arduino\libraries`).
4. Restart the Arduino IDE. You can go straight to the example code by selecting: `File > Examples > SimpleModbusMaster > SimpleModbusMasterExample`

This procedure compiled for me with no errors.

---
Tags: arduino-uno, c, rs485, modbus
---


# Question
Title: Testing tri-state pin - erroneous results with internal pullup
I'm using an MPC73831 - a LiPo charging IC - in my Arduino project. It has a `status` pin to allow interface to a microcontroller, which uses a tri-state operation to convey three possible states of charging. I don't have the IC and battery yet, but I wanted to write a quick program to test a generic tri-state pin for HI, LO, and HiZ while I'm waiting for it to arrive.

The algorithm I wrote is very simple:

```
Set pinTest to input, no pullup.
Is pinTest high?
    Yes - pinTriState is HIGH, done.
Set pinTest to input with pullup.
Is pinTest high?
    Yes - pinTriState is HiZ, internal pullup causes high reading.
    No - pinTriState is LOW, 'cancelling out' internal pullup.

```

However, I'm not getting the expected results when using the internal pullup resistor - my board is showing correct analysis for HI and LO, but HiZ returns a mixture of HiZ and HIGH. I have tried this on an Uno, a Pro-Micro (32u4) and Uno-\>Micro and Micro-\>Uno. All give the same spurious results. I am baffled, therefore some advice would be appreciated. The full code is as below. I have left in code which randomises the time `pinTriState` stays at in a given state to keep `pinTest` guessing, but it's ultimately only an elaborate way of cycling through the three states.

```
#define pinTest 2
#define pinTriState 3

int state = 0;
char stateCh = '?';

int sect1;
int sect2;
int sectMax;

void setup()
{
    Serial.begin(9600);
    randomSeed(analogRead(A0));
    sect1 = random(1, 20);
    sect2 = random(sect1 + 1, random(sect1 + 2, sect1 + 20));
    sectMax = random(sect2 + 1, random(sect2 + 2, sect2 + 20));
}

void loop()
{
    // PART (1) Code to toggle three states of a tri-state pin
    if (state == 0)
    {
        pinMode(pinTriState, OUTPUT);
        digitalWrite(pinTriState, HIGH);
        stateCh = 'H';
    }
    if (state == sect1)
    {
        pinMode(pinTriState, OUTPUT);
        digitalWrite(pinTriState, LOW);
        stateCh = 'L'
    }
    if (state == sect2)
    {
        pinMode(pinTriState, INPUT);
        stateCh = 'Z';
    }

    // PART (2) Code to determine state of tri-state pin
    Serial.print(stateCh);     // Shows what it *should* be
    pinMode(pinTest, INPUT);
    if (digitalRead(pinTest))
        Serial.println(" - HIGH");
    else
    {
        pinMode(pinTest, INPUT_PULLUP);
        if (digitalRead(pinTest))
            Serial.println(" - HiZ");
        else
            Serial.println(" - LOW");
    }

    (state == sectMax ? state = 0 : state++);
}

```

The necessary pins are connected with a single wire. If I upload the code to two boards I remove *PART (2)* on the 'triState' board and *PART (1)* on the 'testing' board. In this case, `stateCh` has no function.

For a single-board setup, I get the following output:

```
H - HIGH
H - HIGH
...
L - LOW
L - LOW
...
Z - HiZ        <-- the first Z is correct 95% of the time
Z - HIGH
Z - HIGH       <-- the remaining Zs are a mixture, biased heavily towards HIGH.
Z - HiZ
...
H - HIGH       <-- H always gives HIGH
...

```

It makes no difference if I change the operating order of `pinState`. I've thrown in `delay(100);` between almost every other line, again to no avail.

I tried with a 22k, a 33k, and a 47k *external* pullup resistor. The results are perfect. However, this requires an extra Arduino pin to make sure that the pullup is only active when necessary. *Part (2)* becomes:

```
// PART (2) Code to determine state of tri-state pin
Serial.print(stateCh);     // Shows what it *should* be
pinMode(pinTest, INPUT);
pinMode(pinPullup, INPUT);    // connected to pinTest via resistor
if (digitalRead(pinTest))
    Serial.println(" - HIGH");
else
{
    //pinMode(pinTest, INPUT_PULLUP);   <-- not anymore
    pinMode(pinPullup, OUTPUT);
    digitalWrite(pinPullup, HIGH);    // pulls pinTest to Vdd
    if (digitalRead(pinTest))
        Serial.println(" - HiZ");
    else
        Serial.println(" - LOW");
}

```

Using the extra pin to provide the pullup is a real pain in the ar...duino. I'm cripplingly short of spare pins and I don't see why this is not resolvable with internal pullups. Help?!

# Answer
> 5 votes
The internal pull-up is around 50k. So, install an external pull-**down** (to ground) of a somewhat higher value, like 1M.

Now:

Go to input mode, no pull-up. Get a reading. Turn on the internal pull-up. This should overpower the pull-down. If the reading **changes**, it was tri-state. Otherwise, if the reading doesn't change the external device is overpowering both pull-up and pull-down and you have the actual reading.

You may need a slight delay to allow the low-value pull-down to change the pin state.

---

Amended code to demonstrate:

```
// PART (2) Code to determine state of tri-state pin
Serial.print(stateCh);     // Shows what it *should* be

pinMode(pinTest, INPUT);
delayMicroseconds (100);
byte firstReading = digitalRead(pinTest);
pinMode(pinTest, INPUT_PULLUP);
delayMicroseconds (10);
byte secondReading =  digitalRead(pinTest);

if (firstReading != secondReading)
  Serial.println(" - HiZ");
else if (secondReading == HIGH)
  Serial.println(" - HIGH");
else
  Serial.println(" - LOW");

```

(Only showing the part that detects the pin state, the rest is the same).

Output:

```
H - HIGH
L - LOW
Z - HiZ
Z - HiZ
Z - HiZ
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
L - LOW
Z - HiZ
Z - HiZ
Z - HiZ
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
L - LOW
Z - HiZ
Z - HiZ
Z - HiZ
H - HIGH
H - HIGH
H - HIGH

```

As you can see, working perfectly. I needed a longer delay after turning the internal pullup **off** because the fall time was around 100 µs. This actually sounds reasonable, because the 1 megohm resistor will take time to discharge the capacitance on the pin.

So:

* 10 µs delay after turning the internal pull-up **on**
* 100 µs delay after turning the internal pull-up **off**

---

**Theory for the delays**

The Atmega328 pin is specified as having a maximum capacitance of 10 pF (10e-12). It is considered charged/discharged after 5 time-constants, where `T = R.C`.

Thus for an internal pull-up resistance of 50k and a capacitance of 10 pF, charging should take:

```
50e3 * 10e-12 * 5 = 2.5e-006 (0.0000025) -> 2.5 µs

```

And to discharge through 1M (1e6) ohms, discharging should take:

```
1e6 * 10e-12 * 5 = 5e-005 (0.00005) -> 50 µs

```

My observed results were about 2.5 µS for the charge, but more like 100 µs for the discharge, however I probably had considerable stray capacitance in the wires used in the test circuit.

# Answer
> 3 votes
Another option is to use an analog input pin instead of a digital input pin.

Create a balanced voltage divider using equal high value resistors (say 100KΩ each). Attach the mid-point to the ADC pin, and one end to each of Vcc and GND. The incoming status signal goes to the ADC pin:

Perform an analogRead() on the pin. You will get one of 3 results:

* Close to 0 = LOW
* Close to 1024 = HIGH
* Close to 512 = HiZ

When the pin is in HiZ the resistors will hold the voltage at around 50% of Vcc. When the pin goes HIGH it will pull the pin up and override the resistors, giving a high value reading. Similarly, when the pin goes low, the resistors will be overridden and a low value reading will be given.

# Answer
> 0 votes
For the 1M pulldown solution, turning off the internal pullup at the end of the pin check routine MIGHT give enough time for the pin to discharge, and it might not if the code can conditionally do very little else between pin checks. If you want to leave out the 100 us delay, take care to ensure that your code will always do something that takes sufficient cycles for the pin to discharge between checks.

# Answer
> 0 votes
Nick Gammon's answer seems the most straightforward solution to your problem, given that you cannot spare an analog input. It has however the drawback of needing a delay of ≈ 100 µs. This may not be an issue, but I just figured out a scheme that allows a faster read, and may be of interest to some: instead of pull-ups or pull-downs, put just a 10 kΩ resistor *in series* between the MPC73831's output and you Arduino input. When you want to read the state:

1. Take a first reading with the pin in INPUT mode:
    * if you read HIGH, then your MPC is either HIGH or HI\_Z
    * if you read LOW, then it's either LOW or HI\_Z
2. Now, switch the pin to OUTPUT, write the *opposite* of what you just read, switch back to input and take a second reading:
    * if you read what you just wrote, then your MPC is in the HI\_Z state
    * if you read the same as before, then it's either HIGH or LOW.

Here is the implementation of this scheme:

```
#define HI_Z 2

/*
 * Read a 3-state pin.
 * Put a 10 kOhm resistor between the output and input pins.
 */
int read3state(int pin)
{
    int reading1 = digitalRead(pin);
    pinMode(pin, OUTPUT);
    digitalWrite(pin, !reading1);
    pinMode(pin, INPUT);
    int reading2 = digitalRead(pin);
    if (reading1 == reading2)
        return reading1;
    else
        return HI_Z;
}

```

I have tested this a few 104 times with an Arduino sending to itself a pseudo-random sequence of LOW, HIGH and HI\_Z. It works reliably for me.

**Caveat**: This scheme relies on the pin being capacitively coupled to GND or Vcc, and this coupling being stronger than couplings with other signals in your circuit. If you fear this might not be the case, you can put something like 100 pF from the pin to ground, but then you should better wait a couple of microseconds before taking the second reading.

---
Tags: pull-up
---


title: Atmel studio 7 - my own libraries

text:
# Question
Title: Atmel studio 7 - my own libraries
I like to use AS7 to make my programs. I know c and some c++, but how things work from there I'm green. I would like to know if there is a folder where I can store my own homemade c and h library files where they get to be available for all my projects. Now I copy all the files into each of my projects and this works but I find it a bit tedious.

# Answer
You should create your library as a separate project: File-\>New-\>Project and select C or C++ static library:

Add your library modules in this project. When building, this will create **lib{your\_project\_name}.a** file (in Debug or Release folder) - your library object file you can use in your other projects.

Usually I include in the same solution both the library project and target project (just library project file, sure the library and it's files resides in single place):

**ORDO** is the library name.

Some check list:

* Include the library file in Libraries folder (shown above)
* Specify the path to the library \*.a file for linker (Toolchain-\>AVR/GNU Linker-\>Libraries). Note that there should be different paths for Debug and Release configurations.
* Specify the path for library include files (Toolchain-\>AVR/GNU C or C++ Compiler-\>Directories)
* In some cases, F\_CPU definition might be needed for library project too (same as in your project, under Symbols).
* When changes are made in your library files, use Build solution (F7) when building, if not - you can use Build project (which will be faster).

Setting project dependencies shall also lead to rebuilding the library automatically when needed (not tested, I usually just hit F7 :).
> 1 votes

---
Tags: arduino-uno, arduino-mega, arduino-ide, atmel-studio
---


title: Random Blink LEDs

text:
# Question
Title: Random Blink LEDs
How can I make LEDs blink randomly?

I found a piece of code, but it is not working for me. I probably need something other than `setPixel()`, but I don't know what.

I am using the Fast.Led library with Arduino Nano and WS2812B LEDs

```
void loop() {
    Twinkle(CRGB::Red, 10, 100, false);
}

void Twinkle(uint32_t color, uint16_t Count, uint16_t SpeedDelay, boolean OnlyOne)
{
    FastLED.setBrightness(MAX_BRIGHTNESS);
    fill_solid(leds, random(NUM_LEDS), CRGB::White);
    FastLED.show();
    for (int i=0; i < Count; i++) {
//        setPixel(random(NUM_LEDS),red,green,blue);  //!ORIGINAL LINE OF CODE!
        setPixel(random(NUM_LEDS), color);  //!MY LINE!
        FastLED.show();
        delay(SpeedDelay);
        if (OnlyOne) {
            fill_solid(leds, NUM_LEDS, CRGB::Black);
            FastLED.show();
        }
    }

    delay(SpeedDelay);
    return;
}

```

# Answer
I can't tell exactly whats not working with your code,it would be really helpful if you elaborate more. But here is some code that I wrote and I think it will get the job done:

```
//declare our variables:
int myPins[] = {2, 4, 8, 3, 6}; //Enter the number of the pins being used
int RNum = 0;

void loop()
{
    DigitalWrite(myPins[RNum],LOW);
    RNum = Random(0,MAX) // MAX being the number of LEDs connected minus one
    //the above generates a random number
    DigitalWrite(myPins[RNum],High);
}

```

This will turn on one LED at a time.
> 1 votes

---
Tags: arduino-nano, rgb-led
---


title: Arduino Uno, Ethernet shield, MySQL

text:
# Question
Title: Arduino Uno, Ethernet shield, MySQL
I'm trying to connect my Arduino Uno with MySQL.

This is my code:

```
#include <SPI.h>
#include <Ethernet.h>
#include <sha1.h>
#include <mysql.h>

/* Setup for Ethernet Library */
byte mac_addr[] = { 0xC8, 0x0A, 0xA9, 0xAF, 0x83, 0x58 };
IPAddress server_addr(192,168,0,102);

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference
char user[] = "root";
char password[] = "fifa2005";
char INSERT_SQL[] = "INSERT INTO test_arduino.hello VALUES ('Hello from Arduino!', NULL)";

void setup() {
Ethernet.begin(mac_addr);
Serial.begin(115200);
delay(1000);
Serial.println("Connecting...");
if (my_conn.mysql_connect(server_addr, 3306, user, password))
delay(500);
else
Serial.println("Connection failed.");
}

void loop() {
}

```

I have the following database:

```
mysql> CREATE DATABASE test_arduino;
Query OK, 1 row affected (0.00 sec)
mysql> USE test_arduino;
Database changed
mysql> CREATE TABLE hello (source char(20), event_date timestamp);
Query OK, 0 rows affected (0.01 sec)

```

This is the output message:

```
Connecting... Connection failed.

```

I am not sure this is the right IP address: `192,168,0,102`. I tried with the localhost IP address - `127.0.0.1`, but nothing happened.

# Answer
> 1 votes
First you have to grant permission to the user!

Type the query in MySQL like:

```
GRANT ALL ON test_arduino.* TO root@'192.168.0.102' IDENTIFIED BY 'fifa2005';

```

# Answer
> 1 votes
Can't comment, so I put here. In your Arduino you shall use unique MAC address, that can't be same as in your laptop or any other node in network segment. And it can't be just any number because some bits have different meanings, so to be safe, use MAC from Ethernet shield samples (BTW in production units, MAC addresses have to be purchased, but unfortunately Ethernet shield comes without it).

127.0.0.1 is a "virtual" localhost address (alternative address used to access the services within same host), in your case you shall use MySQL server (your laptop?) host address, so

```
> server_addr(192,168,0,102);

```

is right.

---
Tags: arduino-uno, ethernet
---


# Question
Title: Cannot include .h files back one directory
I am working on a project with multiple arduinos. I want my folder structure to be as follows:

```
/
  libs/
    someSharedFile.h
  arduino1/
    arduino1.ino
  arduino2/
    arduino2.ino

```

When I include `someSharedFile.h` in one of my .ino files like this `#include "../libs/someSharedFile.h"`, I get this error `No such file or directory`.

However, when I move `libs/` to `arduino1` and include the shared file like this `#include "libs/someSharedFile.h"` everything works fine.

I am using IDE 1.6.7 on windows 10.

# Answer
Arduino IDE copies the files to a temp folder. You can see that when you compile in verbose mode.
As such the lib folder is not available.
You should place you libraries in \[your home folder\]/arduino/libraries
> 2 votes

---
Tags: library
---


# Question
Title: How to increase the brightness of a IR transmitter LED?
I have a pair of IR transmitters and receivers, but I have found that the brightness of the transmitter is very low, so that I can't use it to detect an object in front of them.

What should I do?

# Answer
> 1 votes
IR transmitter LEDs are literally just LEDs that emits Infrared Light which is not visible to the human eye. That being said, IR LEDs behave very similarly to regular LEDs and therefore to increase the brightness you need to increase the Voltage it is receiving, just like you would do with a regular LED.

But the problem with LEDs is that they drain current and that's why we use resistors,to protect our electronics(i.e. Arduino).

So to recieve maximum voltage you can reduce the resistance of the resistor (let's say 220ohm or even 100ohm).

Forgot to mention that the correct wiring of LEDs to an arduino is as follows:

5V pin(or digital pin set to high) -\> Anode leg(longer) of LED -\> Resistor(connected to shorter leg :3) -\> ground pin

# Answer
> 0 votes
If you aren't at the current limit of either the IO pin (40mA) or the LED (usually around 30mA) you can increase the current as far as the lower of those. That can be done by reducing the value of the resistor you are using with the LED or using a higher current drive circuit.

However, just having an LED turned on all the time is not a good way of using it - you are constantly fighting against the background light.

Instead the LED needs to be pulsed on and off using PWM at a very high frequency (typically 30-50kHz) and you need to detect that pulsed light with the receiver.

This is usually achieved by using a high-pass (or band pass) filter and amplifier on the receiver.

---
Tags: ir
---


# Question
Title: How do I transfer more than 1 byte at once via SPI bus?
I have an AD5685R DAC that I am trying to communicate with over SPI. Per the datasheet,

> ...These \[24\] bits are transferred to the input register on the 24 falling edges of `SCLK` and are updated on the rising edge of `/SYNC`

where `/SYNC` is used as chip-select.

I believe Arduino's `SPI.transfer` waits to receive 8 bits after sending 8 bits. But for this particular DAC, I need to send 24 straight bits on 24 clock edges before releasing the chip-select. Is this possible?

# Answer
> 11 votes
> I believe Arduino's `SPI.transfer` waits to receive 8 bits after sending 8 bits.

Incorrect. With SPI, a byte is clocked in *at the same time* as a byte is clocked out. It may be that this byte is simply a dummy byte though, if the slave has nothing to say.

So for 24 bits, simply clock out 3 bytes without deasserting the select. Since SPI is a synchronous protocol there should be no issue with having a delay in between bytes provided the select is maintained.

# Answer
> 7 votes
In the SPI protocol, you get one byte back for every one you send. If you are not interested in the response from a device, you can just ignore the return bytes.

SPI has no handshaking. You just must send no faster than the slave device can handle. In the case of the AD5685R, that is 50 MHz.

For multibyte transfer, you keep the chip select asserted (low) between every byte by setting the transferMode to SPI\_CONTINUE in the SPI.transfer call. For the last byte, you will deassert the chip select (set it high) by setting the transferMode parameter to SPI\_LAST in the SPI.transfer call..

# Answer
> 7 votes
Note that there is also a version of `SPI.transfer` for multi-byte (buffer) transfers:

```
SPI.transfer(buffer, size)

```

I used the buffer transfer in my library for the TLC59711 (see code) and found the buffer transfer faster than transferring bytes individually using `SPI.transfer(val)`; the switch to buffer transfers is *one* of the reasons my library is about 3.5 times faster than a previous library for the TLC59711.

# Answer
> 4 votes
Looks like it just set cs low and do three byte transfers then bring it high. Here's someone's example on how to do it:

http://www.reigndesign.com/blog/controlling-a-10-bit-digital-potentiometer-via-spi-with-arduino/

Code below taken from above page.

```
#include <SPI.h>

const int csPin = 10;

void setup() {

 SPI.begin();
 SPI.setBitOrder(MSBFIRST); //We know this from the Data Sheet

 pinMode(csPin,OUTPUT);
 digitalWrite(csPin, HIGH);
}

void loop() {
 for(int i=0; i<1023; i++) {
  digitalPotWrite(0,i);
  delay(10);
 }
}

void digitalPotWrite(int address, int value) {
 digitalWrite(csPin, LOW); //select slave
 byte command = 0xB0; //0xB0 = 10110000
 command += address;
 SPI.transfer(command);
 byte byte1 = (value >> 8);
 byte byte0 = (value & 0xFF); //0xFF = B11111111
 SPI.transfer(byte1);
 SPI.transfer(byte0);
 digitalWrite(csPin, HIGH); //de-select slave
}

```

---
Tags: spi
---


title: How do I connect this to my breadboard?

text:
# Question
Title: How do I connect this to my breadboard?
I just purchased this Grove RTC. It includes a cable presumably to connect it to a breadboard and/or Arduino, but the pin holes on this cable are much smaller than those on a breadboard or Arduino.

How/where would I connect this in the case of using an Arduino Uno?

# Answer
Either use jumper wire, or pull the connectors from the Housing and connect them with male connectors.
> 0 votes

---
Tags: arduino-uno, rtc
---


title: Rotary Encoder problem with LCD Display

text:
# Question
Title: Rotary Encoder problem with LCD Display
Program reads rotary encoder correctly without bouncing in this code:

```
int val = 0;
byte clkPin = 3;
byte dtPin = 2;
bool lastClk;
bool lastDt;
void setup() {
  pinMode(clkPin,INPUT);
  pinMode(dtPin,INPUT);
  lastClk = digitalRead(3);
  lastDt = digitalRead(2);
  val = 0;
  attachInterrupt(digitalPinToInterrupt(clkPin), clkRise, RISING);
  Serial.begin(9600);
}

void loop() {
}

void clkRise(){
      lastClk = HIGH;
      lastDt = digitalRead(dtPin);
      if(lastDt == LOW){
        val--;
        Serial.println(val);
        }  else{val++; Serial.println(val);}
        }

```

but when i use lcd to show the result, i get massive bounces (i think) in this code:

```
#include <LiquidCrystal_I2C.h>

#include <Wire.h>

LiquidCrystal_I2C lcd(0x27,20,4);
int val = 0;
byte clkPin = 3;
byte dtPin = 2;
bool lastClk;
bool lastDt;
void setup() {
  lcd.begin();
  pinMode(clkPin,INPUT);
  pinMode(dtPin,INPUT);
  lastClk = digitalRead(3);
  lastDt = digitalRead(2);
  val = 0;
  attachInterrupt(digitalPinToInterrupt(clkPin), clkRise, RISING);
  Serial.begin(9600);
  lcd.home();
}

void loop() {
  lcd.print(val);
}

void clkRise(){
      lastClk = HIGH;
      lastDt = digitalRead(dtPin);
      if(lastDt == LOW){
        val--;
        Serial.println(val);
        }  else{val++;}
        }

```

it increases and decreases by random numbers between 0-5.I use KY-040 R.E. it has built-in 10k pull up resistors.

This is what i use to debounce:

```
A or B pin of R.E--10k R----------------------------------Arduino INPUT PIN
                         |
                         |
                         =0.1uF C
                         |
                         ---------------------GND

```

# Answer
I suspect the problem is that your hardware-debounce capacitive circuit isn't working well enough to accurately debounce the contacts, and that invalid transitions are occurring on the quadrature lines as read by the program.

Note that use of `Serial.println()` within your `clkRise()` interrupt handler is problematic, because `Serial.println()` uses interrupts itself. As far as I know, `println()` is not reentrant, ie cannot be used correctly from the multiple interrupts that may start before previous `println()` calls finish their background processing. The bits of extra delay introduced by LCD code may merely be exposing a problem.

There is no need for either hardware or software debouncing on quadrature inputs. A correctly-implemented state machine will reject invalid conditions that arise during bounce, or will immediately follow any extra up-tick by a corresponding down-tick, or vice versa.

For some state machine code, see for example answer 16420/3917 and also see answer 18221/3917. Also see answer 19109/3917.
> 0 votes

---
Tags: lcd, rotary-encoder, debounce
---


title: How to control Adruino through Internet

text:
# Question
Title: How to control Adruino through Internet
I want to control my Adruino through Internet without Ethernet or wifi shield. So what are the ways I can do?

# Answer
Guess you need to use a pc, and a program to receive commands and send them along to the arduino by serial.
> 0 votes

# Answer
You need access to the Internet. Since you dont want to use an Ethernet or WiFi shield/module, then, for the most part, you are left with:

* Using a GSM module with the Arduino to receive data over the Internet
* Using a PC as a web server to receive data over the internet and forward it to the Arduino over a wired connection (UART) or a wireless connection (e.g. bluetooth)

The most direct would be the second method over UART. So it could be seen like this: `Client/Sending PC -> Over the Internet -> Server/Receiving PC -> Over UART -> Arduino`. So you are now faced with 3 main interfaces: `Internet->PC` for the server and client as well as the `PC->Arduino` interface on the server/receiver side.

To handle the `Internet -> PC` interface for the client, the client PC would need to run a program that will connect to the server PC over the Internet (using the server's public IP) and send the Arduino control data. Similarly, the `Internet-PC` interface for the server PC would require a constantly-running server program that will listen for incoming connections from the client PC and receive the data being sent. Assuming you know Python, with Python you can have both programs up and running within minutes. This site should help with the programs.

Note that port forwarding will need to be implemented on the router on the server side so that packets from outside its local network can get to it, given that its behind a router. This software can help with setting port forwarding rules.

The `PC->Arduino` interface will require the `pyserial` package (if you're still using Python). Pyserial can be used to forward the control data received over the internet, to the Arduino over Serial UART. This site should help with using Pyserial for Python 3. Search for other tutorials.

Finally, the Arduino itself must regularly check the Serial buffer for any received characters from the PC. It must then act on the received data, depending on rules you should have established. A simple example would be: 'a' = Write HIGH to pin 13. This means if ASCII char 'a' were received over Serial, the Arduino would interpret this to mean a command to `digitalWrite(13, HIGH)`. You can make use of the built-in `serialEvent()` to regularly poll the serial buffer. A simple sketch to illustrate this:

```
void setup(){
  pinMode(13, OUTPUT);
  Serial.begin(9600);
}

void loop(){}

void serialEvent(){
  if (Serial.read() == 'a')
    digitalwrite(13, HIGH);
  else  //any other character turns off the LED
    digitalWrite(13, LOW);
}

```

This is, by no means, the only way to do this, only very straightforward IMO. For example, you could also upload your control data to some cheap server and have your PC regularly poll that server for any new commands. Of course, this would be greatly simplified if you decided to use a WiFi module, like the cheap ESP-01, directly with the Arduino.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Posting Arduino data via ethernet to PHP server problems
I am currently having difficulties sending data from an Arduino using an ethernet shield to a PHP database in MySQL. My problem is that it appears that the server is receiving the data as there is a time stamp when I send it from the Arduino however, the other values it is receiving are incorrect (see images below). The server says the values of "data", and "serial\_number" are 0 but they are supposed to be 10 and 24. Along with that the Arduino is saying that the data has been sent successfully. My code for both the server and the Arduino is listed below. Any ideas on how to fix this or what is going on are much appreciated.

**Arduino Code:**

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

byte mac[] = { 0x00, 0xAB, 0xBA, 0xBC, 0xDD, 0x02 };
EthernetClient client;
String data;
int t;
int h;

void setup() {
  Serial.begin(9600);
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
  }

  Serial.println("still working here");

}

void loop() {
t = 10;
h = 24;

data = "temp1=";

data.concat(t);

data.concat("&hum1=");

data.concat(h);

  if (client.connect("www.smartwater.x10host.com",80)) {
    Serial.println(data);
    client.print("POST /add.php HTTP/1.1\n");
    client.print("Host: www.smartwater.x10host.com\n");
    client.print("Connection: close\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(data.length());
    client.print("\n\n");
    client.print(data);
    Serial.println("Successfull");

  }

  if (client.connected()) {
    client.stop();
  }

  delay(20000);
}

```

**add.php (Server Code)**

```
<?php
    include("connect.php");

    $link=Connection();

    $temp1=$_POST["data"];
    $hum1=$_POST["serial_number"];

    $query = "INSERT INTO `Main` (`data`, `serial_number`)
        VALUES ('".$temp1."','".$hum1."')";

    mysql_query($query,$link);
    mysql_close($link);

    header("Location: index.php");
?>

```

**connect.php (Server Code)**

```
<?php

    function Connection(){
        $server="localhost";
        $user="smartwat_arduino";
        $pass="*****";
        $db="smartwat_Main";

        $connection = mysql_connect($server, $user, $pass);

        if (!$connection) {
            die('MySQL ERROR: ' . mysql_error());
        }

        mysql_select_db($db) or die( 'MySQL ERROR: '. mysql_error() );

        return $connection;
    }
?>

```

**index.php (Server Code)**

```
<?php

    include("connect.php");

    $link=Connection();

    $result=mysql_query("SELECT * FROM `Main` ORDER BY `timeStamp` DESC",$link);
?>

<html>
   <head>
      <title>Data</title>
   </head>
<body>
   <h1>Stuff</h1>

   <table border="1" cellspacing="1" cellpadding="1">
        <tr>
            <td> Timestamp </td>
            <td> Data </td>
            <td> Serial Number </td>

        </tr>

      <?php
          if($result!==FALSE){
             while($row = mysql_fetch_array($result)) {
                printf("<tr><td>  %s </td><td>  %s  </td><td>  %s  </td></tr>",
                   $row["timeStamp"], $row["data"], $row["serial_number"]);
             }
             mysql_free_result($result);
             mysql_close();
          }
      ?>

   </table>
</body>
</html>

```

# Answer
> 1 votes
In your Arduino code, the function call that send the real data within the HTTP-POST call, is this:

```
[...]
client.print(data);
[...]

```

When executed, the content of the `data` variable is sent to the server.

Supposing `data` is a `String` object then `data.concat()` is this function, allowing "*... String, string, char, byte, **int**, unsigned int, long, unsigned long, float, double...*" as argument.

So, after the execution, `data` should contain:

`temp1=10&hum1=24`

and such content is exactly what is passed, via `POST` to the `/add.php` script.

Basically, you're passing two variables, called "**temp1**" and "**hum1**". **Please keep note of those variable names**!

Now let's switch the the PHP script, where you have:

```
[...]
$temp1=$_POST["data"];
$hum1=$_POST["serial_number"];
[...]

```

Above two statements, asks PHP to retrieve, via the `$_POST` function, the content of the two variables **data** and **serial\_number**.

As such variables are **undefined** (the variables you passed were `temp1` and `hum1`), PHP consider them like `0` and, as such, assign 0 to `$temp1` and `$hum1`.

I bet that to solve your problem you only need to change above PHP with:

```
[...]
$temp1=$_POST["temp1"];
$hum1=$_POST["hum1"];
[...]

```

*BTW: please note that what is inside the $\_POST call is totally unrelated with the names of the variables you have on the left of the `=` sign: they are really different things!*

# Answer
> 0 votes
Data = 10 is not the characters making 1 and 0 but an ascii character with value 10, your php script doesn't understand that. Try using itoa function to make character array 1 and 0 for your php to understand.

# Answer
> 0 votes
You get a timestamp from running the php file. That doest mean that there is a number in $data or $serialnmber. What happens if you fill in a value in your php file instead of the variables $data and serialnumber. If the dbase gets filled, you know that than your variables were empty. If they arent filled something is wrong in your php coding

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


# Question
Title: MQTT broker and Arduino + Sensors NRF24L01
I am newbie, I have never used MQTT before, so I have some questions. Here is my topology.

I have several sensors (Arduino Pro Mini + NRF24L01) and main server/handler(Arduino Mega + Ethernet Shield or ESP module) to receive/send messages to/from sensor nodes, so all network is build on NRF24L01 (NRF24 Mesh library). But I need to be able to communicate with all these sensors from outside over the internet. Previously I implemented simple socket communication.
I have recently discovered MQTT protocol and it is awesome. I want to implement communication between main server and outside world using it.

1. What part of my topology should implement broker in? I think it should be on the main server (Arduino Mega) but again communication between main server/master server is implemented via NRF24L01 modules and custom protocol.
2. Or in my case is better to use HTTP communication with master server?

Please explain this topic and suggest how to implement this correctly in my case.

# Answer
> 1 votes
The normal topology is sensor nodes publishing topic-data on a MQTT broker. And the broker distributing updates to subscribing clients. The MQTT broker is responsible for several levels of QoS (Quality of Service) such as storing attribute/topic-values (persistence), checking that messages are delivered, etc. Typically the broker runs on a server with disk, multiple network connections, etc.

A possible solution is to send sensor messages to a bridge that translates and publishes the message on the MQTT broker. The sensors may use a simple cheap local wireless network (such as based on NRF24L01) and the bridge would publish over IP (Ethernet, WiFi, etc) to the MQTT broker.

Some sensors/actuators might need configuration/control (alarm thresholds, resolution, etc). In this case they need to subscribe to messages (topic updates) from the MQTT broker. Again the bridge needs to provide the subscription and message translation/routing back to the sensor.

Last, topics naming is a challenge as the bridge should be transparent in the naming structure but still configurable. The bridge configuration (e.g. network address/topic translation) could also be handled as a bridge topic.

Cheers!

# Answer
> -1 votes
You can use a Raspberry Pi as your MQTT server and you can also connect a nRF24L01+ module.

---
Tags: arduino-mega, sensors, ethernet, arduino-pro-mini
---


# Question
Title: Writing and reading multiple values through serial
I am currently busy with a project that requires me to use an Arduino and 3 potentiometers (to change background in RGB format) to write values through the serial port and read and separate them in processing.

What I want to do is to be able to use my Arduino to write multiple values to a processing program. I am quite new to coding and its been a while since I worked with my Arduino. I know how to read and write one value, but not multiple values.

Also is there a way to write 20 values?

Thanks in advance!

# Answer
The simplest way is to just print them as a single line and separate them with "something". That "something" could be as simple as a space.

```
Serial.print(val1);
Serial.print(" ");
Serial.print(val2);
...
Serial.print(" ");
Serial.println(val20);

743 234 34 599 2 ... 427 1013 48 2 409

```

Then in processing you just read the entire line into a String and split it on the spaces into an array.
> 0 votes

---
Tags: serial, processing-lang
---


# Question
Title: Arduino water pump not working and beeping
I’m new to Arduino and am trying to build a plant watering system without much knowledge on the subject. But my water pump is not working as I expected it to.

I wanted to keep it simple so I bought a Arduino Motor Shield for my Arduino Uno R3. I’m using a motor rated at 3-9V (motor is shown below), I’ve tried two different DC adaptors plugged into the power supply port on the arduino, 12V 1.5A and 12V 2A, even though the motor is rated at 9V, I’ve read that I need a 12V adapter to power the motor shield. http://www.mabuchi-motor.co.jp/cgi-bin/catalog/e\_catalog.cgi?CAT\_ID=rs\_360sh

The first problem is If I run the motor at full speed, `analogWrite(3, 255)`, it sounds like its going to explode, so I’m trying to run it at a lower speed. But If use values anywhere below 170 the motor will not run and will only make a beeping sound.

Secondly, regardless of the PWM value I run the motor at, the chip gets very hot very quickly.

My question is, why can’t I run the pump at lower PWM values, and why is it getting so hot? If I bought a 12V water pump and used the same setup, would I not have any of these problems?

EDIT: an update... it seems to basically work now. i have a feeling it wasn't working great because I was previously using a powerbar

It will run on max power PWM(255) for about a minute, and then stop working, which is okay. It will stop and then the motor shield lights will start blinking. Does anybody have any guesses what is happening? The motorshield chip is a little hot, so overheating is a possibility. Or is there not enough current ?

video https://www.youtube.com/watch?v=xdxf3f\_Svqs

```
void setup() {

//  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin
}

void loop(){
  //forward @ full speed, A
  digitalWrite(12, HIGH); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 170);   //Spins the motor on Channel A at a speed. approx 90 is min

  delay(3000);

  digitalWrite(9, HIGH); //Engage the Brake for Channel A

  delay(1000);

}

```

# Answer
> 2 votes
Regarding your motor just making high pitched noise (beeping) I would say that you are not supplying enough power to your motor for it to pull in the load and get rotating, you might try to first get it started by a higher power setting (PWM) and then when it's running see how far down you can set it before it stalls (stops).

I don't belive a 12V pump would work any different.

As to the motor and L298 chip getting hot, this is sort of normal and in some cases would require som way of dissipating this heat. A heatsink might be an option.

If you were to overheat the L298 it will shut down before being destroyed (it should).

---
Tags: arduino-uno, motor, pwm, arduino-motor-shield
---


# Question
Title: nRF24L01+ RF24 library - can send but can't receive
I'm prototyping out a board with temperature, humidity, windspeed sensors, and using an NRF2401+ board to send values to a Raspberry Pi base station that will record the data.

Using a Leonardo clone board, I'm able to successfully run the *pingair\_dyn* sketch to send test payloads to the RPi and receive acks. (So I know the RPi can send and recieve OK.)

Moving the same NRF2401+ to a breadboard setup with an ATMEGA328P-PU, the same sketch **can send** payloads which are received on the RPi, but **always hits the timeout** trying to get the ack (which the RPi is dutifully sending).

In fact when running pingair\_dyn as a receiver, it just spins in the loop waiting for radio.available() to return true, which it never does.

The immediate problem is that **radio.available() is always returning false**. So basically I can send but can't receive.

I have checked my wiring several times, and I'm mostly confident that it's right.

> * CE - physical pin 14 (arduino digital pin 8 )
> * CSN - physical pin 13 (arduino digital pin 7)
> * SCK - physical pin 19, per atmega328 datasheet
> * MOSI - physical pin 17, per datasheet
> * MISO - physical pin 18, per datasheet

In the software, I construct the RF24 instance:

> RF24 radio(8,7);

Any ideas? I tried swapping CE \<--\> CSN, then nothing worked. Is there some wiring problem that would cause XMIT to work but RECV to fail?

I've tried putting a 2.2 uF capacitor across the 3.3V - GND as I've seen mentioned in other threads, but no difference.

Any suggestions on what is useful information to dig out of the RF24 library to give some idea of what's going on?

More background

Here is the RF24 debug info from the mega328

```
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1    = 0xf0f0f0f0d2 0xf0f0f0f0e1
RX_ADDR_P2-5    = 0xc3 0xc4 0xc5 0xc6
TX_ADDR       = 0xf0f0f0f0d2
RX_PW_P0-6    = 0x20 0x20 0x00 0x00 0x00 0x00
EN_AA       = 0x3f
EN_RXADDR    = 0x02
RF_CH      = 0x4c
RF_SETUP    = 0x07
CONFIG       = 0x0f
DYNPD/FEATURE    = 0x3f 0x04
Data Rate    = 1 MBPS
Model       = nRF24L01+
CRC Length    = 16 bits
PA Power    = PA_MAX

```

Here is the debug info from the base station (Raspberry Pi): pyRF24/examples/pingpair\_dyn/

```
================ SPI Configuration ================
CSN Pin          = CE0 (PI Hardware Driven)
CE Pin           = Custom GPIO22
Clock Speed      = 8 Mhz
================ NRF Configuration ================
STATUS           = 0x0e RX_DR=0 TX_DS=0
MAX_RT=0 RX_P_NO=7     TX_FULL=0         RX_ADDR_P0-1     =
0xe7e7e7e7e7 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR          = 0xe7e7e7e7e7
RX_PW_P0-6       = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA            = 0x3f
EN_RXADDR        = 0x03
RF_CH            = 0x4c
RF_SETUP         = 0x07
CONFIG           = 0x0e
DYNPD/FEATURE    = 0x3f 0x04
Data Rate        = 1MBPS
Model            = nRF24L01+
CRC Length       = 16 bits
PA Power         = PA_MAX

```

# Answer
> 2 votes
The pins could be wrong for ATMega328.

It should be.

NRF24L01 - Arduino UNO
GND - GND
VCC - 3.3V
CE - 7
CSN - 8
SCK - 13
MOSI - 11
MISO - 12

or B. You need to connect a 500uF electrolytic capacitor to your NRF24L01+ VCC and GND pins directly. To reduce noise related issues. With clone arduinos/cheap regulators/clone NRFs then noise might start creating issues especially with receiving.

# Answer
> 2 votes
FWIW, I had packet loss issues using these boards, until I introduced those 3.3 V piggy back boards to supply current. I use them on both RX and TX now, but experimentation showed that the RX was where it made the crucial difference. Omitting the filter cap also didn't make any difference.

I don't know why these 5 V to 3.3 V piggy back boards were so effective; they're just a regulator. Maybe they've got better quality specs, or their own on board filter caps have a better frequency range for driving the nRF.

They only cost about a $, and save so much agro.

# Answer
> -1 votes
have a look at https://github.com/TMRh20 he's done some great work on the nrf24 radios and has code allowing connection between arduinos and pi's.

Oh and while i've played with non ip addressed data transfer a bit it wasn't the main focus of my research, but shouldn't the tx addresses be matched up?

also you mention a 2.2uf cap on the 3.3v line, but what is supplying the 3.3v line on the arduino side? iirc the pi will supply enough current on its 3.3v line to supply the radio (i remember it working well enough) and i don't know what voltage your running the MEGA at, 3.3v or 5v with level shifters, either way i would imagine your power supply would be sufficient. Unless your running the mega at 16mhz and on a 3.3v (to be stable needs ~4.1v https://electronics.stackexchange.com/questions/58818/programming-3-3v-atmega328-running-at-16mhz) Also iirc most nrf24's are happy enough with 5v logic level, although there are plenty of clones out there, you'll have to do your own testing.

And if you have one to hand would suggest starting off with a non breadboard arduino, get it to work before moving onto the breadboard... there is less that could go wrong :)

---
Tags: atmega328, nrf24l01+
---


title: Using Lua in Arduino project

text:
# Question
Title: Using Lua in Arduino project
I want to write code for my Arduino in Lua. Where I can find the necessary (pins) I/O lib and examples for Arduino IDE?
UPD: I've got arduino mega with many memory.

# Answer
Lua is an interpreted language. That is, the compile phase turns Lua source code into intermediate "pseudo-code" which the Lua interpreter then runs. It doesn't compile into machine code, and therefore there is nothing that could be uploaded to your Uno as a "hex" file.

In any case, with only 2 KB of RAM, it wouldn't be very practical to attempt to run Lua on a Uno. I like Lua personally, but running it on the (AVR) Arduinos just isn't practical.
> 1 votes

# Answer
AFAIK, Arduino IDE supports C++ only. You can use other languages to communicate with Arduino from your PC. Take a look at Firmata.
> 0 votes

---
Tags: lua
---


title: RS485: is "Y" multidrop allowed?

text:
# Question
Title: RS485: is "Y" multidrop allowed?
I imagine that the proper way to implement an RS485 multidrop bus is the following:

What happens if, in order to save cables, I connect the same 5 nodes above using this other topology?

* Will it works?
* If no, why?
* If "maybe", under which circumstances will it work?

---

*P.S.: yes! I know that MEGA has three Serials and, as such, I could implement two different BUSses (1: Mega\<-\>Mega\<-\>Mega; 2: Mega\<-\>Nano\<-\>Nano), but this will increase the complexity of the software I'm running, as it needs some hacking in order to play nicely with two distinct RS-485 busses;*

*P.P.S.: This is the bus discussed in this other question*

# Answer
At low speeds and short distances that won't be a problem.

At high speeds (megabits per second) and long distances (hundreds of meters) you may get reflections unless you get the termination just right.
> 2 votes

---
Tags: rs485
---


title: Controlling HDMI Switch via RS232/UART

text:
# Question
Title: Controlling HDMI Switch via RS232/UART
Problem:

I have an HDMI switch that is controllable via RS232

* Scenario 1:
    + Setup: PC connected to HDMI switch using USB -\> serial adapter
    + Test: Opening PuTTY on COM port and sending command "sw i01" from my PC
    + Results: HDMI switch input changes to port 1 \[Good\]
* Scenario 2:
    + Setup: Arduino UART port connected to TTL-\>RS232 adapter connected to serial-\>USB adapter connected to PC with PuTTY program open on COM port
    + Test: Sending command "sw i01" from Arduino to PC using code below
    + Results: "sw i01" prints repeatedly on the Putty terminal \[Good\]
* Scenario 3:
    + Setup: Arduino UART port connected to TTL-\>RS232 adapter connected to HDMI switch serial port
    + Test: Sending "sw i01" from Arduino repeatedly to HDMI switch using code below
    + Results: HDMI port does not switch from port2 to port1 \[Bad\]

Hardware:

Code:

\[Note: Galileo Gen 2 requires Serial1 for UART communication\]

```
void setup() {
    Serial1.begin(19200);
}

void loop() {
    Serial1.print("sw i01");
    Serial1.write(13);    // CR
    Serial1.write(10);    // LF
    delay(1000);
}

```

Question:

It seems like Scenario 1 and 2 confirm that the Arduino-\>HDMI switch communication should work, but it doesn't. Am I missing something regarding physical connectivity? Does manually typing "sw i01" in PuTTY send different commands than I have in the Arduino code?

# Answer
> 0 votes
I found it is was related to the physical connection!

In Scenario 3, I originally had the Sparkfun TTL/RS232 adapter that had a female DB9 connector wired to the HDMI switch female DB9 connector using a male/male serial cable. The serial cable I bought was a straight through cable.

I swapped it out with a null modem cable and it worked right away.

Looking at the wiring diagram, I thought swapping the Tx/Rx pins on the Sparkfun adapter would have achieved the same result as the null modem cable, but apparently not.

If anybody can point out why the null modem cable made the difference, that would be something good to know for the future.

# Answer
> 1 votes
Your HDMI switcher, and your USB to RS-232 converter speak RS-232. The Arduino speaks TTL UART.

While the concept behind them, and the overall format of the data, is the same there are major differences:

* RS-232 uses a ±10V NRZ signalling method, TTL UART uses a 0-5V signalling method
* RS-232 uses inverse logic compared to TTL UART

That means that you need to convert the Arduino's TTL UART to ±10V NRZ with inverse logic in order to communicate with the IOGear.

Fortunately that's a simple enough task using a special interface chip. These are readily available and can be bought for tiny amounts as a breakout board or even a full shield if you like (such as this one from Sparkfun). The chip is known as a **MAX232** in its most common form, though other manufacturers may use different letters.

If you pop on eBay (or your favourite budget seller site) and search for "Arduino MAX232 DB9" (the DB9 is the type of plug on the board - the 9-pin D connector) you will get lots of hits to choose from.

---
Tags: serial, uart, arduino-galileo, rs232
---


title: Multiplexing potentiometers

text:
# Question
Title: Multiplexing potentiometers
Is it possible to have two rotary potentiometers read from a single analog input pin?

The analog input is 10 bits (0-1023), so each pot would have 5 bit precision (0-15).

Least significant bits for pot 1 and most significant bits for pot 2.

A SPI/I2C ADC IC (eg. MCP3008) is an option if this is not possible.

**Edit:**

The two pots do not need to be read at the same time. It seems full 10 bit precision could be achieved if I use a digital pin to enable each pot before it is read.

# Answer
> 4 votes
There are a few ways of doing what you want. One would be to use an analog multiplexer as in this answer: Expanding analog inputs to the Arduino

Another would be to use digital I/O pins to control the power and ground to the potentiometers. Note that both sides of the pot need to be controlled, not just one, since any connection of one will interfere with the other.

So you will need four IO pins - one for the +5v and one for the GND of each potentiometer.

In this example set D3 to OUTPUT and HIGH, D4 to OUTPUT and LOW, and D5 and D6 both to INPUT. You will now be reading from the top pot.

Then change D3 and D4 to both be INPUT, and D5 to be OUTPUT and HIGH and D6 to be OUTPUT and LOW. You will then be reading from the bottom pot.

A bit wasteful of IO pins though.

# Answer
> 2 votes
Building on @Majenko's answer, I think you could do the same thing, using 1 analog pin (as shown in his answer) and one digital pin.

Rather than using one digital pin for each side of the each pot, you could use one transistor for each side of each pot, and then use one digital pin to switch all 4 transistors on/off at the same time, in the right combination.

---
Tags: potentiometer, adc
---


title: Stuck on uploading sketch via USB 6 pin

text:
# Question
Title: Stuck on uploading sketch via USB 6 pin
I'm just got a Galileo Gen2 and wanted to try a simple blinking-led. The firmware have been updated to 1.0.4. My problem is whenever I try to upload the code I get this error:

```
Sketch uses 83,775 bytes (0%) of program storage space. Maximum is 10,000,000 bytes.
...
echo "Sending Command String to move to download if not already in download mode"
echo "~sketch downloadGalileo" > $tty_port_id

Deleting existing sketch on target
#Move the existing sketch on target.
echo "Deleting existing sketch on target"
"$fixed_path/lsz.exe" --escape -c "mv -f /sketch/sketch.elf /sketch/sketch.elf.old" <> $tty_port_id 1>&0
Login timed out after 60 secondsPoky 9.0.2 (Yocto Project 1.4 Reference Distro) 1.4.2 clanton /dev/ttyS1clanton login:`

```

# Answer
The answer was simply that 6-pin are not designed for uploading sketches. Instead use the micro-USB port to upload sketches.
> 0 votes

---
Tags: sketch, uploading, arduino-galileo
---


# Question
Title: Safe to control multiple power sources through a switch through the ground?
I've attached the breadboard layout and schematic of a circuit I'm constructing, which is a simple Arduino radio control car, with a 9V powering the Arduino Uno, and the 6 volt battery pack feeding power to the motors via the L293D. My question is regarding the switch where I've connected the ground from both battery power supplies to one side, and connected the ground of the circuit to the other side. Is this OK and safe to do? Is there anything I should be concerned about with this setup? Is there a safer or better way to do this? What components added or removed (if any) would improve this circuit in terms of power safety and battery longevity?

In case you are wondering why I have two switches, the reason is because I wanted to debug the radio receiver using the serial monitor when I wired this to USB, but I also wanted to prevent it from powering up the motors so my project doesn't try and roll away while it's still connected to the USB cable. The switch I'm asking about in my question is sort of a mains power switch, so when it's off USB I can just flip on both switches and set the robot car free...

# Answer
You have the grounds of the batteries permanently connected together, so opening the switch won't remove them from the circuit altogether: it will leave a potential difference of 3v between the Arduino's power input at the L293's power input.

That would be exactly equivalent to having a 3v battery with its +ve terminal connected to the Arduino power input, and its -ve connected to the L293's power input, with their grounds connected together - so they're sort of wired in series, with one of them backwards, with a far-too-small supply voltage.

I *suspect* it won't kill anything but I would imagine it would drain the batteries and probably isn't what you want to do.
> 1 votes

---
Tags: arduino-uno, power, motor, battery
---


# Question
Title: Interfacing 9-Axes Motion Shield with RPi and WiFi Shield
I recently purchased the Arduino 9-Axes Motion Shield. I have two questions:

Q1. The official Arduino page says that the shield doesn't have any external power source and can only be powered up by stacking on top of an Arduino board. How can I use this shield with a Raspberry Pi?

Q2. A page here shows that it has support for the Ethernet Shield but doesn't mention WiFi shield anywhere. Does this mean that I cannot use my WiFi shield with it? I plan to stack the 9-axes shield on top of the WiFi shield which in turn is stacked over Arduino Uno.

# Answer
> 1 votes
> Q1. The official Arduino page says that the shield doesn't have any external power source and can only be powered up by stacking on top of an Arduino board. How can I use this shield with a Raspberry Pi?

By providing the right power to the right pins.

> Q2. A page here shows that it has support for the Ethernet Shield but doesn't mention WiFi shield anywhere. Does this mean that I cannot use my WiFi shield with it? I plan to stack the 9-axes shield on top of the WiFi shield which in turn is stacked over Arduino Uno.

No, it says it is compatible with the *Arduino Ethernet* which is not a shield, it is an Arduino.

What other shields you can use it with depends on what pins those other shields use. Look at the schematics. Read the manuals. Do some leg-work.

---
Tags: sensors, wifi, ethernet
---


# Question
Title: Arduino sketch won't run until I open up GUI in processing
I am trying to make a human detection robot using D6T omron thermal sensor. However, I am facing some problem here. My Arduino Uno didn't run the sketches until I open up my GUI in processing. The tx/rx pin did not light up when I remove my USB serial cable from my PC and put in an external power supply to my arduino uno board. The tx/rx pin will only light up when I open my GUI in processing and everything works just fine.

I am trying to move my robot away from my PC. Therefore, it is a must for me to provide my board an external power supply but it just does not work. I am confused here. Fyi, it will be interfacing with my PC thru Xbee in the near future.

Ps: this is my final year project. Your effort will be much appreciated and credits will goes to you. Thanks guys!

Attached below is my code (Arduino sketch):

```
#define E_right 10
#define E_left 11

int RightMotorForward = 9; // Pin 10 has Left Motor connected on Arduino boards.
int RightMotorReverse = 8; // Pin 9 has Left Motor connected on Arduino boards.

int LeftMotorForward = 12; // Pin 12 has Right Motor connected on Arduino boards.
int LeftMotorReverse = 13; // Pin 13 has Right Motor connected on Arduino boards.

float top_sum, bottom_sum, left_sum, right_sum, center_row_sum;

#include <Wire.h>
#include <WireExt.h>

#define D6T_addr 0x0A
#define D6T_cmd 0x4C

int rbuf[35];
float tdata[16];
float t_PTAT;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  Serial.flush();
  pinMode(E_right, OUTPUT);
  pinMode(E_left, OUTPUT);
  pinMode(LeftMotorForward, OUTPUT);  // initialize the  pin as an output.
  pinMode(RightMotorForward, OUTPUT);  // initialize the  pin as an output.
  pinMode(LeftMotorReverse, OUTPUT);  // initialize the  pin as an output.
  pinMode(RightMotorReverse, OUTPUT);  // initialize the  pin as an output.
}
//-----------------------------------------------------------------------------

// The following Loop is to make the Robot move towards heat source.
void loop()
{
int i;

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

      Wire.beginTransmission(D6T_addr);
      Wire.write(D6T_cmd);
      Wire.endTransmission();

      if (WireExt.beginReception(D6T_addr) >= 0) {
        i = 0;
        for (i = 0; i < 35; i++) {
          rbuf[i] = WireExt.get_byte();
        }
        WireExt.endReception();

        t_PTAT = (rbuf[0]+(rbuf[1]<<8))*0.1;
        for (i = 0; i < 16; i++) {
          tdata[i]=(rbuf[(i*2+2)]+(rbuf[(i*2+3)]<<8))*0.1;
        }

      }
    }
  }

top_sum= tdata[0] + tdata[1] + tdata[2] + tdata[3];
bottom_sum= tdata[12] + tdata[13] + tdata[14] + tdata[15];
right_sum= tdata[0]+ tdata[4] + tdata[8] + tdata[12];
left_sum= tdata[3] + tdata[7] + tdata[11] + tdata[15];
center_row_sum= tdata[1] + tdata[2] + tdata[5] + tdata[6] + tdata[9] + tdata[10] + tdata[13] + tdata[14];

if ((left_sum>center_sum)&& (center_sum>right_sum))
{
   analogWrite(E_right, 230);
   analogWrite(E_left, 205);

   digitalWrite(RightMotorForward, HIGH);   // turn the Right Motor ON
   digitalWrite(LeftMotorForward, LOW);   // turn the Left Motor OFF
                  // wait for  0.5 seconds
   delay(500);
   //turn left
}

else if ((right_sum>center_sum)&&(center_sum>left_sum))
{
   analogWrite(E_right, 230);
   analogWrite(E_left, 205);

   digitalWrite(RightMotorForward, LOW);   // turn the Right Motor OFF
   digitalWrite(LeftMotorForward, HIGH);   // turn the Left Motor ON
   // wait for  0.5 seconds
   delay(500);
   //turn right
}
else if ((center_row_sum>right_sum)&&(center_row_sum>left_sum))
{

   analogWrite(E_right, 230);
   analogWrite(E_left, 205);

   digitalWrite(RightMotorForward, HIGH);   // turn the Right Motor ON
   digitalWrite(LeftMotorForward, HIGH);   // turn the Left Motor ON
   delay(500); //forward

}

}

```

Attached below is my code in processing:

```
import processing.serial.*;

float[] tdata = new float[17];
float tptat; // PTAT
String portName;
//int serialport = 0;

String buf;
float colourGreen; //change green in relation to temperature

int lbTemp = 25; //lowest relative temperature
int hbTemp = 35; //highest relative temperature
Serial myPort;  // Create object from Serial class

void setup() {
  size(640,640);
  //println(Serial.list());
  //portName = Serial.list()[serialport];
  myPort = new Serial(this, "COM7", 9600);
  myPort.clear();

}
void draw() {
  myPort.write(0x01);
  delay(100);
  while (myPort.available() > 0) {
    delay(300);
    buf = myPort.readString();
    myPort.clear();
    tdata = float(split(buf, ','));
    for (int i = 0; i <16; i++) {
      colourGreen = map(tdata[i],lbTemp,hbTemp,255,0);
fill (255,colourGreen,0);

      if (i == 0)
    { rect(480,0,160,160);}
      else if (i == 1)
    { rect(320,0,160,160);}
      else if (i == 2)
    { rect(160,0,160,160);}
      else if (i == 3)
    { rect(0,0,160,160);}
      else if (i == 4)
    { rect(480,160,160,160);}
      else if (i == 5)
    { rect(320,160,160,160);}
      else if (i == 6)
    { rect(160,160,160,160);}
      else if (i == 7)
    { rect(0,160,160,160);}
      else if (i == 8)
    { rect(480,320,160,160);}
      else if (i == 9)
    { rect(320,320,160,160);}
      else if (i == 10)
    { rect(160,320,160,160);}
      else if (i == 11)
    { rect(0,320,160,160);}
      else if (i == 12)
    { rect(480,480,160,160);}
      else if (i == 13)
    { rect(320,480,160,160);}
      else if (i == 14)
    { rect(160,480,160,160);}
      else
    { rect(0,480,160,160); }

    if (tdata[i]<5) {fill(255);} else {fill(0);}
      if (i ==0)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),560, 80);}
      else if (i == 1)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),400, 80);
      }
      else if (i == 2)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 240, 80);
      }
      else if (i == 3)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),80, 80);
      }
      else if (i == 4)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 560, 240);
      }
      else if (i == 5)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 400, 240);
      }
      else if (i == 6)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 240, 240);
      }
      else if (i == 7)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 80, 240);
      }
      else if (i == 8)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 560, 400);
      }
      else if (i == 9)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 400, 400);
      }
      else if (i == 10)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 240, 400);
      }
      else if (i == 11)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 80, 400);
      }
      else if (i == 12)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 560, 560);
      }
      else if (i == 13)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 400, 560);
      }
      else if (i == 14)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 240, 560);
      }
      else
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 80, 560);
      }
    }
    delay(800);
  }
}

```

# Answer
> My Arduino Uno didn't run the sketches until I open up my GUI in processing.

How do you know?

> The tx/rx pin did not light up when I remove my USB serial cable from my PC and put in an external power supply to my arduino uno board.

That is because the TX/RX LEDs are linked to the USB interface chip. With no USB connection there can be no lights.

> The tx/rx pin will only light up when I open my GUI in processing and everything works just fine.

That is because there is USB communication.

Your sketch is running fine. However your sketch looks to be wrong. Major portions of it (i.e., the portion that does any detection at all) relies on serial data coming in. How can you have it working, in that case, if you disconnect the serial interface so that no data ever comes in?
> 1 votes

---
Tags: arduino-uno, i2c, processing-lang
---


title: Two voltage sources on the same circuit

text:
# Question
Title: Two voltage sources on the same circuit
I am looking to power a Trinket Pro 5V microcontroller using a 9V voltage source. I have logic running on this controller to gather the data from an accelerometer (powered off of the 5V pin on the controller) and output it to three strands of 21 RGB LEDs (https://www.adafruit.com/products/1655).

RGB LEDs cannot exceed a power source of 5V and after passing through the Trinket voltage regulator the 5V pin on the Trinket just does not have enough power for all three strands.

Please, advise on the appropriate hardware for this case. What is the maximum voltage that RGB LEDs can handle and how does the schematic look on the protoboard.

Thank you for your expertise.

# Answer
> 1 votes
First of all: 9V means that you are using a 9V "transistor" battery (like this), right?

If so it won't last very long: I suggest you to use a different approach (e.g. four AA batteries in series).

As for your question, I couldn't find the power consumption for these leds. Try to measure it yourself, setting the max brightness and white color. I think that, anyway, the max current for each LED should be 60mA (20mA for each color). This means that each strand absorbs 1.2A (quite a lot!).

This power requires you to use at least a switching regulator. I always used some small modules I found on ebay (they have a LM2596 IC, so just search LM2596 on ebay to find them). They are rated for 3A, so you should put at least two of them (1.2 * 3 strands = 3.6A \> 3A).

The connections are quite straightforward: the board has four pins: IN+, IN-, OUT+ and OUT-. IN+ of all the modules go to the positive terminal of the battery, IN- and OUT- of all the modules go to the common ground node (negative terminal of trinket, battery and leds), OUT+ is the 5V regulated output. Oh, by the way, they are adjustable modules, so BEFORE ATTACHING THE LEDS use a multimeter to set the correct voltage (if you attach the leds without regulating the voltage you can destroy them).

Since you will have a lot of current left on the second module, you can power the trinket from there (so you will not waste a lot of power).

One last thought: 9V batteries usually have a capacity of around 600mAh; if you use one of them with the switching modules and drain 4A from the 5V your battery will last 0.6Ah / 4A * 9/5 = 0.27h = 16 minutes; if you switch to 4 AA batteries (around 2000mAh) it will last 2Ah / 4A * 6/5 = 0.6h = 36 minutes. More than double (calculations made rounding up the power drained by 21 leds set at max brightness and white color)

# Answer
> 1 votes
According to the link you supply you might either receive the WS2812 or the SK6812, datasheet on Ws2812 claims you can supply up to 7V , but this is still less than 9V , the SK6812 is lacking in max voltage but says 5v typical.

If you still want to use the 9V supply you will need a extra voltage regulator.

A little math: each pixel can max draw 60mA, if you have 21 of them we multiply and get 1260mA, thats 1.26 Amps but thats max values we might divide by two and still be relative safe. Let's not. So we need a 1.26A source from 9V to 5V then we can calculate the power we need to dissipate. (9-5) x 1.26 = 5.04W of heat. Ok you need a regulator that can dissipate that kind of heat.

A 7805 regulator will not do, you need a switching buck converter.

As to driving this on battery power I don't think alkaline will be able to deliver 1.3A (adding for the MCU) without loosing voltage to inner resistance, some rechargeable might. Lipo can deliver but at a different voltage that will need a new calculation of potential waste using linear regulation, or a buck regulator. In my opinion the charging of lipos require special attention and are not my preference, but might be option here.

---
Tags: arduino-uno, power, voltage-level, rgb-led, voltage-protection
---


title: How to use unregulated VIN voltage?

text:
# Question
Title: How to use unregulated VIN voltage?
I have recently bought an Arduino Mega, and I am powering it with a USB charging port, 5V at 1A. I need to use the 1A with a transistor, since the Arduino itself can only supply a maximum of 20mA through one pin.
So I was wondering, is there any way to access this unregulated power source? Would the VIN pin serve this purpose, or is there no way to access the 1A current without pulling apart the USB cable?

# Answer
The VIN port is connected to the barrel jack. It must only be used if you are powering the board through that jack.

To access the USB power just use the 5V pin - it is directly connected to the USB.

However, the USB, although the socket it is plugged into can supply more, is limited to 500mA. This is because of a 500mA auto-resetting *polyfuse* on the USB power input (the large gold and dark green rectangle next to the USB socket - mine has either XE05 or 503X on it depending on which way up you hold it).
> 2 votes

---
Tags: power, usb, current, voltage-protection
---


title: Max current through an Arduino Mega?

text:
# Question
Title: Max current through an Arduino Mega?
How much current can I put through the pins of an Arduino Mega at the same time?

The situation: I am building a 7x7x7 LED cube, and my plan was to multiplex in 7 layers of 49 pins, lighting each layer, one at a time. This would mean each pin on the Arduino Mega would only have to supply max. 1 LED at a time.
However, if all 49 LEDs in one layer were on, it would presumably draw 49\*20mA (from the LED specs sheet), which is 980mA. This seems like quite a lot of current to put through an ATMega chip, so I was wondering if I could do it, either continuing like this, or using transistors to control the lighting of each layer, or what?
Any help or advice is appreciated!

EDIT: Using ATMega2560, not ATMega328 or alternate.

# Answer
The ATmega 2560 (assuming that's the chip on your Arduino Mega) has an absolute limit of 40mA on each pin, and 200mA in total for all pins. So yes, you will not be able to drive that load directly from the Arduino.

With external circuitry however, anything is possible. If it were me, I'd use some TPIC6B595 IC's to drain current and BC635 NPN's to source it.

The 595's can sink up to 150mA each (so up to 8 LEDs at 18.75mA each, use a 270Ω resistor in series with each LED if you're running everything from 5V.) You would need 7 595's for 49 LEDs (49 / 8 rounded up.)

You can daisy chain the serial in/outs on them so you just need to shift out 8 bytes from the Arduino (either using SPI or the software equivalent, shiftOut or whatever it's called, on any digital pin.)

TPIC6B595N Datasheet

To source current, BC635's are rated up to 1A with a typical current gain (hFE) of 100. Collector pin goes to 5V, Emitter pin goes to all the LED anodes on a layer, Base pin connects in series to a 510Ω or 470Ω resistor and an Arduino digital pin. You would need 7 635's, one for each layer. They turn 10mA from a digital pin into 1A from the power supply.

BC635 Datasheet

Speaking of power supplies, you will not be able to power the whole thing from the Arduino 5V pin (especially if powered from USB.) You will need an additional 5V power supply. If you want simplicity you could use a L7805 voltage regulator and stick a heatsink on it.

L7805 Datasheet

All of these are popular components which can be obtained from eBay for next to nothing.

If you have more questions specific to Arduino, they might be better suited to the Arduino Stack Exchange.

Arduino Stack Exchange Link
> 1 votes

# Answer
You're on the right track here. In the datasheet for the ATmega1280 I find this box:

What you want to look at is `DC Current Vcc and GND Pins .... 200.0 mA`

This is the total limit of *all the current* going through the chip (because everything must come through Vcc), and it is the *absolute maximum*. Don't go near it. You need to boost this with some transistors.
> 2 votes

# Answer
It's listed in the Electrical Characteristics of the specific MCU used in the Arduino you have.

For the Mega2560, its remarkably similar to the 328 in the Uno.

Absolute Max, 40mA per pin, 200mA VCC or GND current. 20mA per pin recommended max. A huge note, various ports have individual limits:

> **3: Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state conditions (non-transient), the following must be observed:**
> ATmega1281/2561:
> 1.)The sum of all IOL, for ports A0-A7, G2, C4-C7 should not exceed 100mA.
> 2.)The sum of all IOL, for ports C0-C3, G0-G1, D0-D7 should not exceed 100mA.
> 3.)The sum of all IOL, for ports G3-G5, B0-B7, E0-E7 should not exceed 100mA.
> 4.)The sum of all IOL, for ports F0-F7 should not exceed 100mA.
> ATmega640/1280/2560:
> 1.)The sum of all IOL, for ports J0-J7, A0-A7, G2 should not exceed 200mA.
> 2.)The sum of all IOL, for ports C0-C7, G0-G1, D0-D7, L0-L7 should not exceed 200mA.
> 3.)The sum of all IOL, for ports G3-G4, B0-B7, H0-B7 should not exceed 200mA.
> 4.)The sum of all IOL, for ports E0-E7, G5 should not exceed 100mA.
> 5.)The sum of all IOL, for ports F0-F7, K0-K7 should not exceed 100mA.
> **If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.**
>
> **4: Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state conditions (non-transient), the following must be observed:**
> ATmega1281/2561:
> 1)The sum of all IOH, for ports A0-A7, G2, C4-C7 should not exceed 100mA.
> 2)The sum of all IOH, for ports C0-C3, G0-G1, D0-D7 should not exceed 100mA.
> 3)The sum of all IOH, for ports G3-G5, B0-B7, E0-E7 should not exceed 100mA.
> 4)The sum of all IOH, for ports F0-F7 should not exceed 100mA. ATmega640/1280/2560:
> 1)The sum of all IOH, for ports J0-J7, G2, A0-A7 should not exceed 200mA.
> 2)The sum of all IOH, for ports C0-C7, G0-G1, D0-D7, L0-L7 should not exceed 200mA.
> 3)The sum of all IOH, for ports G3-G4, B0-B7, H0-H7 should not exceed 200mA.
> 4)The sum of all IOH, for ports E0-E7, G5 should not exceed 100mA.
> 5)The sum of all IOH, for ports F0-F7, K0-K7 should not exceed 100mA.
> 1 votes

---
Tags: current
---


title: ATtiny85 and INPUT_PULLUP

text:
# Question
Title: ATtiny85 and INPUT_PULLUP
I have read some conflicting sources about what pins have internal pullup resistors available for the Attiny85 microcontroller. Can all I/O pins work with INPUT\_PULLUP, or just some of them? And if so, which ones?

Thanks!

# Answer
> 4 votes
Check the datasheet, probably just search for "internal" or "pullup" I believe there are little more pins/ports as portB, so they should all have internal pull ups.

---
Tags: attiny, input, pull-up
---


# Question
Title: Hardware network-infrastructure for a fully-arduino-based home-automation project
As already mentioned in another question, I'm spending **LOT** of time planning the home-automation system for my new house (currently still in the "still building" phase).

Even if started only as a "lights/switch management project", things started getting bigger and bigger and, at the moment, in addition to original requirements, I **already** have:

1. A reed switch including cut-detection wires (for a total of 4 wires) installed on every single window (one switch for single-windows; two switches for dual-door windows);
2. planned the location of a DHT22 sensor in each room.

In addition to the above, I'm currently evaluating the opportunity to add a single **RGB led to have visual-feedback for each push-button** (something like: GREEN=\>LIGHT/OFF; RED=\>LIGHT/ON). More specifically, I'm evaluating the opportunity to replace common/simple pushbuttons with these:

Obviously, such a change will **heavily** impact the cabling, as:

* original simple/pushbutton required **only two wires** for each pushbutton, with one wire potentially shareable among adiacent pushbuttons (I'll be using "internal pullups", so one wire will be GND)
* RGB pushbuttons require **six** wires (GND and SIGNAL for pushbutton; R, G and B plus COMMON for LED), with only two wires potentially shareable among adjacent pushbuttons (GND and COMMON).

Adding to this that it will be easy to have wall-boxes hosting two, three or even four pushbuttons, and you easily understand that **LOTS** of cables are required!

Here below I'm attaching a rough schema of what I'm planning to build, in terms of hardware:

where you can see:

* ROOM 1, with:

+ 2 x reed switch (up to 8 wires);
    + 1 x DHT22 (3 wires);
    + a wall box with two pushbuttons/wLED (up to 12 wires);
    + a wall box with one pushbutton/wLED (up to 6 wires)
* ROOM 2, with:

+ 1 x reed switch (4 wires);
    + 1 x DHT22 (3 wires)
    + a wall box with two pushbuttons/wLED (up to 12 wires)

Also, as for "controlling" the whole system:

* two POWER-BOXES, located externally to rooms, where I originally planned to host the "controller" (a MEGA2560) together with needed Relay-modules, and interconnected via an RS-485 bus.

(BTW: actually, I'll have three POWER-BOXES, and not only TWO. But this is a detail, as for the spirit of this question).

Please note that POWER-BOXES (PB1 and PB2) will be located (...as for the original plan) quite **FAR** from some rooms: up to 10/15 meters, in the worst case scenario. Also, please note that each power-boxes are far up to 10/15 meters from each-others.

Before the real question, let me add another couple of important points:

* Even tough I know that some kind of wireless system and/or wireless segment could simplify my overall architecture, I'm a strongly believer that a "wired" system is more reliable than a "wireless" one, expecially in the long-term. As such, as I'm lucky enough to put down **lots** of "pipes" (to properly distribute cables all around the house), I really prefer a wholly wired system;
* As for this question, I'm **not** interested in the "software" side of the system. This is really an accessory (again, as for this very question). My **really\_big\_problem** relates to the "hardware" infrastructure to put in place. That's why I'm posting this question here.

After the all of this, here is the question:

As for your experience and knowledge:

1. should I stick to original plan, having an RS-485 multidrop-bus interconnecting only the MEGAs, with "signal" cables going directly from room-hardware (pushbuttons, reeds, DHT22, etc.) to the MEGA PINs ....

or

2. should I add some other Arduinos (a Micro seems a really good candidates) in **each room**, terminating all the signal-room-cables coming from room-hardware, and speaking with MEGAs via the same RS-485 bus?

In the first case, I'll have a real simple RS-485 bus with a mess of cables; In the second case I'll have a \_longer\_and\_more\_complex\_ RS-485 bus, with a much manageable network cabling/infrastructure.

Am I right? What are the PROs and the CONSs of above two scenarios? Should I investigate **other** approaches?

Are there some documentation that can help me picking the right solution?

**Thanks in advance to all of those who will spend some (precious) time helping me in this really difficult decision to take!**

---

BTW: if you need further details, please don't hesitate to ask.

# Answer
> 1 votes
1. short wires are generally better than long ones
2. I agree, that wired is better in your situation
3. Maybe you distinguish between two different areas: sensor/actor to controller and controller to controller communication
4. In many cases you can not chose the sensor/actor to controller communication, because it is given by the device (DHT-22, reed, led push button etc.). Therefore, keep these lines short
5. RS-485 is good, but is it necessary? It adds drivers to each device. Maybe, I2C could do it,to. You can still use twisted pair cables.

# Answer
> 0 votes
Here my additional thoughts in short:

1. 20 meters is, compared with the distance to the moon, quite short ;-). Maximum length of RS-485 is reported to be kilometers with small transmission rates (google: rs485 cable length).
2. Noise can either be avoided (hardware) or corrected by software (fault tolerant codes, checksums etc.) Generally, software is cheaper.
3. Short wires does not mean no wires at all. Short wires would e.g. result if you have a controller per room and connect the sensors to it.
4. There are also small packages of Arduino compatible chips available (ATTiny84/85). And without RS485 you save the space of the controllers...
5. I2C bus length should work inside a house, if yous is not bigger than the one of Bill Gates... http://www.esacademy.com/en/library/technical-articles-and-documents/miscellaneous/i2c-bus/frequently-asked-questions/i2c-faq.html
6. I would not use serial for communication. It is not extensible. Serial is ok for debugging.

---
Tags: arduino-micro, networking, arduino-pro-micro, rs485, home-automation
---


title: Reading 2 numbers from serial

text:
# Question
Title: Reading 2 numbers from serial
I try to send pairs of numbers over the serial port from a linux pc to the arduino. By now I did so always by piecing together the ASCII chars from the serial line and using `Serial.read()`. Now I need this same thing to run at 100-200Hz, and it turns out, that the Arduino does not receive all the data (even at 1Hz).

As turned out, my problem was in another portion of the code and all below code works perfectly as is!

How do I make sure, that every char (or better even byte without ASCII encoding) is received? I am aware, that each connection has errors, but this is a systematical error! I guess, that the bytes are lost during the processing within the main loop, or because of other callbacks I use (got some ISR running). I am not looking for error detection, but rather a concise way of reading the serial line, without loosing 70% of the data validity.

If important: the pairs i need to send are unsigned, 1 byte and another one with 2 bytes. The values are in the range of `[0;7]` and `[1000;2000]`. Thanks for any advice. Disclaimer, I read a lot, including this, but most questions go into detail about the packaging format, whereas I am concerned about the reading method.

Code I use at the moment:

```
// read numbers from the char representation!
// on the serial connection
// each DIGIT is sent separately

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
uint8_t channel; // holding the number of the channel to modify
uint16_t signal; // ppm signal length in us (1000-2000)

void setup() {
  Serial.begin(115200);
  inputString.reserve(200);

  pinMode(9,OUTPUT); // fixed pin 9 for PPM output
}

void loop() {
  if (stringComplete) {
    channel = uint8_t(inputString[0])-48;
    signal = 0;
    for (uint8_t n=1; n<5; n++) {
      signal = (signal*10) + uint8_t(inputString[n])-48;
    }
    Serial.print(F("ch: ")); Serial.print(channel);
    Serial.print(F(" signal: ")); Serial.print(signal);
    Serial.print(F("\n"));
    //PROCESS Data
    inputString = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    // if the incoming character is a
    // newline (10) or carriage return (13)
    // set a flag for a complete transmission
    if (inChar == 10 | inChar == 13) {
      stringComplete = true;
    }
  }
}

```

Another version I tried, without strings is:

```
// channel and pulse-length
uint16_t numbers[2] = {0, 0}; // channel,value
uint8_t buf[5];

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

void loop() {
  if (serial_input(numbers,buf)) {
    numbers[0] = buf[0]-48;
    numbers[1] = (buf[1]-48)*10+(buf[2]-48);
    Serial.print(F("channel: ")); Serial.println(numbers[0]);
    Serial.print(F(" signal: ")); Serial.println(numbers[1]);
    // Do Stuff
  }
}

uint8_t serial_input(uint16_t* num, uint8_t* buf) {
  uint8_t newData = 0;
  uint8_t k = 0;
  num[0] = 0; num[1] = 0;
  while(Serial.available()) {
    delayMicroseconds(2100);
    char ser = Serial.read();
    if (isDigit(ser)) {
      buf[k] = uint8_t(ser);
      k++;
      newData = 1;
    } else {break;}
  }
  return newData;
}

```

Another try inspired by an answer here, where I send "3 1500\n" over the serial line:

```
void serialEvent() {
  if (!newdata) {
    channel = Serial.parseInt();
    signal = Serial.parseInt();
    newdata = true;
  }
}

```

Turns out all of those methods work (more or less elegantly), but having a "delay" within an ISR isn't such a good idea - even intermediately...

# Answer
> 0 votes
there is a great function: https://www.arduino.cc/en/Serial/ParseInt

I have tested the following script up 2kHz incoming, but it should go even faster. Do something like this

```
int number = 0;
int number2 = 0;
bool get_data = false;
void setup() {
  Serial.begin(115200);
  inputString.reserve(200);

  pinMode(9,OUTPUT); // fixed pin 9 for PPM output
}

void loop() {
    if(get_data == true){
      Serial.print(number);
      Serial.print(number2);
      get_data = false;
    }
}
 void SerialEvent()
   if(!get_data){
     number = Serial.parseInt();
     number2 = Serial.parseInt();
     get_data = true;
   }
}

```

# Answer
> 1 votes
115200 baud at 200Hz means you should be able to transfer in excess of 50 characters between each "trigger". That is more than enough time to send the data even as ASCII encoded text.

`serialEvent()` is no better than manually looking at things like `serialAvailable()` in your loop since that is all it does anyway. It just runs after each iteration of your loop.

One problem that you have is that you're appending each character to a String object. This is very inefficient and should be avoided. Instead you should really use a character array:

```
// Input text in the form "123 456\n"
char instring[20]; // Room for 19 characters plus terminating null
int spos = 0; // Location in the array
int val1 = 0;
int val2 = 0;

void loop() {
    if (Serial.available()) {
        char *bita, *bitb;
        int c = Serial.read();
        switch (c) {
            case '\r': break; // ignore
            case '\n':
                 spos = 0;
                 bita = strtok(instring, " ");
                 bitb = strtok(NULL, " ");
                 if (bita && bitb) {
                     val1 = atoi(bita);
                     val2 = atoi(bitb);
                 }
                 // You now have two new values in val1 and val2
                 break;
            default:
                if (spos < 18) {
                    instring[spos++] = c;
                    instring[spos] = 0;
                }
        }
    }
}

```

---
Tags: serial, usb, linux
---


# Question
Title: Has anybody seen/created a gps guided vehicle with arduino?
I thought the idea of Amazon Prime air drone delivery was a pretty cool one when it first came out and I started to question whether something like that (an autonomous gps guided vehicle) could possibly be created with the Arduino microcontroller(s). Any thoughts?

# Answer
GPS is not, by itself, enough to make an Amazon Prime-like delivery drone. GPS only provides a very rough position (thanks to the US Military imposing a large margin of error on non-military users, or so the urban legend goes (it's actually a difference in transmission systems that makes the difference)). It's good enough for getting you to your destination and working out roughly where you are, but getting to a specific pinpoint location just can't be done.

So you need other sensors as well. Things that can examine the environment and work out where you are in relation to other things. Especially people. Object avoidance is the critical component of any autonomous drone, and unless you can come up with a completely safe and foolproof system the FAA will be down on you like a ton of rectangular building blocks.
> 1 votes

# Answer
Yes, someone (not me) has: https://www.youtube.com/watch?v=3-r2Jk0uA6U

I doubt it would work very well with non-flying vehicles - in the air, a 3 meter margin of error is fine, on the ground it's the difference between the sidewalk and the middle of the road.
> 2 votes

---
Tags: arduino-uno, programming, sensors, c++, power
---


title: Arduino sensors with various periods

text:
# Question
Title: Arduino sensors with various periods
Right now I have DHT11, PIR sensor, relay, and a photocell on the same board. I am planning to upload the data to a web server. But I want both DHT11 and photocell to be uploaded hourly; PIR and relay by every 3s. Is it possible for a single Arduino to perform such thing?

# Answer
> 2 votes
Yes. Perfectly possible.

How accurate do you need the "hourly"? If you want any form of accuracy at all you will really want to use an RTC module to provide the real time.

Otherwise that, and the higher speed 3s updates, can be timed using the `millis()` function. The BlinkWithoutDelay example in the IDE shows you the basic idea of working with timestamps to examine elapsed time.

Also there are simple libraries that could help you, such as SimpleTimer.

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


title: Sparkfun Si4703 FM not getting to loop

text:
# Question
Title: Sparkfun Si4703 FM not getting to loop
I recently purcahsed an si4703, from sparkfun

https://www.sparkfun.com/products/11083

I got it soldered to some headers and now I am not getting anything to work on it, my wire diagram is as follows

( I know the FM module pictured is different but its ultimately wired up the same I think)

And I am just trying to run the out of box example code modified to my Arduino Mega board

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

int resetPin = 35;
int SDIO = A15;
int SCLK = A14;

Si4703_Breakout radio(resetPin, SDIO, SCLK);
int channel;
int volume;
char rdsBuffer[10];

void setup()
{
  Serial.begin(9600);
  Serial.println("\n\nSi4703_Breakout Test Sketch");
  Serial.println("===========================");
  Serial.println("a b     Favourite stations");
  Serial.println("+ -     Volume (max 15)");
  Serial.println("u d     Seek up / down");
  Serial.println("r       Listen for RDS Data (15 sec timeout)");
  Serial.println("Send me a command letter.");

  radio.powerOn();
  radio.setVolume(0);
}

void loop()
{
  Serial.println("looping");
  if (Serial.available())
  {
    char ch = Serial.read();
    if (ch == 'u')
    {
      channel = radio.seekUp();
      displayInfo();
    }
    else if (ch == 'd')
    {
      channel = radio.seekDown();
      displayInfo();
    }
    else if (ch == '+')
    {
      volume ++;
      if (volume == 16) volume = 15;
      radio.setVolume(volume);
      displayInfo();
    }
    else if (ch == '-')
    {
      volume --;
      if (volume < 0) volume = 0;
      radio.setVolume(volume);
      displayInfo();
    }
    else if (ch == 'a')
    {
      channel = 930; // Rock FM
      radio.setChannel(channel);
      displayInfo();
    }
    else if (ch == 'b')
    {
      channel = 1067; // BBC R4
      radio.setChannel(channel);
      displayInfo();
    }
    else if (ch == 'r')
    {
      Serial.println("RDS listening");
      radio.readRDS(rdsBuffer, 15000);
      Serial.print("RDS heard:");
      Serial.println(rdsBuffer);
    }
  }
}

void displayInfo()
{
   Serial.print("Channel:"); Serial.print(channel);
   Serial.print(" Volume:"); Serial.println(volume);
}

```

However I do not think it is ever getting to the actual loop, it seems to get stuck on the code `radio.powerOn()` and then does nothing after that, what can I do to make this work?

# Answer
> 1 votes
According to your hookup image, you have connected I2c pins to A14 and A15, I2c on Mega is on pins 20 and 21 , clearly marked SDA and SCL.

Also note that this module can ba powered by 5V but is only 3.3V tolerant on the input pins, you should use a level converter.

---
Tags: arduino-mega
---


# Question
Title: Background processes - Arduino Mega and SeeedStudio CAN shield
I am attempting to interface an Arduino Mega 2560 with a system of four Black Jaguar motor controllers connected in CAN. I'm using the CAN shield from SeeedStudios to accomplish this.

The way Jaguars in CAN mode are configured, you must send a message every 100 ms to the network to keep the link active. However, I'm also getting input from Serial to another Arduino as well as sending other commands to the Jaguars, but not regularly enough to specifically time it out.

Is it possible to have the link message sent asynchronously in the background while I perform other code? I have looked into timers and interrupts, however I am unsure if this would truly solve the issue considering I have other processes that take more than 100 ms to complete.

Here's my loop statement:

```
loop() {
  CAN.sendMsgBuf(HEARTBEAT,1,0,volModeEnable); //HEARTBEAT keeps CAN link active
  setVoltage(3,.5); //Sets voltage of Motor by percent
  setVoltage(4,.5);
  setVoltage(6,.5);
  setVoltage(8,.5);
  //GrabFromSerial(); Takes longer than 100ms
  //Control Statement for Additional Commands goes here... (also necessary to be > 100ms)
}

```

# Answer
> 1 votes
I see several options:

1. Change your code to achieve lower delays on the other functions
2. Use interrupts at a set frequency to trigger the sending (and maybe the automatic transmission trigger pins, see MCP2515 datasheet, depending on pin use & schematic of your specific shield)
3. Use a basic scheduler/rtos

It is hard to tell what is going on without the rest of your code, if it is a good idea to try to achieve faster functions.

I am not 100% sure the CAN-lib would will work well in the context of an interrupt.

---
Tags: programming, can-bus
---