# Question
Title: How do you write to a free location on an external EEPROM?
I want to log GPS positions to an external EEPROM over I2C.

For example: Latitude: 51.0000 Longitude: 4.0000

If I remove the decimal place then each of these addresses would consume up to two bytes each.

My question is: ***How can I log each new set of GPS data to a new memory address on the EEPROM each time?***

Bearing in mind that the Arduino might be switched off between entries.

# Answer
The trick you are looking to implement here is the ability to look through the EEPROM and say "This is the last place I wrote to - I will write to the next place now."

There's two ways of doing it, the easy way and the right way.

The easy way is to maintain a single address in the EEPROM that says where you wrote to last. If you are trying to implement some form of wear levelling to extend the life of your EEPROM then this would basically negate it, since that one cell in the EEPROM will wear out before the rest of it and become useless. So it's really not a good idea although it may sound like it at first.

The *right* way to do it is to store *more* information in the EEPROM every time. Not only do you need to store the data, but also some kind of identifying *sequence* number.

Say you have 4 bytes of data to write each time. Add a fifth byte to it. That fifth byte increases by one each time you write. Before you write you scan through the EEPROM looking at every fifth byte looking for the "end" of the sequence.

For instance, you may end up with (`xx` is your data bytes) in hexadecimal:

```
00: 00 xx xx xx xx
05: 01 xx xx xx xx
0A: 02 xx xx xx xx
0F: 03 xx xx xx xx
14: FF FF FF FF FF

```

You see that at address 0x14 the nice sequence of numbers breaks. Therefore your next write must be at that point. Now, if you then loop through the EEPROM many times after a while, you may end up with something that looks like this:

```
00: FE xx xx xx xx
05: FF xx xx xx xx
0A: 00 xx xx xx xx
0F: 01 xx xx xx xx
14: 58 xx xx xx xx

```

You can see a clear sequence here of `0xFE 0xFF 0x01` where they increase by 1 each time (0xFF + 1 = 0x00) so you can see that you have looped through your sequence numbers. You don't care though because it's still just plus one. Only when you get the jump from 0x01 to 0x58 does the sequence break, so you know where the last write would have been.

There are only a couple of small gotchas here:

1. You can only use 5\*n cells in the EEPROM since the last 5-byte packet of data may not fit within the last bit of EEPROM (say it's a 1024 byte EEPROM you would have room for 204.8 packets - so 204 packets and 4 bytes left over).
2. You must ensure that you don't end up with exactly 256 packets fitting in the EEPROM before you loop the address - otherwise the sequence won't "break" so you will never know where the last write was after the first loop.
> 6 votes

# Answer
You can divide EEPROM space into entries and provide each entry with a single "used" bit. You could use a separate byte to store it, or reuse a bit from a byte which is not completely used by your data.

Suppose you start with EEPROM willed with zeroes, and you decide that the first byte of each entry holds the "used" bit in the LSb. When you log coordinates the first time, you'll have:

```
 /---"used"
01 51 00 00 04 00 00
00 00 00 00 00 00 00
 \---"free"
...
00 00 00 00 00 00 00

```

(of course, you don't have to store GPS coordinates as BCD, it's just an illustration).

Note that as you add entries, it's trivial to keep track of the last one: just check the entries in sequence until you find a "free" one and go back one step. Also note that the first entry is always "used".

This will go on until all your entries are "used":

```
01 51 00 00 04 00 00
01 52 00 00 05 00 00
...
01 53 00 00 06 00 00

```

At this point (when you have to write new data but there are no "free" entries), you start writing from the first entry again, inverting the value of the "used" bit:

```
 /---"used"
00 54 00 00 07 00 00
01 02 00 00 05 00 00
 \---"free"
...
01 53 00 00 06 00 00

```

(remember that the first entry is always "used"? Thanks to this, it's possible to simply swap the values representing "used" and "free" entries without actually erasing anything).

To sum up, the algorithm is:

* read the "used" bit from the first entry
* scan entries until the value of the "used" bit changes, or until you reach the end.
* to read the last logged data, use the last "used" entry
* to write new data, use the first "free" entry. If there are no "free" entries, start from the beginning, inverting the "used" bit.
> 7 votes

# Answer
You could assign the first byte(s) of the EEPROM as the address of the next free location in which to store GPS coordinates, and update it before the Arduino sleeps. At wake-up, retrieve the address.

You could keep the pointer in RAM, too; RAM keeps its contents across a sleep. But using EEPROM would even let you power off the Arduino, and still pick up where you left off after the power-up reset. (Of course, other parts of your program would have to be restart-tolerant as well; I'm just looking at the coordinate storage here).

As an aside, two bytes isn't sufficient to store a GPS coordinate to four decimals unless their range is limited such that you can scale them into \[0 - 65535\].
> 1 votes

# Answer
The question asks specifically about EEPROM (E2) and many of the answers point out or attempt to address E2's main limitation: limited # of write operations. Not mentioned is E2's slow speed. Its is best suited for storing infrequently modified data such as-built- or setup parameters such device calibration data and features of a device's external operating environment. Its only real advantage over other solutions is that it may already exist on your MCU - Atmega 328, for instance.

The new(er) kid on the block for non-volatile data storage is Ferroelectric RAM - FRAM. Write times are on the order of 30 times faster, at 150ns, and endurance is claimed to be 10^12 writes, or 10 million TIMES the endurance of E2. I've built a data logger that uses a ring-buffer in FRAM to store periodic data samples and write them on request.

The same techniques proposed in the answers for E2 will work equally well in FRAM with the additional advantage that you can ignore the complications meant to work around E2's limited write-endurance.

And by way of disclaimer: I don't sell this this stuff or have any other interest in it. But I do use it and it works like it says on the box.

Adafruit makes these on a breakout board in a couple of variations - size and serial-bus type - that are sold by them and other retailers. The link is for an 8K-byte, SPI-bus board.
> 0 votes

---
Tags: eeprom
---


title: Arduıno button problem

text:
# Question
Title: Arduıno button problem
I did a project with a fingerprint sensor. You can do the fingerprinting process by typing down 4 on the serial port, but in the same time i want to do this process with pressing another button.Can someone help me?

code http://www.heypasteit.com/clip/0IIQ6G

```
> #define  VB

#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <EEPROM.h>

SoftwareSerial mySerial(10, 11);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

char data;
unsigned int p;
uint8_t id;

void setup()
{
  Serial.begin(9600);
  finger.begin(57600);
  Serial.println("Sensore baglaniyor!");
  if(finger.verifyPassword())
  {
    Serial.println("Baglanti basarili!");
  }
  else
  {
    Serial.println("Sensor bulunamadi ");
    while (1);
  }
}

void loop()
{
  delay(100);

  if(Serial.available()>0)
  {
    data=Serial.read();

    if(data=='1')
    {
      Serial.println("Delete all ID records");
      finger.emptyDatabase();
      delay(50);
      EEPROM.write(0,-1);    //reset ID counter
    }
    else if(data=='3')
    {
      id = EEPROM.read(0) + 1;    //get next available ID
      Serial.print("Enrolling ID #");
      Serial.println(id);
      getFingerprintEnroll(id);
      delay(50);
      EEPROM.write(0, id);        //save current ID
    }

    while (data=='4')
    {
      getFingerprintID();
      delay(50);

    }
  }
}

uint8_t getFingerprintEnroll(uint8_t id)
{
  uint8_t p = -1;
  Serial.println("Waiting for valid finger to enroll");
  while (p != FINGERPRINT_OK)
  {
    p = finger.getImage();
    switch (p)
    {
    case FINGERPRINT_OK:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
#if !defined (VB)
      Serial.print(".");
#endif
      break;
    default:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Unknown error");
      break;
    }
  }

  p = finger.image2Tz(1);
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Image converted");
    break;
  }

  Serial.println("Remove finger");
  delay(1000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER)
  {
    p = finger.getImage();
  }

  p = -1;
  Serial.println("Place same finger again");
  while (p != FINGERPRINT_OK)
  {
    p = finger.getImage();
    switch (p)
    {
    case FINGERPRINT_OK:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
#if !defined (VB)
      Serial.print(".");
#endif
      break;
    default:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Unknown error");
      break;
    }
  }

  p = finger.image2Tz(2);
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Image converted");
    break;
  default:
    Serial.println("Unknown error");
    return p;
  }

  p = finger.createModel();
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Prints matched!");
    break;
  case FINGERPRINT_ENROLLMISMATCH:
    Serial.println("Fingerprints did not match");
    return -1;
    break;
  default:
    Serial.println("Unknown error");
    return -1;
    break;
  }

  p = finger.storeModel(id);
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Stored!");
    break;
  default:
    Serial.println("Unknown error");
    return p;
    break;

  }
}

int getFingerprintID()
{
  p = -1;
  Serial.println("Waiting for registered ID");
  while (p != FINGERPRINT_OK)
  {
    p = finger.getImage();
    switch (p)
    {
    case FINGERPRINT_OK:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
#if !defined (VB)
      Serial.print(".");
#endif
      break;
    default:
#if !defined (VB)
      Serial.println();
#endif
      Serial.println("Unknown error");
      break;
    }
  }

  p = finger.image2Tz();
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Image converted");
    break;
  default:
    Serial.println("Unknown error");
    return -1;
  }

  p = finger.fingerFastSearch();
  switch (p)
  {
  case FINGERPRINT_OK:
    Serial.println("Found a print match!");
    break;
  case FINGERPRINT_NOTFOUND:
    Serial.println("Did not find a match");
    return -1;
    break;
  default:
    Serial.println("Unknown error");
    return -1;
    break;
  }

  digitalWrite(A1, HIGH);
  delay(500);
  digitalWrite(A1, LOW);
  delay(2000);

  Serial.print("Found ID #");
  Serial.print(finger.fingerID);
  Serial.print(" with accuracy value of ");
  Serial.println(finger.confidence);
  return finger.fingerID;
}

```

# Answer
> 1 votes
Take a look at the `Button` sketch in the examples menu in the Arduino IDE. That is the simplest example of how to use a button in Arduino.

**Circuit**

This is the test circuit. When you press the button, the built LED turns on/off. The circuit is applicable to any Arduino Uno, Mini, etc. The two wires at right are not really needed, but it doesn't hurt if you put them in the breadboard).

Note: What follows is an excerpt from https://www.arduino.cc/en/Tutorial/Button.

Connect three wires to the board. The first two, red and black, connect to the two long vertical rows on the side of the breadboard to provide access to the 5 volt supply and ground. The third wire goes from digital pin 2 to one leg of the pushbutton. That same leg of the button connects through a pull-down resistor (here 10K ohm) to ground. The other leg of the button connects to the 5 volt supply.

When the pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton, so the pin is connected to ground (through the pull-down resistor) and we read a LOW. When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5 volts, so that we read a HIGH.

You can also wire this circuit the opposite way, with a pullup resistor keeping the input HIGH, and going LOW when the button is pressed. If so, the behavior of the sketch will be reversed, with the LED normally on and turning off when you press the button.

If you disconnect the digital I/O pin from everything, the LED may blink erratically. This is because the input is "floating" - that is, it will randomly return either HIGH or LOW. That's why you need a pull-up or pull-down resistor in the circuit.

**Code**

```
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

```

---
Tags: arduino-uno
---


# Question
Title: How can my library source code instantiate an object from another library?
I'm having trouble explaining my issue. What I'm doing is creating a library to work easily with the RFID reader/writer RC522 module. I need to create an object of the library MFRC522 in my .cpp file to be able to communticate with the module itself. I want my constructor end up like this:`UltimateRFID rfid(53, 5);`, the parameters being the slave select and the reset pins, respectively. The problem is that I don't know how to make my constructor so that it is within the scope of the functions that require the MFRC522 object to be called. Below's my code.

```
#include "Arduino.h"
#include "UltimateRFID.h"
#include <MFRC522.h>

MFRC522::MIFARE_Key key;

UltimateRFID::UltimateRFID(int ss, int rst)
{
   MFRC522 mfrc522(ss, rst); //this would be ideal, but how can my functions access the instance?
}

void UltimateRFID::initialize() //sample of a function that uses the MFRC522 object
{
  //digitalWrite(49, HIGH);
  digitalWrite(2, LOW);
  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }
  mfrc522.PCD_Init();
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }

}

```

Now comes my header file, although I'm not sure it matters much.

```
#ifndef UltimateRFID_h
#define UltimateRFID_h

#include "Arduino.h"
#include <MFRC522.h>

class UltimateRFID
{
  public:
    UltimateRFID(int ss, int rst);
    void initialize();
  private:
    MFRC522::MIFARE_Key key;
};

#endif

```

Please be patient, it's my first library.

# Answer
Why not have your class just extend the MFRC522 class?

```
#include <MFRC522.h>

class UltimateRFID : public MFRC522 {
    private:
        MIFARE_Key key;

    public:
        UltimateRFID(uint8_t ss, uint8_t rst) : MFRC522(ss, rst) {}
        // your other methods
        void initialize();
};

void UltimateRFID::initialize() {
    //digitalWrite(49, HIGH);
    digitalWrite(2, LOW);
    for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
    }
    PCD_Init();
    if ( ! PICC_IsNewCardPresent()) {
        return;
    }
    if ( ! PICC_ReadCardSerial()) {
        return;
    }
}

UltimateRFID rfid(53, 5);

void setup() {
    rfid.initialize();
}

void loop() {}

```

Your class then becomes a "flavour" of MFRC522 with additional functionality. It can access all the public functions of the MFRC522 class, since they are now a part of your class.

Anything you can do with an MFRC522 object you can now do with your object. As well as your extra functions.
> 3 votes

# Answer
While @Majenko's answer is probably best (I +1'd it), for completeness, here's how to construct a member variable with parameters:

```
class UltimateRFID {
    public:
    UltimateRFID(int ss, int rst) : mfrc522(ss, rst) {}

    protected:
    MFRC522 mfrc522;
};

```

"placement new" is another option:

```
class UltimateRFID {
    public:
    UltimateRFID(int ss, int rst) {
        new (&mfrc522) MFRC522(ss, rst)
    }

    protected:
    MFRC522 mfrc522;
};

```

However, this method calls the default ctor - which may or may not be an issue. This is usually reserved for re-initializing an existing object.

There's also assignment:

```
class UltimateRFID {
    public:
    UltimateRFID(int ss, int rst) {
        mfrc522 = MFRC522(ss, rst)
    }

    protected:
    MFRC522 mfrc522;
};

```

This also calls the default ctor and works best if the class provides `operator=`.
> 2 votes

# Answer
```
UltimateRFID::UltimateRFID(int ss, int rst)
{
   MFRC522 mfrc522(ss, rst); //this would be ideal, but how can my functions access the instance?
}

```

As you note, that instance would go out of scope immediately. The simplest thing would be to put a **pointer** to the other class in your class definition. Then in your `init` function do a `new` to create the instance of the class, passing the appropriate parameters.
> 1 votes

---
Tags: library, rfid
---


# Question
Title: What to use instead of a USB to serial converter
The usb to serial converter i found was $4 .maybe i could use something less expensive,like jus a port.I need serious help ,the serial port was about $1

# Answer
May I suggest RS232 connection? It is an ancient tech but it might work for you. I am adding a tutorial. Also a component from eBay, which is 0.99 US dolar.
> 1 votes

# Answer
> The usb to serial converter i found was $4 .

you can find old Nokia data cable (a form of usb/ttl converter) for less than a dollar, or free if you happen to have one.

alternaively, usbasp programmers are very simple / inexpensive.

diy is possible but you need to count your time. tools need to be reliable so i tend to rule that out.
> 0 votes

---
Tags: arduino-uno
---


title: Send a polymorphic object over serial

text:
# Question
Title: Send a polymorphic object over serial
I am sending a polymorphic object over serial between two Arduinos. The transmission should be fine, indeed if on the receiver side I `static_cast` the pointer to the `Derived` class it works properly. On the other hand if I try to call virtual functions on the `Base` pointer, Arduino resets. What is causing this behaviour?

Some samples of the code follows.

Sender:

```
RS485_Serial bus;
void loop ()
{
  Random r(1); //targeting device 1 in the bus
  if (r.request(bus)) { blink(r.val); } //make a request for a random number
                                        //blink the led the given number of times

  delay(1000);
}

```

Receiver:

```
RS485_Serial bus;
bus.set_address(1);
void loop ()
{
  listen(bus);
}

```

Selected common parts:

```
struct Action {
  byte target_address;

  Action(byte addr): target_address(addr) {}
  virtual ~Action() {}

  virtual size_t size() const { return sizeof(*this); }
  virtual int  vrequest(RS485_Serial &) = 0;
  virtual void vrespond(RS485_Serial &) = 0;

  int request(RS485_Serial & bus) {
    bus.write(reinterpret_cast<byte*>(this), size());
    return vrequest(bus);
  }
  void respond(RS485_Serial & bus) {
    vrespond(bus); // <--- This virtual call makes the sender reset
  }
};

struct Random: Action {
  size_t size() const override { return sizeof(*this); }
  int val;
  Random(byte address): Action(address) {}

  int vrequest(RS485_Serial & bus) override {
    return bus.read(val);
  }
  void vrespond(RS485_Serial & bus) override {
    bus.write(static_cast<decltype(val)>(random(2,5)));
  }
};

void listen(RS485_Serial & bus) {
  byte * data = nullptr;
  byte length = 0;
  if ( bus.read(data, length) ){
    Action & a = *(reinterpret_cast<Action*>(data));
    if (a.size() == length) blink(3);
    if (a.target_address == bus.address) {
      a.respond(bus);
      //static_cast<Random*>(&a)->vrespond(); works but it has no point
    }
  }
}

```

My doubt is that if the vtable is stored in different positions, than the vtable pointer in the object obtained by the receiver will be off, causing the crash.

# Answer
I think http://stackoverflow.com is the correct forum for your question. Your problem is how to serialize/deserialize correctly an object in C++.

An easy way to do it is simply send the values (not the object) and recreate the object at the other side. So, now your problem is reduced to send and receive a bunch of int's, float's, string's, whatever.

Why you want/need to do that?
> 1 votes

# Answer
I suspect then that the object contains a pointer to the code for `vrespond`, which is at a specific (and differing from program to program) location in flash memory. An object in C++ isn't a single atomic item, it is a collection of data and pointers to functions. On a Harvard architecture system the data is in RAM and the code is in Flash (you cannot typically execute code from RAM). The compiler chooses where to place the code in Flash when it compiles (well, the linker does). That won't be the same address in different programs. All you are doing is sending over the addresses in flash that the code resides at - and those addresses are incorrect. By specifically casting it to a type that has code available you are also telling it where that code resides. Without that manual cast you are having to rely on the (incorrect) function pointers.

It is a bad idea to transfer objects like that from one system to another. It is better to transfer just the data and feed that data into an existing object created on the receiver. How you send and receive that data and feed it into the object is up to you.
> 1 votes

---
Tags: serial, programming, c++, pointer
---


# Question
Title: Documentation for creating a Board Manager profile for the Arduino IDE
I'd like to write a Board Manager profile for some Arduino boards that I have. So far I've struck out on finding the documentation on the format and contents of the files. Does anybody know where I can find it?

# Answer
Documentation is kind of scarce.

Basically there are two aspects to what you want - the *board definition* and the *board manager JSON file*.

The first describes the board to both the IDE (entry in `boards.txt`) and to the API software (definition of what pins are what and what peripherals are where, etc). The latter is in the file `pins_arduino.h`.

Then there is the `JSON` file that describes the whole package to the board manager and is what allows people to download the `boards.txt` and `pins_arduino.h` files (and anything else you may require) from your website.

As there is not much documentation you are best off taking an existing set of files that are close to what you want and modifying them. Most of the time it will be a slight tweak such as re-ordering a few pins in some arrays, or changing the name of the board and maybe an upload command or baud rate setting.
> 2 votes

# Answer
Arduino has provided comprehensive official documentation. You may not have found it because, since this is developer documentation rather than something the average Arduino user needs, it is published in the wiki of the Arduino IDE GitHub repository rather than with the standard documentation on arduino.cc.

### Hardware Package

https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification

### Boards Manager Support Files
> 0 votes

---
Tags: arduino-ide
---


# Question
Title: RS485 Multimaster Communication with collision avoidance
I'd like to know if there is an easy way to implement communication between multiple arduinos that avoids collisions using the RS485 module.

My setup would have multiple masters that send messages to only one slave that performs a task upon been given the message.

I've tried researching some libraries for this, but they normally don't fulfil the multimaster requisite, nevertheless I found this library which apparently does implement what I need, but I haven't been able to understand how it works.

My current options are either finding an easier library that is capable of doing what I need, learning how to make the linked library work (which I have already tried) or building my own serial communication protocol that implements collision avoidance and a multiple master configuration.

What path should I follow? Can you give me any recommendation for any of the paths I'm suggesting? Is there a better way of implementing this type of communication?

# Answer
Collision avoidance is a tricky subject. You can never completely avoid collisions - all you can do is work out how to a) detect them, and b) recover from them.

There's many different ways of doing it, and how you implement it is very much dependent on what your hardware can do, and how you are actually using the protocol.

The best way of detecting a collision is to arrange it so that your master is always reading the bus even when it is sending. You require separate receiver and transmitter modules, so that as you place a byte on the bus you attempt to also receive that byte. If it doesn't get received, or the wrong byte gets received, then you have a collision.

That is a 100% guaranteed way of detecting a collision as it happens. If you know that what you sent didn't make it onto the wire properly then it collided.

A simpler scheme is to be watching the bus before you send. If there has been no sign of any traffic for more than a certain threshold time then you can assume that the bus is currently quiet. You can then try and send your data. You don't know if it got through OK though, since something else could have decided that the bus was quiet long enough for it to send too.

So you would have to have some kind of ACK signal coming back from the other end that says the packet got received OK. Keep retrying until you get that ACK back. Of course, the ACK could be colliding as well, so it may have been received, but you just haven't been told. So your remote device would have to be able to gracefully handle receiving the same packet multiple times and discarding (yet still ACKing) the repeated packets.

What you should do when you do detect a collision (or fail to receive an ACK) is also kind of tricky. You have to wait and try sending again. But if there are two devices both waiting to send again, how can you be sure that they won't both be waiting for the same time, and thus collide again?

You have to ensure that both devices delay for a random period - and make sure that the random period truly is random. Using the default `random()` function, unless you can seed it from a truly random source of entropy, will generate the same sequence of numbers for all the devices - so each device would get the *same* "random" number. And collisions ensue.

So you see, you can't just throw a random library at it and say "This library will stop collisions" - the best you can say is "This library can help reduce collisions, detect them when they do occur, and gracefully recover from them."

For the library you link to it appears to attempt to implement the latter system:

> * Collision avoidance is implemented through the assignment of a message priority. A node will not start transmission before the bus has been idle for a time determined by the priority. Note that the highest priority is given to messages with the lowest priority number.
> * Collision detection is implemented by read-verified-write, i.e. all data written is checked on the fly for proper echo-back. If the software detects a frame error or a data mismatch when the echo character is received, it will disable the RS485 transmission and flag the collision status. The included transaction management will resend the message after the bus is idle again.

It waits for the bus to be free of traffic for a specific amount of time (the time is variable depending on the message priority), and expects the message to be sent back again as a form of ACK.

It makes no mention of random back-off times though to avoid collisions between different masters sending messages with the same priority.
> 6 votes

# Answer
There is a ready out the box solution documented in https://github.com/MichaelJonker/HardwareSerialRS485/wiki (This wiki describes the library you referred to).

The problem is quite complex: collision avoidance, collision detection and message retrial, message priority and message filtering. But the library solves it all. The software even provides a solution to interface a host (PC or Android) to the RS485, providing the same features.

In ‘understanding the library’ there are two aspects: how it works, and how to make it work.

The library itself is non-trivial (because the problem is also non-trivial), so to understand how it works is also non-trivial (Majenko, in his answer, gave a nice functional description of some of the features that are implemented by the library. The actual implementation has additional complications due to the direct interaction with the USART at interrupt level.). I guess you do not want to know (in first instance) how it works in such details.

However, the author (me) went to quite some detail to document how to make it work. But I reckon that documentation may be difficult to follow if the documentation does not match the expectations of the reader.

So I would be very interested to improve the documentation and to match the expectations of new users. However, here I need your help (or anyone interested) in pointing me out what and where I can improve.

The preferred way to contact me on these matters is by creating an issue on my Github project page:

https://github.com/MichaelJonker/HardwareSerialRS485/issues

BTW one of the issues addresses the same topic.

I guess that you need to create Github account in order to submit issues. Alternatively, you can contact me through this site (However, I might be less reactive through this channel).

Best regards

MichaelJonker
> 5 votes

# Answer
I did a post about rolling masters here on Arduino Stack Exchange.

The general idea is that you can set up multiple Arduinos to take turns becoming a master, based on waiting for its own "turn" in a time-based sequence, with provision for recovering from one of the units not responding.
> 2 votes

# Answer
I thinks the easiest way for software is not use any software do this at all, using a hardware controller chip/module instead which dedicated to support multi-master and arbitration for RS485 (the same way as CAN bus).

There is a protocol, named CDBUS, witch has stand-alone controller to do the work for you, which is very simple, I can even transfer video stream through it, details:

https://github.com/dukelec/cdbus\_doc (Introduction)
https://github.com/dukelec/cdbus\_ip (Protocol details & FPGA IP core)

You can also achieve this protocol by software only, if you don't care the speed or CPU usage.

Update: connect the CDCTL-Bx controller to an Arduino:
> -1 votes

---
Tags: arduino-uno, communication, rs485
---


title: Arduino nano does not draw enough power

text:
# Question
Title: Arduino nano does not draw enough power
I am trying to run a sensor from my switch using POE. I have created a temp/humidity sensor using the MySensors directions https://www.mysensors.org/about/arduino. I decided to use a nano due to the USB connector. I have connected this to my switch via a TP-Link POE splitter set to 5 volt output.

When connected, the switch provides power for a second or two then turns off for 10 seconds or so before coming on again. I believe the Switch is testing the circuit not detecting enough power being drawn and shuts down. It then goes through the cycle again. Note: both the power LED on the switch and the nano LEDS light up while power is supplied. I believe the nano itself only uses about 20mA

I have tested with another device that requires 9volts (hand held phone) via the splitter and it works fine with power provided consistently.

I was wondering if there is some circuitry I can add before the Arduino that will draw a little more current but still provide a constant 5V to the nano.

Additional information. The switch is a Linksys LGS124P. I have tried to find more detail regarding the required power but can only find this datasheet that does not provide that level of detail http://downloads.linksys.com/downloads/datasheet/1224699456700/25685\_LINKSYS\_unmanaged\_POE\_switches\_PROD\_Revised.pdf

# Answer
> 0 votes
A resistor or a light bulb in parallel with the Arduino will increase the power consumption.

---
Tags: power, arduino-nano
---


title: Do Arduinos meet military standards?

text:
# Question
Title: Do Arduinos meet military standards?
Do Arduinos meet military standards?

If not, where does it fall short? Is it something internal to the chip which might be corrected via external circuit? How could I evaluate the potential of a device I'm building?

# Answer
It depends on the application. For something like a rechargeable torch, Arduino might exceed the specifications. For a weapons system, NEVER (and **this is one of the *specific* prohibitions in the license agreement** \- see section 1.5 *note: link currently broken*). You also have to consider that there's literally thousands of armies in the world and they all have different standards. What might be acceptable to one might not be acceptable to another. Hamas uses rockets I wouldn't consider safe for anything, and they use them effectively - the Qassam rocket would never meet US military standards but it works great for Hamas.

US military standards are so complicated, nobody can answer this question for you. You're gonna need an army of lawyers to do that... here's a link to some documents to get started though...

Please note there are multiple standards which may apply to a given device. For example, you will see common off the shelf desktop computers (running Windows) used for some things in a military installation, but they could never be used to control a vehicle. Bottom line - you're gonna need a lawyer to navigate this. (You are better off selling your devices directly to soldiers, if you can live with that if it fails.)

http://www.dsp.dla.mil/ \- Terrible site - get used to that if you want to deal with govs.

OH BTW... if you want to use Arduino to prototype something, and you plan to remove "Arduino" later, running straight from the ATMega - that's the whole point of Arduino! It is a prototyping system, not intended to be used wholly in products. Arduino is very little more than a break-out board for the ATMega processor, a robust (kinda) power supply, and a runtime environment in C++.
> 5 votes

# Answer
Defiantly not. If you wanted to use it for very early prototyping then I think it would be fine. However, it really depends on the use because lets admit it Adriuno boards don't have huge amounts of processing power and are somewhat limited to capabilities.
> 1 votes

# Answer
Your question is broad. My first reaction is to say No. But in order to be very accurate (or fair), your should find the application standard. Military has an extensive library of standards ranging from manufacturing and testing. Therefore, take a look at the standard regulating your application. Only after this assessment, the question of whether Arduino will suffice a military application will be accurately answered.
> 1 votes

# Answer
It is not mil spec. Making something comply with milspec is a big, complex subject. (A subject I know very little about.)
> 0 votes

# Answer
> Do Arduinos meet military standards?

it meets some military standards but fails the others.
> 0 votes

---
Tags: safety, coding-standards
---


# Question
Title: Using an Arduino as a crystal oscillator
I want to overclock my Game Boy Advance SP. It has a built-in 4 MHz crystal, and I was able to temporarily replace it with an 8 MHz crystal to see if I was able to overclock it, which I was :).

However I'm wondering if it's possible to emulate/simulate a crystal using an Arduino? Like instead of a crystal soldered to the Game Boy, two output pins from the Arduino? If not, is there a such thing as a variable oscillator? Like a crystal with a potentiometer to change the frequency when the potentiometer is adjusted?

# Answer
> 2 votes
You want to use the Uno? You can set up a timer to output varying frequencies and output them on a pin. I have a page about timers which might help. The fastest you can get with a 16 MHz processor is 8 MHz output however you can get other frequencies by changing the timer parameters.

The ATtiny85 can output higher frequencies if you use the PLL clock option, I think you can then adjust the resulting frequency.

> If not, is there a such thing as a variable oscillator?

Adafruit make a Clock Generator Breakout Board - 8KHz to 160MHz. You connect that via I2C to your Arduino and then program assorted frequencies as a clock output. That uses the Si5351A clock generator chip.

---

Example code to output 8 MHz on a Uno or Mega2560:

```
#ifdef __AVR_ATmega2560__
  const byte CLOCKOUT = 11;  // Mega 2560
#else
  const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
#endif

void setup ()
  {
  // set up 8 MHz timer on CLOCKOUT (OC1A)
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
  OCR1A =  0;       // output every cycle
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

```

To output 4 MHz change OCR1A to 1 rather than 0.

# Answer
> 2 votes
A crystal oscillator connection to a microcontroller typically consists of two pins - an output "driving" pin, and an input "amplifying" pin. The crystal sits between the two pins (basically between the input and the output of the amplifier) and the amplifier oscillates at the frequency of the crystal.

In general you can bypass the crystal itself and just provide a clock signal on the input pin (often labelled OSC1 or OSCI) and ignore the output pin since it isn't needed to drive a crystal.

Some microcontrollers provide a special "EC" mode (External Clock) which disables the amplifier and just expects a clock signal.

# Answer
> 0 votes
Using the Arduino platform as a signal generator (oscillator) results in too high a granularity factor. Software that has been suggested can only change between 8 and 4 MHz but not output anything between those two frequencies.

It would be better to use some sort of DDS or Frequency Synthesizer circuit that can be adjusted incrementally with a granularity of 1 Hz or better.
My suggestion would be to use the Arduino to control a modern synthesis IC like the S15351a. This combination can output any frequency from 3KHz to 160 MHz in 1 Hz steps. The device is inexpensive and has 3 outputs which can be adjusted independently. Google "Si5351a Arduino" to find some circuit suggestions. https://www.qrp-labs.com/progrock.html

---
Tags: arduino-uno
---


title: Multiple SPIs on one Arduino [SOLVED]

text:
# Question
Title: Multiple SPIs on one Arduino [SOLVED]
**Setup**

* I have 2 Arduinos... each has two 2.4 GHz nRF24L01+ transceivers (so in total 4).
* Per Arduino, one is only for transmitting, while the other is for receiving (to prevent the need for switching between transmitting and receiving).
* The receiver and transmitter are on different channels (per Arduino, so channel 109 for receiver on arduino 1 and transmitter on arduino 2 and 112 for the other pair).

**SPI / Chip Select**

Because the nRF24L01+ are SPI devices, I need to use Chip Select, since there is only one SPI bus on an Arduino.

**Setup settings**

Since I can both receive and send (successfully) I did not add the Setup code (I used slowest speed 250 kbps, 16 bytes payload, no auto ack, no retries, highest power).

**Problem**

I can transmit/receive from both Arduinos, so all 4 transceivers work correctly. However, what I see in the output (see directly after the logging), is when I send, a lot of messages which should be received are missed. See the log at the end

Also, when I remove the write and replace it by a delay(1) than I miss just occasionally a message, so I think the write is the problem.

**Assumption**

Is it possible that during the write so many message from the other Arduino are colliding? I would expect a very fast on-air time, and even than, using two different channels should not make messages collide.

So it seems, while calling the Transmit for one RF, the other does not receive somehow. I know the CS pin of the receiver is HIGH (inactive) during transmitting (transmitter CS pin is LOW), but I would assume messages would be received by the RF, and when I set the CS pin of the receiver to LOW (active), that I can read the messages.

**Code (of one of the Arduinos)**

The code for the other Arduino is almost similar (only opposite port names as transmitter/receiver)

```
/*
*/
#include <SPI.h>
#include "RF24.h"

static const uint8_t RECEIVER_CE    = 5; // Chip Enable
static const uint8_t RECEIVER_CS    = 6; // Chip Select
static const uint8_t TRANSMITTER_CE = 7; // Chip Enable
static const uint8_t TRANSMITTER_CS = 8; // Chip Select

RF24 radioReceiver(RECEIVER_CE, RECEIVER_CS);
RF24 radioTransmitter(TRANSMITTER_CE, TRANSMITTER_CS);

uint32_t counter = 0;

static const int PAYLOAD_SIZE = 16;

static const int NR_OF_LOG_ITEMS = 10;
static const int LOG_LENGTH = 25;
uint32_t logData[LOG_LENGTH][NR_OF_LOG_ITEMS];
uint8_t currentLogLine = 0;

void setup()
{
  for (int m = 0; m < LOG_LENGTH; m++)
  {
    for (int n = 0; n < NR_OF_LOG_ITEMS; n++)
    {
      logData[m][n] = -1;
    }
  }

  pinMode(RECEIVER_CE   , OUTPUT);
  pinMode(RECEIVER_CS   , OUTPUT);
  pinMode(TRANSMITTER_CE, OUTPUT);
  pinMode(TRANSMITTER_CS, OUTPUT);

  digitalWrite(RECEIVER_CE   , HIGH);
  digitalWrite(TRANSMITTER_CE, HIGH);

  Serial.begin(250000);
  Serial.println(F("CONTROLLER"));

  digitalWrite(RECEIVER_CS   , LOW); // Select
  digitalWrite(TRANSMITTER_CS, HIGH); // Deselect

  radioReceiver.begin();
  radioReceiver.setPALevel(RF24_PA_MAX);
  radioReceiver.setChannel(109);
  radioReceiver.setDataRate(RF24_250KBPS);
  radioReceiver.setRetries(0, 0);
  radioReceiver.setAutoAck(false);
  //radioReceiver.enableAckPayload();
  radioReceiver.setPayloadSize(PAYLOAD_SIZE);
  //radioReceiver.enableDynamicPayloads();
  //radioReceiver.disableCRC();
  radioReceiver.setCRCLength(RF24_CRC_8);

  digitalWrite(RECEIVER_CS   , HIGH); // Deselect
  digitalWrite(TRANSMITTER_CS, LOW);  // Select

  radioTransmitter.begin();
  radioTransmitter.setPALevel(RF24_PA_MAX);
  radioTransmitter.setChannel(112);
  radioTransmitter.setDataRate(RF24_250KBPS);
  radioTransmitter.setRetries(0, 0);
  radioTransmitter.setAutoAck(false);
  //radioTransmitter.enableAckPayload();
  radioTransmitter.setPayloadSize(PAYLOAD_SIZE);
  //radioTransmitter.enableDynamicPayloads();
  radioTransmitter.disableCRC();
  radioTransmitter.setCRCLength(RF24_CRC_8);

  byte addresses[][6] = {"Read ", "Write"}; // TODO: Change name to slave/contr?
  radioReceiver.openReadingPipe(0, addresses[1]);
  radioTransmitter.openWritingPipe(addresses[0]);

  radioReceiver.startListening();
  radioTransmitter.stopListening();

  //radio.writeAckPayload(1, &counter, PAYLOAD_SIZE);
  //radio.printDetails();
}

uint8_t receiverBuffer   [PAYLOAD_SIZE];
uint8_t transmitterBuffer[PAYLOAD_SIZE];

uint32_t prevResponse = -1;
uint32_t response;

void loop(void)
{
  // Transmit.
  //Serial.print("Sending: ");
  //Serial.println(counter);

  transmitterBuffer[0] = counter >> 24;
  transmitterBuffer[1] = (counter & 0x00FFFFFF) >> 16;
  transmitterBuffer[2] = (counter & 0x0000FF00) >> 8;
  transmitterBuffer[3] = (counter & 0x000000FF);

  digitalWrite(TRANSMITTER_CS, LOW);  // Select
  digitalWrite(RECEIVER_CS   , HIGH); // Deselect
  //if (!radioTransmitter.write(transmitterBuffer, PAYLOAD_SIZE))
  {
    //Serial.println(F("Sending failed."));
  }
  delay(10); // Fake write

  // Receive.
  byte pipeNo = 0;

  digitalWrite(TRANSMITTER_CS, HIGH);  // Deselect
  digitalWrite(RECEIVER_CS   , LOW); // Select

  while ( radioReceiver.available(&pipeNo))
  {
    radioReceiver.read(receiverBuffer, PAYLOAD_SIZE);

    response = (receiverBuffer[0] << 24) +
               (receiverBuffer[1] << 16) +
               (receiverBuffer[2] << 8) +
               (receiverBuffer[3]);
    Serial.print("Received: ");
    Serial.print(response);

    if (prevResponse == -1)
    {
      prevResponse = response - 1;
    }
    else
    {
      if (prevResponse + 1 != response)
      {
        Serial.print(" MISSED ");
        Serial.print(response - prevResponse - 1);
      }
      prevResponse = response;
    }
    Serial.println("");
  }

  // Logging
  currentLogLine++;
  counter++;
  delay(10);  // Try again later
}

```

**Log**

```
Received: 10261 MISSED 15
Received: 10262
Received: 10263
Sending: 245
Received: 10278 MISSED 14
Received: 10279
Received: 10280
Sending: 246
Received: 10296 MISSED 15
Received: 10298 MISSED 1
Received: 10299
Sending: 247

```

# Answer
> 1 votes
\[solved\] ... I found out I HAVE to put one of the CS (chip select) pins to pin 10.

I thought it would not needed since the CS pin is different per SPI device, but it seems one needs to be on pin 10. Or at least, now I don't get problems sending/receiving (except some errors now and than, but that's normal with RF devices).

Thanks for everybody giving comments to my question.

---
Tags: arduino-uno, spi, nrf24l01+
---


# Question
Title: Make action happen after time is passed using interrupts
I am trying to create a code which prints to the LCD a message once a certain time is passed.

```
#include <Time.h>
#include <TimeLib.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  setTime(02, 10,00, 14, 03, 2016);

  //pinMode(13, OUTPUT);
  pinMode(2, INPUT);
  digitalWrite(2, LOW);
  attachInterrupt(0, blink, CHANGE);
}

void loop() {
  lcd.setCursor(0, 1);
  char time_out[16];
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());//use %x to get hex
  lcd.print(time_out);

  int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
  lcd.print(totalSeconds);
  if(totalSeconds > 7806) {
    digitalWrite(2, HIGH);
  }
}

void blink() {
  lcd.print("time passed");
}

```

The `setup` uses the Time lib to set a date. It also sets `pin 2` as an `INPUT` and sets it it `LOW`. The `attachInterrupt` checks if `pin 2 (0)`, changes, then function `blink` should execute.

In the loop, I am creating a string that prints out the time and displaying it to the LCD. I am also converting the time to seconds, so that I can easily compare two times. After 6 seconds (the timer starts at 7800), I am changing the value of `pin 2` to `HIGH`.

This should indicate a change in its state and should and trigger `blink`, but it does not. Can anyone spot the mistake I made? Thanks in advance.

# Answer
> 1 votes
Since I don't have enough reputations to comment on your question I am going to drop my two cents here.

Since your question is a little bit vague, I am going to suppose that you don't want any external interrupts thus, you don't need to use the `attachInterrupt` function. I am going to suppose that there is no need to use timers' interrupts as well.

Have a look at the following code:

```
#include <Time.h>
#include <TimeLib.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  setTime(02, 10,00, 14, 03, 2016);
}

void loop() {
  char time_out[16];
  lcd.setCursor(0, 1);
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());//use %x to get hex
  lcd.print(time_out);

  int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
  lcd.print(totalSeconds);
  if(totalSeconds > 7806) {
    blink();
  }
}

void blink() {
  lcd.print("time passed");
}

```

You should know the following:

Commands inside `void loop()` is going to be executed for ever again and again. Especially `lcd.print(time_out);`. You had better refresh the LCD every 1 second.

After 6 seconds `blink()` is going to be executed many times (maybe forever) since it is inside the loop and `if(totalSeconds > 7806)` is going to be always true.

If you have any question let me know in the comment section.

# Answer
> 0 votes
1. To do what you want, pin 2 would need to be an output. As an input you have no control over its state when you write it low. It may be hanging there floating in a high state and when you write high to it and turn on the pullup that may or may not actually be a change of state.
2. Doing a print to the LCD may not work in an ISR. Remember that during the ISR all other interrupts are disabled and depending on how your lcd library works it may not print anything from inside the ISR.
3. Even if it does print "time passed" upon being triggered by the line at the end of loop, a few microseconds later loop would repeat and that would be overwritten by the stuff that loop writes to the screen. So even if it did work you'd never know.

Instead of having your ISR print something to the screen, have it turn on an led or something so you know it actually triggered.

Try this instead and see if it is closer to what you want: (uncompiled and untested as I don't have the libraries)

```
#include <Time.h>
#include <TimeLib.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

boolean passed = false;

void setup() {
  lcd.begin(16, 2);
  setTime(02, 10, 00, 14, 03, 2016);

  //pinMode(13, OUTPUT);
  pinMode(2, OUTPUT);
  digitalWrite(2, LOW);
  attachInterrupt(0, blink, CHANGE);
}

void loop() {
  if (passed) {
    lcd.setCursor(0, 1);
    lcd.print("time passed");
    while(1);  // freeze here time is up
  }
  else {
    lcd.setCursor(0, 1);
    char time_out[16];
    sprintf(time_out, "%02u:%02u:%02u", hour(), minute(), second()); //use %x to get hex
    lcd.print(time_out);

    int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
    lcd.print(totalSeconds);
    if (totalSeconds > 7806) {
      digitalWrite(2, HIGH);
    }
  }
}

void blink() {
  passed = true;
}

```

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


# Question
Title: Powering Multiple Servos From One Battery- What is my circuit missing?
I'm working on a robotics project right now and my limited DIYer knowledge of electrical circuits is failing me. I need to power 7 Rage Standard Metal Gear Servos (RGRS104-16-6vm) and 4 RadioShack Micro Servos using a Tenergy 6V 3300mAh NiMH Battery Pack. I've made a diagram of the circuit I'd like to make, but I feel like there's more to this type of circuit than I've planned for. There are only 9 servo connections because two pairs of Rage Servos will be wired together to share the same battery and signal connection. I'm also open to using a different battery if that's what it takes to make the robot run smoothly (It has to use a rechargeable battery though; It's meant to be portable.) Also, the Arduino has it's own battery, so no worries there.

**Would you please point out what I need to add to my circuit to make sure it works properly?**

Thanks in advance!

**More Info:**

**Rage Standard Metal Gear Servo RGRS104-16-6vm** Dimensions: 40.8 × 20.1 × 38 mm Weight: 56 g Operating Speed: 0.18sec/60degree (4.8V), 0.16sec/60degree (6V) Stall Torque: 9kg.cm/125.2oz.in(4.8V), 10.2kg.cm/141.9oz.in(6V) Operating Voltage: 4.8V~6V Control System: Analog Direction: CCW Operating Angle: 180degree Required Pulse: 500us-2500us Bearing Type: 2BB Gear Type: Metal Motor Type: Carbon Connector Wire Length: 30 cm.

**RadioShack Micro Servo** Voltage: 4.8~6.0V Torque: 1.5kg/cm at 4.8V; 1.8kg/cm at 6.0V Speed: 0.12/60ТА at 4.8V; 0.10/60ТА at 6.0V Size: 23x11.5x24mm Weight: 8.6 g Use Angle: \<=160ТА

**Tenergy 6V 3300mAh NiMH Battery Pack** Chemistry: Ni-MH Cell Size: Sub-C Nominal Voltage (V): 6 Capacity (mAh): 3300 Max Continuous Discharge Current: 6A Battery Charging Current: Standard: 1A Weight: 10oz. Dimensions: 112 x 46 x 23mm (LxWxT) Connector: Hitech

**Link to Diagram:** https://i.stack.imgur.com/L4GtP.jpg

# Answer
One thing to ask, it is not clear if you are going to run the Arduino Uno off the same battery, or off a different battery?

If the same battery, then you are likely going to need to create an V+ output for the Uno, but will need to ensure that any drain from multiple servo's running are not going to impact on the voltage supplied to the arduino, and also that the voltage supplied is compatiable with the Uno (e.g. don't run 6V+ into the 3V outlet)

Just to note as well, the Arduino Uno has (to my knowledge) only has about 6 PWM pins which is what you will need to drive the servo's through the signal pin. You can add I2C PWM expanders which give you more pins (e.g. https://www.adafruit.com/product/815) but YMMV
> 1 votes

---
Tags: arduino-uno, power, servo, robotics
---


# Question
Title: DHT11 sensor works on Arduino Uno, not on LoLin NodeMcu
When run this code on an Arduino Uno (clone), everything works. When I run it on my LoLin NodeMcu, I get the following verbose upload output:

```
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM4
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

```

The only difference I really see is that on the Arduino Uno, the voltage pin is connected to 5V, while on the LoLin, it's connected to one of the 3V pins. Does the DHT11 require 5V?

**Edit**

So I stumbled upon this list of port mappings. When I change my pin number to 5 (meaning D1), it actually works. Kinda. The numbers outputted are strange. Even when I put the board outside, in about -6 Celcius, it still displays

```
Temp 247.208 °C
RH 216.208 %

```

Well, I guess this oddity should be posted as another question. I'll answer my own question here with reference to the weird pin-to-number mapping on the LoLin board.

# Answer
> 1 votes
The problem was that the port mappings on the LoLin board didn't make much sense.

Port D0 is for instance mapped to number 16, not 0.

Go to this Github comment to get a complete list:

```
/*
 * Weird pin mappings on LoLin:
 *
 * static const uint8_t D0   = 16;
 * static const uint8_t D1   = 5;
 * static const uint8_t D2   = 4;
 * static const uint8_t D3   = 0;
 * static const uint8_t D4   = 2;
 * static const uint8_t D5   = 14;
 * static const uint8_t D6   = 12;
 * static const uint8_t D7   = 13;
 * static const uint8_t D8   = 15;
 * static const uint8_t D9   = 3;
 * static const uint8_t D10  = 1;
*/

```

**Missing decimal digits and not able to measure sub zero values**

If this comment on github is correct, the DHT11 sensor *does not offer decimals* and *does not measure values below zero*.

# Answer
> 1 votes
I was scratching my head since last two days over similar issue. I am using ESP8266 NodeMCU which is V2 of LoLin NodeMCU and wanted to read DHT11 sensor data over WiFi into blynk app. However my serial output was 'Failed to read from DHT sensor!'. The program and interfacing was working perfectly with Arduin Uno and Raspberry Pi but not with NodeMCU.

Being a hardware guy, I tried all sorts of hardware modification possible. I had DHT11 sensor module which is already having 5k pull up resistors on board. Since NodeMCU board doesn't have 5V supply, I desoldered the sensor and did direct interfacing with 10k resistor as recommended by adafruit DHTxx guide. Doing internet search , someone recommended IDE version issue, tried that too. Nothing worked.

Finally referring per @nitech answer, I checked the pin details of NodeMCU board and got the idea of D2 pin actual mapped on GPIO4. Just changed the pin 2 with 4 in example code and it worked. Voila! I think recent race in achieving most of the boards as Arduino shield and IDE standard compatible, we need to be used for such issues for any deviation.

# Answer
> 0 votes
The datasheet says 3V-5V. 3V is the minimum so I **DOUBT** that isn't the problem, **BUT** try to pump more juice into it to see what happens. Never believe the datasheet if these cheap components at 100%.

It does say this though:

> VDD=5V, T = 25℃ (unless otherwise stated)

So maybe....

Link to datasheet.

---
Tags: voltage-level, temperature-sensor, nodemcu
---


# Question
Title: Uno pin 13 LED mysteriously always ON at 0.14V unless pinMode OUTPUT
* I upload a blank sketch: pin 13 LED is on. Why?
* I connect pin 13 to GND: it turns off until I remove the connection
* I connect multimeter between pin 13 and GND: measures 0.14V and LED turns off until multimeter is removed
* I press hard reset: LED blinks a few times, turns off for a second then turns on
* I upload a sketch that on setup sets pinMode(13, INPUT): pin 13 LED is on
* I upload a sketch that on setup sets pinMode(13, OUTPUT): pin 13 LED is off 0.01V
* I upload a Blink example: Everything works fine, LED cycles from 4.84V to 0.01V

Why is the LED on unless I set pinMode to output? Have I broken my UNO or is this normal? I swear it wasn't like this a few days ago.

# Answer
> 8 votes
The LED is driven by an op-amp (see the schematic). When the pin is configured as input the op-amp has an undefined input (floating input). Thus it may or may not turn on the LED. If you configure it to an output the op-amp is driven in a known way.

> Why is the LED on unless I set pinMode to output? Have I broken my UNO or is this normal?

It's perfectly normal.

---

I think they did this to stop the LED "loading" the SCK pin (pin 13), particularly if you have it configured as an input and are trying to measure something, the 1k resistor and LED would throw out the measurement.

You could conceivably have a pull-down resistor from SCK to GND, but that would load the pin as well.

# Answer
> 1 votes
Apparently it's normal. Although random. Sometimes the default voltage of the pin is high enough to make the LED light up because of the op-amp. Sometimes it isn't. Source: https://electronics.stackexchange.com/a/39707

# Answer
> 0 votes
If SCK is set as an input then pin 5 of the op amp goes high (pnp transistor input stage) and the op amp output goes high turning on the LED.

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


title: Arduino Yun V2.0.1 can't configure WiFi

text:
# Question
Title: Arduino Yun V2.0.1 can't configure WiFi
I can't configure at 192.168.240.1. It's giving me this message multiple times:

1- AJAX/HAR Error:0 has not allowed Arduino Configuration Wizard to complete.

Details of my board:

Arduino Yun V2.0.1 anders evinrud

# Answer
I have this error too when I typed a wrong password to connect to the green 'osjs' interface. have you changed the password of your board ? have you tried the 2 possible passwords ( "arduino" or "doghunter" ) depends on the image installed ? hacve you cleared your browser cache / test with another browser ?
> 1 votes

---
Tags: wifi, arduino-yun
---


# Question
Title: Yun did not connect to WiFi after configuration and restart
When examined we find that Yun is still in master mode and 0% signal.

Any procedure known to solve this problem manually?

We can access Linux command under Mater mode AP-mode and print WiFi status

```
/usr/bin/pretty-wifi-info.lua

```

We know procedure to change REST API access

```
Method II:  config file

opkg update
opkg install nano
nano /etc/config/arduino

config arduino
        option password '775e9f944188a7bcb36e9ca5dc51672b44bcceeb7d56d89dfb914e$
        option wifi_reset_step 'clear'
        option secure_rest_api 'true'
...

Merhod 1:  UCI API    need access to the Linux system by YSM program

```

PASSWORD

```
uci set arduino.@arduino[0].secure_rest_api=true

```

OPEN:

```
uci commit arduino

```

Is there any procedure manually to perform the configuration by hand for the mode:

* change to client?
* then restart?
* from master mode where we have access to Linux command line?

This question has been left unanswered before in all forums examined. Maybe someone knows the answer.

The problem lies in the Linux not in the hardware or routers or PC, as proven by testing.

# Answer
My wireless config is in the /etc/config/wireless, not in the /etc/config/arduino

How do you configure your Wifi ? There is at least 4 methods :
you can do this through OSJS, through LUCI, through ARDUINO IDE, or with UCI.
> 1 votes

---
Tags: wifi, arduino-yun
---


# Question
Title: Can I control analog IO pins using Yun Linux
2 days back I bought Arduino Yun. I'm able to flash Led on 13 pin. And I'm able to flash Led on Bread board connected to A0. I'm able to run linux commands.

Now I want control A0 pin using Linux/Python program. Is this possible? I read many documents. But I didn't find thing related to this.

**How I can flash the LED using Linux programs?**

# Answer
> 1 votes
There are several libraries which will do this for you. Basically, you should upload a special sketch onto the Arduino, which listens to the serial port, and performs the I/O that the Linux chip requests. Libraries which can do this are

# Answer
> 0 votes
I haven't used a Yun before, but here is my understanding.

The Yun is really 2 separate computers with a bidirectional serial port between them.

The output pins are on the Arduino side. If you want to control Arduino pins from the LINUX side, you need to come up with a simple command syntax for communicating between the 2 computers and write code on both sides that supports that command syntax.

Say the command is:

```
digitalPinx=n;

```

Where x is the pin number, and n is a value, 0 or 1. (for digital pins). For a PWM output pin you could use a command analogPin and values of n from 0 to 255:

```
analogPinx=n;

```

On the LINUX side you'd just send that command through the serial port to the Arduino.

On the Arduino side, you'd write a loop that would wait for data to come into the serial port from the LINUX chip. If it gets data, it would read it into a buffer until it saw a semicolon.

Then it would break the data into separate lines using the semicolon as a delimiter, search for "digitalPin" or "analogPin", parse the data between the command and the semicolon for the values, and issue the digitalWrite or analogWrite command using those values.

# Answer
> 0 votes
I am looking for the same thing. The only thing I have come up with is that you can use the Bridge Library and use curl on the Linux side to read or write the pins

# Answer
> 0 votes
Suggest starting with the the `Mailbox` examples in the Bridge library. Specifically the example http://www.arduino.cc/en/Tutorial/MailboxReadMessage Which shows how to transfer messages to the Arduino processor. It does discuss how to fire the curl process from the command line.

# Answer
> 0 votes
The simpliest thing I've found, is using the command "lininoio start"

then you can use nodejs with https://github.com/ideino/ideino-linino-lib and you no need to worry with the sketch part anymore, just javascript :-)

http://smag0.blogspot.fr/2017/07/smagyun.html

---
Tags: arduino-yun, linux
---


# Question
Title: Unreliable serial communication from Arduino Mega
I'm using an Arduino Mega to send serial commands to a device that supports RS485 or RS422 half-duplex. To do this, I'm using the following code:

```
bool foo(int A, int B)
//...
//Const global int to byte 1&2
//Math on int A and int B to make bytes 3-8
//...
  unsigned char cmd[8]={[byte1],[byte2],[byte3],[byte4],[byte5],[byte6],[byte7],[byte8]};
  while(rep)
  {
    for (int i=0; i< 8; i++)
    {
      Serial2.write(cmd[i]);   // Send C string
    }
    if(Serial2.available())
    {
      //device echoed == command recieved
      rep=false;
    }
  }

```

The odd thing is that sometimes the loop gets it right on the first try, other times it takes 50+ tries to receive a command. This makes me think that there is something in my code that is making the data transmission unreliable. I believe it could be one of the following three things.

---

1. I still need an RS485 module

In a previous version of my software, I was using the software serial library and used an RS485 module similar to the one shown here:

As I'm no longer using the software serial library and instead using the Mega's Serial2 port, I thought I could get rid of the module. Is this incorrect? If so, why would the commands work after N attempts as opposed to never working at all?

---

2. Looping the `Serial2.write()`

Previously, while using the above module, I had to have two lines of code that would shift the DE and RE pins high or low depending on if I was sending or receiving data. I realized that these needed to be outside the `for (int i=0; i< 8; i++)` loop as otherwise, the device would not be able to read/understand the data being passed. Do I need to reimplement some version of this with the Arduino Mega's native serial? If so, how would I do this?

---

3. I'm Not supporting a tri-state the transmit buffer

I was rereading the device's manual and found this line:

> The converter must have the hardware and software support to tri-state the transmit buffer following the message transmission.

Honestly, I have no idea what this means. Does Arduino do this? If not, how can I make this happen?

---

Additional things of note:

* I'd much rather use something like Majenko's pointer way to send data to my device so that I could make the code not rely on the fact that there are always 8 bytes transmitted. However, sometimes a byte will be `\0` (or any other termchar) which would stop the loop prematurely. Is there a way to avoid this?
* I'm still pretty new here, Is there some way that I can do this better than the way I'm currently doing it?

# Answer
> As I'm no longer using the software serial library and instead using the Mega's Serial2 port, I thought I could get rid of the module. Is this incorrect? If so, why would the commands work after N attempts as opposed to never working at all?

You still need the module. RS-485 and RS-422 are electrically incompatible with CMOS.

> Previously, while using the above module, I had to have two lines of code that would shift the DE and RE pins high or low depending on if I was sending or receiving data. I realized that these needed to be outside the for (int i=0; i\< 8; i++) loop as otherwise, the device would not be able to read/understand the data being passed. Do I need to reimplement some version of this with the Arduino Mega's native serial? If so, how would I do this?

Absolutely. Also you need to flush the serial after transmitting and switching back to receiving:

```
digitalWrite(DE_PIN, HIGH);
Serial2.write(cmd, 8);
Serial2.flush();
digitalWrite(DE_PIN, LOW);

```

Flushing the serial pauses your program until the entire command has been transmitted. That means not only sent from the TX buffer to the TX FIFO in the UART hardware, but also the last byte from the FIFO has been shifted out onto the wire. If you don't do that your command will get truncated by the transceiver module as you switch back to receive mode prematurely.

Note: I forget which is which for the DE pin - HIGH/LOW or LOW/HIGH. Change it appropriately. Also note that you don't need to manually loop - the Serial code already has that facility for you.

> The converter must have the hardware and software support to tri-state the transmit buffer following the message transmission.

That is what the DE/RE pins do - switch the module between active drive (transmit) and high-impedance (receive).

> I'd much rather use something like Majenko's pointer way to send data to my device so that I could make the code not rely on the fact that there are always 8 bytes transmitted. However, sometimes a byte will be \0 (or any other termchar) which would stop the loop prematurely. Is there a way to avoid this?

That is only applicable with strings. With binary data you always have to know the length (though that doesn't have to be hard coded). All you need is a *maximum* length for any buffers you have.

> I'm still pretty new here, Is there some way that I can do this better than the way I'm currently doing it?

Besides my notes above, this method:

```
while(rep)
{
  for (int i=0; i< 8; i++)
  {
    Serial2.write(cmd[i]);   // Send C string
  }
  if(Serial2.available())
  {
    //device echoed == command recieved
    rep=false;
  }
}

```

is completely wrong. You are sending a command and then *immediately* looking for a response. You haven't given that response time to either be generated by the remote end or be received by the Mega.

Instead it should be:

1. Send the command.
2. Look for some response data
3. If some data has arrived then add it to the response buffer
4. If the whole response has not yet arrived go back to 2

You can also add 2.5: if it's been checking too long then abort with a "timeout".
> 2 votes

---
Tags: serial, arduino-mega
---


# Question
Title: Changing parameters of pulseIn() to sense different materials
I have a ultrasonic sensor and in order to get the distance I use the pulseIn() function included in the arduino library, and then change it to distance. As the ultrasounds does not work equally in different materials as i have seen in Performance comparison of Infrared and Ultrasonic sensors for obstacles of different materials in vehicle/ robot navigation applications. My question is if there is a way of changing the pulseIn() to have different materials, function:

```
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
{
    // cache the port and bit of the pin in order to speed up the
    // pulse width measuring loop and achieve finer resolution.  calling
    // digitalRead() instead yields much coarser resolution.
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    uint8_t stateMask = (state ? bit : 0);

    // convert the timeout from microseconds to a number of times through
    // the initial loop; it takes approximately 16 clock cycles per iteration
    unsigned long maxloops = microsecondsToClockCycles(timeout)/16;

    unsigned long width = countPulseASM(portInputRegister(port), bit, stateMask, maxloops);

    // prevent clockCyclesToMicroseconds to return bogus values if countPulseASM timed out
    if (width)
        return clockCyclesToMicroseconds(width * 16 + 16);
    else
        return 0;
}

```

or the countPulseASM, which I translate from the asembled code, which can have some errors) as:

```
// wait for any previous pulse to end
while ((*port & bit) == stateMask)
{
        if (--maxloops == 0)
        {
           return 0;
        }
}

// wait for the pulse to start
 while ((*port & bit) != stateMask)
{
    if (--maxloops == 0)
    {
       return 0;
    }
}

// wait for the pulse to stop
 while ((*port & bit) == stateMask)
 {
    if (++width == maxloops)
    {
        return 0;
    }
 }
return width;

```

Another way of doing that is having a correction factor while changing the time into the distance, but for that I shold have the differences of all the materials.

# Answer
`pulseIn` just returns the length of a pulse on a pin. That has nothing to do with materials and can have no concept of materials. It is just time. You cannot change time just to suit different materials.

Instead if you want to calculate the distance depending on different materials you need the actual time of the pulse to then calculate the distance in different ways.

That is down to your sketch to do that calculation using the time provided by `pulseIn` and your own adjustment values.
> 0 votes

---
Tags: sensors, sound, pulsein
---


# Question
Title: Weird behaviour of rotary encoder values
**The plan is to control a NEMA 17 stepper motor with an endless rotary encoder.**

First, I found a code to read the rotary encoders data on www.HowToMechatronics.com by Dejan Nedelkovski. It basically manipulates an integer and outputs it on the Serial Monitor.

Works almost perfectly except that it actually doubles the count of steps the rotary encoder does.
So a clockwise turn subtracts 1, outputs it in the SM, subtracts 1 and outputs it in the SM again. Same in the other direction with adding 1. Although being not a big deal for intended use of the rotary encoder data, I think this has something to do with the problem.

In the code down below you will find a modified version of the code from Mr. Nedelkovski. I added a few lines to move the motor a few steps in each direction.

Clockwise rotation works as I expected.
One step on the rotary equals subtract, output, movement, subtract, output, movement.

But counterclockwise rotation now adds 1 to the rotary position and subtracts it immediately, leaving the motor in moving back and forward.
But if I move the rotary very very slowly it will work.

Why are the rotary values jumping around once I added the lines?
Is there a way to solve this?

**The code:**

```
/*     Arduino Rotary Encoder Tutorial
 *
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *
 *  to make it work with a stepper
 *  modified by me
 *
 */

#include <Stepper.h>

#define outputA 52
#define outputB 50

int counter = 0;
int dir = 0;
int aState;
int aLastState;

Stepper myStepper(200, 47, 49, 51, 53);

void setup() {

  pinMode (outputA,INPUT);
  pinMode (outputB,INPUT);

  Serial.begin (9600);
  // Reads the initial state of the outputA
  aLastState = digitalRead(outputA);

  // set the speed at 60 rpm:
  myStepper.setSpeed(60);

}

void loop() {

  aState = digitalRead(outputA); // Reads the "current" state of the outputA
  // If the previous and the current state of the outputA are different, that means a Pulse has occured

  if (aState != aLastState){
    // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise

    if (digitalRead(outputB) != aState) {

      counter ++;
      myStepper.step(50);

    } else {

      counter --;
      myStepper.step(-50);

    }

    Serial.print("Position: ");
    Serial.println(counter);
  }

  aLastState = aState; // Updates the previous state of the outputA with the current state
}

```

Thanks for taking your time to read this and help me. I hope that a detailed explanation will help solving the problem.

# Answer
Unfortunately, I couldn't find the issue.
BUT I used another approach which worked fine.

I used the ClickEncoder library.
This time, my rotary encoder triggered 4 events per notch.

After a little research I found out, that it's possible to set the steps per notch with this library. I used this code to initiate the ClickEncoder:

```
encoder = new ClickEncoder(A15, A14, A13, 4);

```

The first three arguments define the pins the encoder is connected to. **The last argument sets the steps per notch.** Now it works like a charm!

Full code:

```
#include <ClickEncoder.h>
#include <TimerOne.h>

ClickEncoder *encoder;
int16_t last, value;

void timerIsr() {
  encoder->service();
}

void setup() {
  Serial.begin(9600);
  encoder = new ClickEncoder(A15, A14, A13, 4);

  Timer1.initialize(1000);
  Timer1.attachInterrupt(timerIsr);

  last = -1;
}

void loop() {
  value += encoder->getValue();

  if (value != last) {
    last = value;
    Serial.print("Encoder Value: ");
    Serial.println(value);
  }

  ClickEncoder::Button b = encoder->getButton();
  if (b != ClickEncoder::Open) {
    Serial.print("Button: ");
    #define VERBOSECASE(label) case label: Serial.println(#label); break;
    switch (b) {
      VERBOSECASE(ClickEncoder::Pressed);
      VERBOSECASE(ClickEncoder::Held)
      VERBOSECASE(ClickEncoder::Released)
      VERBOSECASE(ClickEncoder::Clicked)
      case ClickEncoder::DoubleClicked:
          Serial.println("ClickEncoder::DoubleClicked");
          encoder->setAccelerationEnabled(!encoder->getAccelerationEnabled());
          Serial.print("  Acceleration is ");
          Serial.println((encoder->getAccelerationEnabled()) ? "enabled" : "disabled");
        break;
    }
  }
}

```
> 1 votes

---
Tags: arduino-mega, stepper, rotary-encoder, l298n
---


# Question
Title: Arduino port relocation (PORTD to PORTB)
So I'm trying to connect the chip with an 8-bit data bus. All works good, but...

Arduino Uno uses D0 and D1 for serial TX/RX (USB connection with PC). When I try to open a serial connection (on serial.begin stage) ports D0 and D1 blocks and the chip stops working. This is a problem.

I think I should relocate pins D0 and D1 to another port. But the chip uses 8 pins (8bit chip). So I need to relocate the first pin (D0) and the second pin (D1) to port b. Maybe I can use B4 and B3?

But I don't know how to use PORTD\[PD2, PD3, PD4, PD5, PD6, PD7\] and PORTB\[PB4, PB3\] in one time like:

```
var portX = PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];
portX = data;

```

My code:

```
#include <avr/io.h>     // For I/O and other AVR registers
#include <util/delay.h> // For timing

/* Pinmap (Arduino UNO compatible) */
#define YM_IC (5) // PC5 (= pin A5 for Arduino UNO)
#define YM_CS (4) // PC4 (= pin A4 for Arduino UNO)
#define YM_WR (3) // PC3 (= pin A3 for Arduino UNO)
#define YM_RD (2) // PC2 (= pin A2 for Arduino UNO)
#define YM_A0 (1) // PC1 (= pin A1 for Arduino UNO)
#define YM_A1 (0) // PC0 (= pin A0 for Arduino UNO)
#define YM_CTRL_DDR DDRC
#define YM_CTRL_PORT PORTC
#define YM_DATA_DDR DDRD

#define YD0 (0)(= pin D0 for Arduino UNO)
#define YD1 (1)(= pin D1 for Arduino UNO)
#define YD2 (2)(= pin D2 for Arduino UNO)
#define YD3 (3)(= pin D3 for Arduino UNO)
#define YD4 (4)(= pin D4 for Arduino UNO)
#define YD5 (5)(= pin D5 for Arduino UNO)
#define YD6 (6)(= pin D6 for Arduino UNO)
#define YD7 (7)(= pin D7 for Arduino UNO)

#define YM_DATA_PORT PORTD // Whole PORT D for data bus (= pins D0 to D7 for Arduino UNO)
#define YM_MCLOCK (1) // PB1 = OC1A (= pin D9 for Arduino UNO)
#define YM_MCLOCK_DDR DDRB

extern uint8_t chflash[6];
uint8_t dacflash;
#define NOTEONFLASH 4
#define VGMWAIT 15

static void write_ym(uint8_t data) {
  YM_CTRL_PORT &= ~_BV(YM_CS); // CS LOW
  YM_DATA_PORT = data;
  _delay_us(1);
  YM_CTRL_PORT &= ~_BV(YM_WR); // Write data
  _delay_us(5);
  YM_CTRL_PORT |= _BV(YM_WR);
  _delay_us(5);
  YM_CTRL_PORT |= _BV(YM_CS); // CS HIGH
}

/**
 * Write data into a specific register of the YM2612
 *
 * @author Furrtek
 * @param reg Destination register address
 * @param data Data to write
 */
static void setreg(uint8_t reg, uint8_t data) {
  YM_CTRL_PORT &= ~_BV(YM_A0); // A0 low (select register)
  write_ym(reg);
  YM_CTRL_PORT |= _BV(YM_A0);  // A0 high (write register)
  write_ym(data);
}

void call() {
  setreg(0x28, 0xF0); // Key on
  _delay_ms(1000);
  setreg(0x28, 0x00); // Key off
}

uint8_t getfilebyte() {
  return Serial.read();
}

int main() {
  init();

  //Serial.begin(9600);
  /* Pins setup */
  YM_CTRL_DDR |= _BV(YM_IC) | _BV(YM_CS) | _BV(YM_WR) | _BV(YM_RD) | _BV(YM_A0) | _BV(YM_A1);
  YM_DATA_DDR |= _BV(YD0) | _BV(YD1) | _BV(YD2) | _BV(YD3) | _BV(YD4) | _BV(YD5) | _BV(YD6) | _BV(YD7);
  YM_MCLOCK_DDR |= _BV(YM_MCLOCK);
  YM_CTRL_PORT |= _BV(YM_IC) | _BV(YM_CS) | _BV(YM_WR) | _BV(YM_RD); /* IC, CS, WR and RD HIGH by default */
  YM_CTRL_PORT &= ~(_BV(YM_A0) | _BV(YM_A1)); /* A0 and A1 LOW by default */

  /* F_CPU / 2 clock generation */
  TCCR1A = _BV(COM1A0);            /* Toggle OCA1 on compare match */
  TCCR1B = _BV(WGM12) | _BV(CS10); /* CTC mode with prescaler /1 */
  TCCR1C = 0;                      /* Flag reset */
  TCNT1 = 0;                       /* Counter reset */
  OCR1A = 0;                       /* Divide base clock by two */

  /* Reset YM2612 */
  YM_CTRL_PORT &= ~_BV(YM_IC);
  _delay_ms(10);
  YM_CTRL_PORT |= _BV(YM_IC);
  _delay_ms(10);

  /* YM2612 Test code */
  setreg(0x22, 0x00); // LFO off
  setreg(0x27, 0x00); // Note off (channel 0)
  setreg(0x28, 0x01); // Note off (channel 1)
  setreg(0x28, 0x02); // Note off (channel 2)
  setreg(0x28, 0x04); // Note off (channel 3)
  setreg(0x28, 0x05); // Note off (channel 4)
  setreg(0x28, 0x06); // Note off (channel 5)
  setreg(0x2B, 0x00); // DAC off
  setreg(0x30, 0x71); //
  setreg(0x34, 0x0D); //
  setreg(0x38, 0x33); //
  setreg(0x3C, 0x01); // DT1/MUL
  setreg(0x40, 0x23); //
  setreg(0x44, 0x2D); //
  setreg(0x48, 0x26); //
  setreg(0x4C, 0x00); // Total level
  setreg(0x50, 0x5F); //
  setreg(0x54, 0x99); //
  setreg(0x58, 0x5F); //
  setreg(0x5C, 0x94); // RS/AR
  setreg(0x60, 0x05); //
  setreg(0x64, 0x05); //
  setreg(0x68, 0x05); //
  setreg(0x6C, 0x07); // AM/D1R
  setreg(0x70, 0x02); //
  setreg(0x74, 0x02); //
  setreg(0x78, 0x02); //
  setreg(0x7C, 0x02); // D2R
  setreg(0x80, 0x11); //
  setreg(0x84, 0x11); //
  setreg(0x88, 0x11); //
  setreg(0x8C, 0xA6); // D1L/RR
  setreg(0x90, 0x00); //
  setreg(0x94, 0x00); //
  setreg(0x98, 0x00); //
  setreg(0x9C, 0x00); // Proprietary
  setreg(0xB0, 0x32); // Feedback/algorithm
  setreg(0xB4, 0xC0); // Both speakers on
  setreg(0x28, 0x00); // Key off
  setreg(0xA4, 0x22); //
  setreg(0xA0, 0x69); // Set frequency

  call();

  while(1000) {
    if (Serial.available() > 0) {
      _delay_ms(1000);
      call();
      _delay_ms(1000);
      char var = getfilebyte();
      Serial.print("Yeah: ");
      Serial.println(var);
    } else {
      Serial.print("Nooo: ");
      Serial.println(Serial.available());
      call();
    }
  }
  while(1);
}

```

# Answer
You cannot set pin states in multiple ports simultaneously, if that's what you're asking.

At the instruction set level, setting pin states is a single that writes to an 8-bit register which corresponds to the 8 pins in a port. There is no way to write to two different registers in the same instruction, so if you need all eight bits to change exactly at the same time you're out of luck. However, if you can tolerate a little bit of time between 6 bits in one port changing state and 2 bits in another port changing state, then you can simply write a wrapper function.

```
PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];
void set_ym_ctrl_port(uint8_t data) {
    PORTD &= ~(0x3f<<2);
    PORTB &= ~(0x3<<3);
    PORTD |= (data & (0x3f<<2));
    PORTB |= (data & 0x3)<<3;
}

```

Or something like that. If you need even less delay and you think you can do better than the compiler, inline assembly can be helpful.

As an aside, syntax like

```
var portX = PORTD[PD2, PD3, PD4, PD5, PD6, PD7] + PORTB[PB4, PB3];

```

is not valid for a number of reasons.
> 8 votes

# Answer
Adding to what @uint128\_t said, if you really need to change the state of many pins at the same time, you can add some external latched shift registers as a SIPO (serial-in/parallel-out) interface towards the outer world.

The price you pay is that you have to load the entire register with the data you want to send before you can update the output pin states. This requires a clock cycle for each loaded bit (here I'm speaking of the clock of the external register, not Arduino's) and thus may add too much latency in your system, depending on what you are trying to do.

The 74HC595 is a classic (8-bit shift register with output latches), and can be cascaded to obtain a register of the desired width.

Here is an excerpt from the datasheet of TI's 74HC595 (yellow emphasis mine):

>

It's also sold in 16-pin DIP package, very convenient for breadboarding, in case you need it (common need for people that play with Arduinos).

The internal logic diagram is the following (from the same datasheet):

>

It is so common in the Arduino world that there are also open libraries do drive it, for example this. But even without pre-written libraries, it is not difficult to drive it from an Arduino, if you have a little experience in digital logic and can understand the timing requirements stated in its datasheet (the table in section 7.6 is fairly easy to understand, once you know what setup and hold times are).
> 4 votes

# Answer
This is intended as a complement to uint128\_t's answer. I would like to point out that the code in that answer changes the outputs in four steps:

1. set to `LOW` the pins of `PORTD` that need to be `LOW`
2. set to `LOW` the pins of `PORTB` that need to be `LOW`
3. set to `HIGH` the pins of `PORTD` that need to be `HIGH`
4. set to `HIGH` the pins of `PORTB` that need to be `HIGH`

I compiled it on my system (with gcc 5.4.0): the generated assembly shows that the whole process takes 18 CPU cycles. I.e. during 1.125 µs the outputs can be in an inconsistent state.

I then tried this alternative version:

```
void set_ym_ctrl_port(uint8_t data) {
    uint8_t new_portd = PORTD & ~(0x3f<<2) | (data & (0x3f<<2)),
            new_portb = PORTB & ~(0x03<<3) | (data & 0x03)<<3;
    cli();
    PORTD = new_portd;
    PORTB = new_portb;
    sei();
}

```

This changes the outputs on two steps:

1. update `PORTD`
2. update `PORTB`

The generated assembly showed that the updates are only one CPU cycle apart. I.e. the outputs are inconsistent during only 62.5 ns.

Your mileage may vary. In case of doubt check the generated assembly.
> 0 votes

---
Tags: c
---


# Question
Title: How to get Arduino to talk to two seperate motors wirelessly?
I have an Arduino Uno and I also have two Servo Motors. Say I have a room that is 15 feet wide, and I want to be able to place the Arduino in the center of the room and control two servo motors placed at each end of the room using a button on the Arduino. Is it possible to wirelessly communicate with these two servo motors using just one Arduino and bluetooth transmitters/receivers? Or will I have to use three Arduinos, one for the center with the button and one for each servo. If so, will I be able to substitute the two servo Arduinos with an ATtiny chip?

# Answer
> 1 votes
You'll probably need 3 "controllers", of which the one in the middle of the room might need to be a full-featured Arduino. Depending on the the needed libraries of your bluetooth receivers at the remote servos, it seems likely that you could use ATTinys in place of more feature-filled Arduino, but you would still have to think of the ATTinys as Arduinos or at least the glue controller to translate commands from Bluetooth to servo signals (PWM).

You could provide us with more details, such what particular bluetooth modules or transceivers you plan to use; some might provide an asynchronous serial interface, others might present an I2C or SPI interface, and given the small flash and RAM size in the ATTiny line, you would need to evaluate the code and associated libraries needed to operate it on such a processor.

The answer to your question is, "Maybe", given the small amount of detail you have provided.

# Answer
> -1 votes
> Is it possible to wirelessly communicate with these two servo motors using just one Arduino and bluetooth transmitters/receivers?

Yes. The process goes like this:

1. Can you get your Arduino to talk?
2. Can you get your Arduino to talk to one servo via wires?
3. Can you get your Arduino to talk to one servo wirelessly? R. Can you get your Arduino to talk to two servos wirelessly?

> Or will I have to use three Arduinos, one for the center with the button and one for each servo.

That's certainly one aporoach.

> If so, will I be able to substitute the two servo Arduinos with an ATtiny chip

It certainly can be done. Whether you can do it is unknown to anyone but you.

---
Tags: arduino-uno, servo, wireless
---


# Question
Title: Nano-like Board - Programmer Not Responding
I am trying to upload a basic sketch to my unofficial Nano-like board and keep getting this error. I understand that it is a generic connection error between the Arduino and my PC, but can't figure out why it is having this problem.

I've looked up the drivers from the manufacturer's website and installed them, and the Arduino Nano shows up just fine under my Device Manager. The green power light comes on, it is recognized by my PC, and blue flashing 'L' light blinks, making me think that the manufacturer had uploaded the Blink sketch to test it. However, when I try to upload a sketch from the IDE I get this error:

```
avrdude: stk500_recv(): programmer is not responding

```

Under 'Tools" I have the board set to 'Arduino Nano', the processor set to 'ATmega168' and the port the **same COM port as what it's listed as in Device Manager**. Assuming that all of those are correct, I have tried a few things with no luck:

* Reinstalling the IDE, drivers and restarting my computer.
* Letting Windows find its own driver.
* Pressing the 'reset' button just before hitting 'upload' in the IDE
* Using different micro USB cables and USB ports on my computer.

Any other ideas or is the unit possibly just faulty?

**Please note that I have already at similar questions and tried a bunch of their suggestions with no luck.**

# Answer
That is a Chinese NANO clone, using the notorious CH340G chip.

`macOS` does **NOT** have a driver, and it is difficult, if not impossible to get a driver which 1. `macOS` will let you install, and 2. Actually works.

I do not know the state with current Windows.

In my experience, in addition to poor support the chips are unreliable and fail to respond.

You could try using a Uno as ICSP, bypassing the boot loader, or (untried) use an external USB serial interface. Both of these approaches are documented on the Arduino site.
> 2 votes

# Answer
For issues like this, you have to narrow down the problems first. For example

is the computer plus programmer combo able to program any avr? If so, the issue us with your target, including wiring.

If not, can the programmer able to program any chip? If so, the issue is with your pc plus programming software.

...

Going backwards and with solid logic, which means making zero assumption, you will narrow the issues down further.
> 0 votes

# Answer
It's a wiring problem (soldering), check by multimeter (continuity mode). between RST and GND. Then between ICSP pins. you have to get (1) that mean no shorts between the PINS. Good luck!
> -1 votes

---
Tags: arduino-ide, arduino-nano, clones, ch340
---


# Question
Title: Arduino library not working, can't find header
I have fair experience with C/C++ so I decided to have a go at writing my first simple Arduino library. I wrote the code which seems to be fine to me except that it keeps complaining about the header file not found during compilation:

```
/home/me/sketchbook/libraries/SegDisplay/SegDisplay.cpp:1:24: fatal error: SegDispaly.h: No such file or directory
 #include "SegDispaly.h"
                        ^
compilation terminated.

```

I have the library located in my sketch folder under the name "SegDisplay":

```
/home/me/sketchbook/libraries/
└── SegDisplay
    ├── examples
    ├── keywords.txt
    ├── README.md
    ├── SegDisplay.cpp
    └── SegDisplay.h

```

and here's the code:

### SegDisplay.h:

```
#ifndef _SEVEN_SEG_H_
#define _SEVEN_SEG_H_

#include <math.h>

#if defined(ARDUINO) && (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif

class SegDisplay
{
public:
    SegDisplay (int clockPin, int latchPin, int dataPin, int digitPins[4]);
    void display (double value);

private:
    const int digitPins[4];
    const int clockPin;
    const int latchPin;
    const int dataPin;
    const byte digit[10] = //seven segment digits in bits
    {
        B00111111, //0
        B00000110, //1
        B01011011, //2
        B01001111, //3
        B01100110, //4
        B01101101, //5
        B01111101, //6
        B00000111, //7
        B01111111, //8
        B01101111  //9
    };
    int digitBuffer[4];

    void setRegisterData (byte data);
    void clearRegister();
    void clearDisplay();
    void updateDisplay();
};

#endif

```

### SegDisplay.cpp:

```
#include "SegDispaly.h"

SegDisplay::SegDisplay (int a, int b, int c, int d[4]):
    clockPin (a), latchPin (b), dataPin (c), digitPins (d), digitBuffer ({0})
{
    for (int i = 0; i < 4; i++)
    {
        pinMode (digitPins[i], OUTPUT);
        digitalWrite (digitPins[i], HIGH);
    }
    pinMode (latchPin, OUTPUT);
    pinMode (clockPin, OUTPUT);
    pinMode (dataPin, OUTPUT);
}

void SegDispaly::setRegisterData (byte data)
{
    digitalWrite (latchPin, LOW);
    shiftOut (dataPin, clockPin, MSBFIRST, data);
    digitalWrite (latchPin, HIGH);
}

void SegDispaly::clearRegister()
{
    setRegisterData (B00000000);
}

void SegDispaly::clearDisplay()
{
    // deactivate transistors
    for (int n = 0; n < 4; n++) digitalWrite (digitPins[n], HIGH);
}

//writes the temperature on display
void SegDispaly::updateDisplay()
{
    byte outByte;
    // dispaly digits
    for (int i = 0; i < 4; i++)
    {
        clearDisplay();
        clearRegister();

        // enable nth cell cathode (transistor)
        digitalWrite (digitPins[i], LOW);

        // output nth digit on display
        if (i == 1)
        {
            //print the decimal point on the 2nd digit
            outByte = digit[digitBuffer[i]] | B10000000;
        }
        else outByte = digit[digitBuffer[i]];
        setRegisterData (outByte);

        //delayMicroseconds (500);
        delay (5);

        //Serial.print (outByte, BIN);
        //if (i == 3)
        //{
        //  Serial.println (".");
        //}
        //else Serial.print (", ");
    }
}

void SegDispaly::display (double value)
{
    int n = int (value * 100);
    digitBuffer[0] = n / 1000;
    digitBuffer[1] = (n % 1000) / 100;
    digitBuffer[2] = (n % 100) / 10;
    digitBuffer[3] = (n % 100) % 10;
    updateDisplay();
}

```

My target AVR is Arduino Uno R3, the code used to work fine in a sketch before I decided to create a library out of it. Any help would be greatly appreciated. thanks in advance.

# Answer
> 3 votes
You spelled the header filename wrong:

```
#include "SegDispaly.h"

```

should be:

```
#include "SegDisplay.h"

```

You have also made the same mistake in the class name multiple places in SegDisplay.cpp.

---
Tags: c++, library, compilation-errors
---


# Question
Title: Trying to flash ATTiny85 bootloader using FT232R in the Arduino IDE
I have a FT232R that I want to use to flash my ATTiny85 bootloader in the Arduino IDE, can someone help me out on this? I don't want to get a AVR programmer.

# Answer
A bootloader is a program that gets loaded into the bare microcontroller to handle a number of low level tasks. One of those tasks is the ability to load a program over UART (serial).

As such, the bootloader can be loaded into the microcontroller using a AVR programmer. Once this has occurred, you can then easily load in programs with the FT232R.

It is possible to use the bitbang mode on the FT232R to load the bootloader into an Arduino board, hence replacing the AVR programmer. So, it can work but it isn't easy.

As suggested by per1234, there is some instructions on how to do this to an Arduino Diecimila on the Adafruit website: Programming the Arduino Bootloader In general the full page has a lot of useful information: Full page
> 1 votes

---
Tags: arduino-ide, attiny, bootloader, ftdi, attiny85
---