# Question
Title: How to trigger an alarm when toilet paper is low?
Anyone with kids knows they never help with the toilet paper. Anyone know how to track when it's low or out and sound an audible alarm? I just don't know what sensor to use that may help.

Some that came to mind are: by weight, by reflection (the color of the paper) or some laser tripwire - all right on the spool. I don't mind building it, it's just I don't know which sensor. Anyone know which to use?

# Answer
Bring up several rolls at a time and hang one for use. Put the other two on a short vertical pole within reach of the sitter. Sitter can take another roll when needed.

Mechanically sense lack of weight on the shelf at the bottom of the pole. Alarm triggers when the last roll is removed. No one has to get caught short.

To sense the weight use a force sensitive resistor such as the FSR 400 (see datasheet). Alternatively, you could use a lightweight coil spring to rest the toilet paper on with a micro switch that is released when both rolls are removed. Another option would be an IR beam break detector where the circuit is completed when the last roll is removed.
> 47 votes

# Answer
I believe the reed sensor concept put forth by jfpoilpret and jmathew is the easiest to accomplish. I have drawn a diagram of how I think it would look.

You could adjust sensitivity by adjusting the height of the lower contact.

This really only gets you to a "low" condition and not necessarily out. Unless you want to change rolls while there are still a few sheets left this doesn't seem to me to be a satisfactory solution. I'd rather have an "out" indicator and have an audible buzzer to prompt/shame the user into replacing the roll.

This design could be accomplished using standalone electronics (no arduino needed). However it you wanted to gamify the changing of the roll you could use an arduino for that.

Note also for color based optics sensors, while the vast majority of cardboard tubes used for this purpose are brown, I have seen white ones in use as well.
> 22 votes

# Answer
I think I saw this in series 1 episode 2 of James May's Manlab.

Similar to jfpoilpret, use a wide piece of material on a spring that makes contact with the roll at all times. I say 'wide' so that when the roll is empty the reed touches with a contact on one of the roll holders on the side. When it touches it completes a circuit to your alarm.

Here's a crude image describing what I mean.

In Arluin's response it was mentioned that this method would not show that the the roll was empty. Thats pretty much true. If the top contact is as thick as the TP cardboard roll and the bottom contact is positioned inside the inner part of the cardboard roll it should get close enough for practical purposes. One foot of TP roll is not enough after taco night.
> 14 votes

# Answer
Use a radiation detector to detect the amount of paper left on the roll. Place some amount of radioactive material in the middle of the spool rod, and place the radiation detector somewhere else (you could mount it on the other side of the surface the roll holder is mounted to, if you want; radiation sensors are extremely flexible), and measure the radiation amounts to determine how much paper is left on the roll.

Alternately, you could have an electronically controlled toilet paper dispenser (push button to dispense a preprogrammed length of toilet paper) and have the arduino just keep track of how much has been dispensed.

Or, attach a rotary encoder to the side of the spool rod (make sure it fits without slipping inside the roll), and count the rotations of the roll to determine how much has been used.

Of course, with any of these methods, you will have to do tests and collect data depending on the exact type/brand/material/etc of toilet paper.

Especially for the second and third ideas, I would recommend taking data from the system regularly, to keep track of the typical length of a roll so you can adjust the program for any significant variation. Even within one type of toilet paper, I would imagine that there would be some variation in roll length.

For even more fun, you could instrument the detector to collect time series data, so later you can upload it to a computer and make a "toilet paper usage over time" graph or something.
> 9 votes

# Answer
I think 'Arluin' and 'jmathew' have the right idea. Use a lever resting on the top of the roll.

I would do it slightly different however. Rather than rely on contacts shutting you can use a potentiometer. With this system you can measure the amount left instead of simply being notified when it gets low.

With a contact such as those suggested already, you might get paper stuck in the contact as it closes and then low paper would not be detected.

(You may need a weight, shown in blue on the diagram, to push the lever down as the roll is used)

You would need to try and get the pot as close to the roll as possible for maximum swing of the pot and therefore maximum resolution of amount remaining.

Another thing you might want is some kind of roller on the end of the lever so that the paper roll can move easily with little drag where the lever contacts the paper.
> 7 votes

# Answer
You could just crack open one of those playing birthday cards and adapt the switch to the holder arm. Once you hear 'Happy Birthday" chiming from the toilet you know you're in trouble! (and because they are very low-power these things chime on forever ;-) ) I've shown a LED setup here but you get the idea...
> 5 votes

# Answer
I built a reflectance tachometer for an Arduino that'd probably solve your problem. The basic circuit is quite simple:

I had a photoransistor laying around that responded well to red light, and another from Radio Shack that was quite sensitive to the IR output of old TV remote LED's. For your purposes, green wire would be hooked up to Analog Pin 0 of Arduino, and you just have to sample periodically, not set up an interupt driven sketch. The trick to getting a reflected signal difference between white paper and grey roll is knowing that light sensitivity of a photransistor increases w increasing resistance to GND, but the dark voltage also goes up. I came by the 5 and 3 megohm values empically, by checking the AtoD values off dark and light objects at a distance of a few inches from the detector. Same procedure should work for your detection of grey vs white. Although some things that look quite different visibly have the same reflectance in IR. Here's a pic of the finished red light tachometer:

It should be simple to make the sensor board small enough to fit into the back of your paper dispenser. IR version is even smaller, but buried too deeply in a home-built centrifuge to get a pic of it today.
> 3 votes

# Answer
I think another decent and cheap option to use is a proximity sensor like the ones on the phone or a fixed field infrared sensor. These sensor are pretty accurate and can easily be used to "look" at the back of the toilet roll by mounting the sensor to the holder or the wall where the toilet roll is placed. All the other ideas I saw on the post were either fairly inaccurate or felt intrusive towards the toilet roll which in the long run I feel may provide contamination. A proximity sensor is not only fairly cheap and easy to use, if calibrated well, they can allow a very good amount of accuracy and reliability. This model is already in wide usage in men urinals to auto-flush. For example on your phone: Your phone will accurately provide a distance of 2.0 inches or infinity when your hand or your face is near the screen.
> 3 votes

# Answer
One idea that comes to mind would be something like that:

* stick a small magnet inside the paper roll, i.e. inside the cardboard part (this has to be done every time you change it; though)
* use a reed contact (electro-magnetic switch) at the tip of a stick mounted with a spring to be always in contact with the paper roll
* one pin of the reed contact can be directly connected to an input logical pin (set it up as a pullup resistor input)
* the other pin of the reed contact is to be connected to the ground

Thus, as soon as the distance between the magnet and the reed contact is under some limit, the switch will close the circuit. That distance will decrease while the paper roll gets drawn.

Note that, instead of a reed contact, you may also use a Hall Effect sensor, the principles remain the same, only technology and characteristics change.

The difficulty here will be to find the right sensitivity of the reed contact (or the force of the magnet) so that the reed contact gets closed when the distance between it and the magnet is small enough to avoid an alarm that would be activated too soon).
> 2 votes

# Answer
An short-range ultrasound distance sensor might be an effective (and fairly cheap) option. You can get an emitter+sensor combination mounted on a chip. Different sensors may work in different ways (always check the datasheet). A common output though uses the length of a pulse to indicate the distance sensed. You could process that in Arduino using the `pulseIn()` function.

In terms of installation, you'd probably fit it directly behind the toilet paper, pointing at the centre of the spool. The readings are often quite erratic, so you want to take several measurements and average them (or use a simple moving average). With a bit of calibration, you could determine what distance represents an empty spool.

When you detect that distance repeatedly for a significant period (e.g. a minute or more), you'd sound the alarm.

A reflectance-based sensor might be another possibility, although I wonder if you might struggle to find one which will work properly on toilet paper (depending on how soft your preferred brand is!).
> 2 votes

# Answer
Sounds like a cool project, here are my 2 ct:

Point a camera to take photos of the roll from sideways, that is probably the only way to really find out how much paper is left. (edit: You could use a raspberry pi with the csi camera and create an output signal corresponding to the number of sheets and feed that signal to the arduino?!)

For an estimate it might also be enough to count rotations of the roll, but you need to fiix the roll better so it doesn't slip. Or you can use magnets like you do on bicycles, but they need to be attached to the roll directly then.

(edit: one more idea, mesure the thickness of the roll by measuring the angle of the lid)
> 2 votes

# Answer
The simplest, yet best solution afaict, would be to use an optocoupler made of one IR LED and an opto-transistor. You make the LED lighten towards the roll, the LED being within the roll tied to the "handle". Once you remove the cardboard roll, the opto-transistor gets the IR light from the LED and triggers a pin change interruption on the Arduino, which can then alert you through many ways (light, SMS, twitter, alarm…).

That design is really cheap, easy and fast to build. Though there's still one thing you need to do: when there's no more toilet paper, you need to actually have the cardboard roll *removed* ;-)

Otherwise, the same kind of solution for the spare rolls is even a better idea :-)
> 2 votes

# Answer
A lot of the options here seem overcomplicated and intrusive.

## Color Sensor

Another option, slightly complicated (but fun) to implement, but unintrusive and easy-to-install, is to build a cheap color sensor and mount it on the wall behind the roll. When you detect the color of the roll (or the absence of the color of TP), it's low.

You can also just buy one for $8.

You can adjust the threshold by taking advantage of the thinness of TP and the fact that it starts to look a little darker when there's only a few sheets left.

If necessary, calibration can be done by pressing a button after a new roll is installed with the bathroom lights on.

You would have to make a few adjustments depending on the specifics of your bathroom. If you added some extra complexity and powered it off an AC outlet that was tied to the bathroom light switch, you could only have it powered on when the bathroom lights were on, which would filter out a lot of unreliable data.

This is very easy to install and doesn't involve modification to the roll itself. You could stick the sensor to the wall with double-sided tape, or put it on a tiny shelf under the roll facing up (or on top facing down).

## IR beam break

Mount a small IR LED on one side of the dispenser, just above the spool. Mount an IR photo sensor on the other side of the dispenser. When the sensor sees the LED, the roll is low. Could be done with a cheap laser too (e.g. an off the shelf laser pointer on one side and a photosensor on the other; but don't hurt your eyes!)

This is also easy to install (e.g. hot glue to dispenser) and doesn't involve modification to the roll, although the location of the sensors might make them easy to damage when you're replacing rolls.

---

I also really like the reed sensor and range sensor (BTW: $10 gets you a great short range distance sensor) options here.
> 2 votes

# Answer
## You have a few options:

Note: The links given are just the first ones that come up. Most of them are pricey compared to other sites. eBay buy it nows can be fairly cheap for most of these items. Check other places, too, including Sparkfun.

* Ultrasonic Ping Sensor. This isn't ideal by any means, but they're easy to use. Just add one with an enclosure. It isn't ideal because it won't be accurate enough to tell when exactly it's empty. It might be a little over/under sensitive. Weight would be harder, though if it shifts at all.
* Color sensor (preferable, but costs more). You mentioned this and this is probably the best idea. It'll give you analogue values (to read with Arduino) for red, green, and blue. \[Assuming that the higher the content of that color, the higher the voltage,\] white should be pretty much all of those at 100% and brown I would image that most of them would be about 30-40%. (More later, if you don't understand this, skip this part)

---

**I'm going to go into more detail on the color sensor:**

Colors are read with three values here: red, green, and blue. There are three sensors on the board. One filters out everything except red, another blue, and the other green. The sensors on the board detect the amount of incoming light and then convert that to a voltage: between 5V ("100% red/green/blue") or 0V ("0% red/green/blue"). This then can be converted into a number by the Arduino (0-1024 on an analogue pin).

**A problem with lighting:** This sensor, from what I can tell, has a LED that's always on. You'll want to either desolder that or cover it up, unless you want an illuminated toilet paper holder. Now wait... your sensor will think that when it's dark, it's brown. No problem... here's something for you mind to think about.

Use a color picker like I'm using and select a brown. On the left of this one, you can control the "simulated brightness." Besides that is the hexadecimal form of RGB. You'll want to convert that to standard values with this calcuator.

In brown, the color blue is almost nonexistent. We should ignore that color, unless you want a way to double check that it's brown. I'd say it should always be under 40% for pretty much any shade of brown.

From what I can tell with a sample shade of brown, the red is pretty much 2x the green. That ratio may vary, but you should verify that it is *somewhat* existent. For white/grey/black, all the colors are proportional 1:1:1. You can use this to detect if it's dark, or if it's brown.

```
int rPin = A0;      //Red Pin
int gPin = A1;      //Green Pin
int bPin = A2;      //Blue Pin
int ledPin = 13;    //I made this code with a LED, not a speaker
boolean testTwice = false;

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

void loop() {
  int rValue = analogRead(rPin);
  int gValue = analogRead(gPin);
  int bValue = analogRead(bPin);

  if (bPin < 256) { //If this is false, either something is in the way or it's white. Going to verify that something's not in the way...
    int minRed = rPin * 0.4; //A little under a half for padding... this values may need to be adjusted. Adjust this one and the one below farther apart for less sensitive.
    int maxRed = rPin * 0.6; //A little over a half for padding... this values may need to be adjusted.
    if (gPin < maxRed && gPin > minRed) { //Verifys that red between minRed and maxRed
      digitalWrite(ledPin, HIGH);
      delay(5000);
      digitalWrite(ledPin, LOW);
    }
  }
  delay(5000); // No need to waste power... you might want to add an actutal sleep function if on battery power
}

```

First, it verifies that the blue is less than 25%. Then, it verifies that the red and green are equal... give or take 20%. (i.e. red = 100 green = 80, red = 110 green = 90, etc.). If that is true, you can pretty much establish that it's brown. Then, a LED turn on for five seconds.

You can modify the LED to be a buzzer if you want. You might have to adjust the if statement with verifying that the blue is less than 256/1024 (1024 = resolution of analog pin) if it isn't working in a lot of light or is working in dark light. Since the code later verifies that the red is about 2x the green, any shade of white shouldn't pass that if statement. You may also have to adjust the `minRed` and `maxRed` to be farther (if not detecting brown) or closer (if detecting brown when it's white). I can't really test this code with no color sensor.

---

Note: these can be a little fidgety. **I would recommend a LED instead** so the whole house isn't woken up in the middle of the night just because of low toilet paper. Also, if you obstruct the sensor at all... If it wasn't in the bathroom, I would recommend a camera and have it take a shot every time it gets very low with a reed switch like @jfpolipret's answer... but... (no pun intended) :)
> 1 votes

# Answer
Your best option is attaching a rotary encoder to the side of the roll, and count the rotations of the roll to determine how much has been used. Once you know the number of rotations per roll,you can set where you want your notification to fire. Attach it to a logging system of sorts and you'll have historical data of paper use as well as toilet use.
> 1 votes

# Answer
I say get a weight sensor, and program it for the roll's weight. When it drops below a certain weight, start flashing an LED or make a beep.
> 1 votes

# Answer
Another way to do it, in case you just want to for the fun of it would be to put a metal rod inside the roll, and a metal plate on the outside, and measure the capacitance which should change with the TP remaining due to the dielectric constant of the paper.

But that would be taking the "scenic route" for sure. Still, the Arduino can measure capacitance pretty easily and it might even be sensitive enough, and it would stay out of the way because it would just be a metal plate behind the roll and a metal rod in the roll. You might even be able to retrofit an existing holder without it being noticed.

An easier way would be a stick attached to the shaft of a potentiometer held up by the top of the roll. Less TP, shaft goes lower and turns the pot. Might need a long shaft for leverage because you can't press too hard without impeding the function of pulling toilet paper.

As AJMansfield suggested, Radioactivity actually is used to measure the thickness of things in industrial settings. If you really wanted to go crazy maybe you could use an extremely low energy radioactive source like a can of that weird tasting salt substitute which is a tiny bit above background levels and average over extremely long times(toilet paper shouldn't change much from hour to hour), so this could actually be a reasonable if expensive way to do things.

Infrared beam break sensors are also good, and if you position it right you could get it to block more light the fuller the roll was instead of just giving you and on or off signal.

EDIT: Working Proof of concept of the capacitative approach. Only needs an arduino and 2 stiff wires. Precise to about an 8th of an inch, with a lot of noise. Pretty sure you could reliably get at least 1inch accuracy. Measurement time is about a minute. It's really sensitive to it's surroundings. You'd have to make sure anything metal within a foot stayed where it was or use shielding.

```
float difference;
unsigned long i;
unsigned long j;
unsigned int temp;
volatile unsigned char blah;

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

void loop()
{
 difference =0;
 Serial.print("Measuring: ");

 for(i=0;i<100;i++)
   {
     for(j=0;j<5000;j++)
     {
       digitalWrite(5,LOW);

       temp=analogRead(A0);

       digitalWrite(5,HIGH);

       temp = analogRead(A0)-temp;
       if(temp<1024)
       {
         difference += temp;
       }

     }
     //Random delay every 5000 samples helps avoid problems with interference by staggering the samples to cancel aliasing.
     delay(random(1,50));
     Serial.print("|");

   }
   Serial.print("\n");
   Serial.print("Value: ");
   Serial.print(difference/500000);
   Serial.print("\nMeasurement Complete. Press Enter to begin another test.\n");

   while(!Serial.available())
   {
     blah = 20;
   }
   Serial.read();

}

```

http://pastebin.com/2W5y81AB
> 0 votes

---
Tags: sensors, system-design
---


# Question
Title: Can I connect and control 12 Arduino's over USB/serial to my laptop?
I have 12 arduinos, each of them controlling some simple hardware peripherals. I want to interact with all of them over 1 USB connection to my laptop, where I have a python program communicating over serial.

The following seems like it could work: https://www.amazon.ca/Satechi-Power-Adapter-Control-Switches/dp/B0051PGX2I

Are there any electrical/other considerations to take into account for why this would/wouldn't work?

# Answer
From a technical standpoint, USB can host up to 127 devices, so 12 Arduino boards is certainly not pushing the limit. Having 12 serial ports shouldn't be an issue in either Linux or Windows.

From a practical standpoint, you will have to find a powered USB hub which can support that many devices, or plug multiple hubs together. I'll leave that up to you as shopping recommendations are off topic.

In terms of the hub you use, you need to make sure you don't exceed its maximum current rating. The Arduino boards draw typically around 60-100mA alone. 12 of those and you will need at least 1.2A rating. The hub you mentioned says that it cannot exceed 2A. Depending on what other circuitry you attach to your Arduino boards you may need an external power supply for the boards.
> 3 votes

---
Tags: power
---


title: Library for DIY Keyboard

text:
# Question
Title: Library for DIY Keyboard
I'm planning on making my own Bluetooth mechanical keyboard using the Adafruit Feather 32u4 Bluetooth LE. Something that I haven't really figured out is the programming side of things. I was wondering if there is an easy to use library for this.

I know of the KeyPad library but I'm not sure how to handle modifier keys like Shift and CTRL with it. Any idea can help!

Edit: Like said before the project I'm working on is a Bluetooth mechanical keyboard. So this means there will be 85 (at least for my design) switches in a matrix.

In an ideal world the library I'm looking for can do the following: I specify the keys and their position in a matrix and what the modifier keys are. It can generate the appropriate ASCII character when the matching key(s) are pressed and return it or something, so that I can send it over Bluetooth in another piece of code.

In a less ideal world I use the KeyPad library but I don't really know how to take care of modifier keys like shift when doing that.

Have a nice day!

# Answer
> 1 votes
For shift (making an `a` into an `A`), simply program in some ands. Pseudo-code:

```
if shift AND a:
    return A
elif shift AND b:
    return B

```

and so on and so forth.

# Answer
> 0 votes
https://github.com/tmk/tmk\_keyboard is what you want.

Search in Adafruit's site for how to incorporate Bluefruit.

---
Tags: programming, bluetooth, adafruit, keyboard
---


# Question
Title: How do I communicate with a sensor via an Arduino's RX/TX ports?
I have a sensor that communicates via serial communication. CTi Sensors TILT-05. It transmits an ASCII string with data separated by commas. I want to be able to read the incoming ASCII data in the Arduino IDE's Serial Monitor in real time (the device is an accelerometer).

I am struggling to convey this in the code. Currently, I have the sensor's RX connected to an Arduino Uno's TX port (digital 1) and sensor TX-\> Arduino RX (digital 0). The sensor is powered and grounded via the Arduino.

I have searched for serial communication methods but can't find any that seem to work. How can I receive and interpret the incoming data from the sensor?

# Answer
You don't mention the sensor brand or a datasheet so this will be a very general answer to the problem.

Firstly, how you have the sensor connected now should just spool info into the Serial monitor of the Arduino IDE without any code on the Arduino.

What are the data speed and the exact way the Serial comes out from the sensor?

If you want to interpret the data as it is coming through you should use Software Serial as you can't relay info to the PC with an Arduino's RX TX lines connected to something else.

What you can do is below(***Untested***):

```
#include <SoftwareSerial.h>

SoftwareSerial mySer(3, 4); //RX TX

//these are char areay because its from Serial
char accel[3] = {'0'};
uint8_t place = 0;

// array to print in sync with the accelerometer values array
const char* SerialText[3] = {
   "\nX Axis: ",
   "\nY Axis: ",
   "\nZ Axis: ",
};

char inData = '0';
char separator = ','; // separator you described

void setup(){
//set to the normal baud, mines for the example
     Serial.begin(9600);

     mySer.begin(9600);

}//~ end setup

void loop(){

    if(mySer.available()){

     inData = mySer.read(); // get the value at the instance of the serial data being there

        if(inData != separator){
          accel[place] = inData;
          Serial.print(SerialText[place]); // print the current values identifier
          Serial.print(accel[place]); // print value
          place++; // increment for the next time
     }
   }

if(place >= 3) place = 0;
}//~ end loop

```

The above gives this output at the moment, with an input of `$CSACC,-0156.4,-0226.3,+0981.2*49`

```
X Axis: $
Y Axis: C
Z Axis: S
X Axis: A
Y Axis: C
Z Axis: C
X Axis:
Y Axis: -
Z Axis:
X Axis: 0
Y Axis: 1
Z Axis: 5
X Axis: 6
Y Axis: .
Z Axis: 4
X Axis:
Y Axis: -
Z Axis:
X Axis: 0
Y Axis: 2
Z Axis: 2
X Axis: 6
Y Axis: .
Z Axis: 3
X Axis: +
Y Axis: 0
Z Axis: 9
X Axis: 8
Y Axis: 1
Z Axis: .
X Axis: 2
Y Axis: *
Z Axis: 4
X Axis: 9
Y Axis:
Z Axis:
X Axis:

```

The code doesn't filter this the way it should but is a stepping stone. I will update it to do it properly when I have a chance.
> 1 votes

# Answer
With RSM's help I've managed to get the sensor reading into the serial monitor semi-reliably. I have yet to solder the headers onto the sensor yet and am just doing prototyping (basically just me pushing a wire against the sensor output hole) which is unreliable. I believe once I get some headers soldered on the output will be much more reliable. For those searching, this code worked for me.

Digital pins 3/4 function as your RX/TX pins respectively. Connect the TX of your sensor to the RX (3) of the Arduino and likewise for the TX. I used a baud rate of 115200 but you can change it to whatever works in the code. This is simply a simplification of RSM's code in his previous answer and all credit/kudos goes to him.

```
#include <SoftwareSerial.h>

SoftwareSerial mySer(3, 4);

char inData = '0';

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

void loop(){
    if(mySer.available()){
     inData = mySer.read();
     Serial.print(inData);
  }
}

```
> 0 votes

---
Tags: serial, sensors, communication, accelerometer
---


# Question
Title: On Arduino Due webserver, there is a 5 second delay on Windows, only when connected via native port
My Due webserver was working perfectly fine for months when connected to Linux via the native port.

But when connected to Windows 10 via the native port, if the Arduino webserver is idle for about 5 minutes (when no client calls a webpage), then there is a strange 5-10 second delay before the webpage is able to load. This delay doesn't happen when connected to the webserver via the programming port.

It almost seems like maybe Windows is putting the port to sleep when it notices an idle delay, and then it has to wait for the port to wake up before it can call the webpage.

On the Windows "Power Settings" I set the computer to never go to sleep, and also in the Power "Advanced Settings" I disabled the USB "selective suspend".

Do you have any ideas why there would be this strange delay only on Windows and only when connected via the native port?

---

**ADDITIONS:** I made a simplified example that reproduces the problem on my machine. I wonder if anyone can see any problems with this code.

First, the python code. Note that if the python script is never run, there are no delays on the Arduino webserver, and everything works as expected.

```
import serial, sys

SERIALPORT = "COM5" # Change this to your serial port!

# Set up serial port
try:
  ser = serial.Serial(SERIALPORT, 115200, timeout=0)
except serial.SerialException:
  sys.exit()

ser.write("Hello World")
print("Hello World")

ser.close()

```

And below is the simplified Arduino code. It's just a simple webserver that serves a page that has a "reload" button that reloads the page. You can hit "reload" as many times as you want, and the program never freezes. But if you run the python code above and then try to reload the page, there is a long delay (anywhere between 10-60 seconds by my current estimate).

If you comment out all of the "SerialUSB.print" lines that are anywhere in the loop (in this simplified case, there's only 1 line at: "SerialUSB.println (data);" in the processData function), then the webpage never freezes, even if you run the python code frequently.

In my real-world example, my python code was running once a minute, causing random freezes. If I stopped the python code from running, then there were no more freezes on the webpage. I ended up commenting out all of my SerialUSB.print statements that were in the loop, and that way I could have the python code running on schedule, and my program had full functionality (except for the loss of SerialUSB.print).

```
#include <Ethernet.h>

byte mac[] = {
  0x04, 0xBA, 0xB0, 0xCC, 0xDF, 0x04
};
EthernetServer server(80);
EthernetClient client;

const byte MAX_INPUT = 25; //for processIncomingByte

void setup ()
{
  SerialUSB.begin (115200);
  Ethernet.begin(mac);
  SerialUSB.print("server is at ");
  SerialUSB.println(Ethernet.localIP());
}  // end of setup

bool processIncomingByte (const byte inByte)
{
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;
  switch (inByte)
  {
    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte
      if (input_pos == 0)
        return true;   // got blank line
      // terminator reached! process input_line here ...
      processData (input_line);
      // reset buffer for next time
      input_pos = 0;
      break;
    case '\r':   // discard carriage return
      break;
    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1)) input_line [input_pos++] = inByte;
      break;
  }  // end of switch
  return false;    // don't have a blank line yet
} // end of processIncomingByteWeb

void processData (const char * data)
{ //Note: since there are no GET requests in this simple example, I removed the parts for processing GET.
  SerialUSB.println (data);
  if (strlen (data) < 4)
    return;
}  // end of processDataWeb

void loop ()
{
  client = server.available();
  if (client) {
    boolean done = false;
    while (client.connected() && !done)
    {
      while (client.available () > 0 && !done)
        done = processIncomingByte (client.read ());
    }  // end of while client connected

      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println();
      client.print("<html><body>");
      client.print("<a href=\"/\">Reload</a></body></html>");
      delay(10); client.stop();
  }
}  // end of loop

```

This is not technically a problem for me anymore, except for having had to comment out all my "SerialUSB.print" statements. But I am interested in learning what is causing this strange behavior.

Note: the "processIncomingByte" and "processData" functions are mainly from Mr. Gammon's writings and tutorials, and they are working flawlessly for me in 2 other Arduino webservers I have running. I wanted to note this because if I had written the functions myself, then obviously they would require much more scrutiny.

# Answer
> 1 votes
This is speculation as it may be nearly impossible for any given person to simulate your network (for example, not only the version of Windows you are running but all the drivers installed and hardware specific to your Ethernet interface ... to only mention a few variables).

Consider using a network monitor to capture all communications set out by the Windows computer. Consider the Windows computer occasionally failing your network. Consider the delay you experience may be the time it takes for Windows to recover from what it thinks is a bad network.

The observation is that Windows sends out many autonomous messages over a new network in a "discovery" mode. The suspicion is that the lack of response to some or all of these messages will result in Windows failing a network.

Windows does have ways of reporting the status of networks that vary with the version of Windows. But these methods (menus) can be frustrating to use as they don't appear to update often enough to reflect the true behavior of traffic coming out of the Windows computer.

Regardless, test if the state of the network is always good. Also, test if connecting equipment Windows might expect on a functioning network (for example, a router with a DHCP server) improves the response time. This, as an effort / test to determine if Windows is more responsive while connected to a healthy / active network.

---
Tags: serial, arduino-due, web-server
---


# Question
Title: Arduino Robot. a function-definition is not allowed here before '{' token
The code is very messy. We have an L293D circuit which has two enable pins always on. We also have an LDR light sensor with two light resistors, one on the left and one on the right.

We are trying to make a line following robot

We are ambitious high school students.

```
// Use this code to test your motor with the Arduino board:

// if you need PWM, just use the PWM outputs on the Arduino
// and instead of digitalWrite, you should use the digitalWrite command

// --------------------------------------------------------------------------- Setup
void setup() {
{Serial.begin(9600);

// --------------------------------------------------------------------------- Motors
int motor_left[] = {2, 7};
int motor_right[] = {10, 15};
int LDR = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDRValue = 0;      //that’s a variable to store LDR values
int light_sensitivity = 500;    //This is the approx value of light surrounding your LDR
int LDR2 = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDR2Value = 0;      //that’s a variable to store LDR values
int light_sensitivity2 = 500;    //This is the approx value of light surrounding your LDR
int i;
for(i = 0; i < 2; i++){
pinMode(motor_left[i], OUTPUT);
pinMode(motor_right[i], OUTPUT);
LDRValue = analogRead(LDR);
    Serial.println(LDRValue);

    if (LDRValue < light_sensitivity);
    Serial.println("wat");

}
// --------------------------------------------------------------------------- Loop

// --------------------------------------------------------------------------- Drive

void motor_stop(){
digitalWrite(motor_left[0], LOW);
digitalWrite(motor_left[1], LOW);

digitalWrite(motor_right[0], LOW);
digitalWrite(motor_right[1], LOW);
delay(25);
}

void drive_forward(){
digitalWrite(motor_left[0], HIGH);
digitalWrite(motor_left[1], LOW);

digitalWrite(motor_right[0], HIGH);
digitalWrite(motor_right[1], LOW);
}

void drive_backward(){
digitalWrite(motor_left[0], LOW);
digitalWrite(motor_left[1], HIGH);

digitalWrite(motor_right[0], LOW);
digitalWrite(motor_right[1], HIGH);
}

void turn_left(){
digitalWrite(motor_left[0], LOW);
digitalWrite(motor_left[1], HIGH);

digitalWrite(motor_right[0], HIGH);
digitalWrite(motor_right[1], LOW);
}

void turn_right(){
digitalWrite(motor_left[0], HIGH);
digitalWrite(motor_left[1], LOW);

digitalWrite(motor_right[0], LOW);
digitalWrite(motor_right[1], HIGH);
}
void loop() {
drive_forward();
delay(1000);
motor_stop();
Serial.println("1");

drive_backward();
delay(1000);
motor_stop();
Serial.println("2");

turn_left();
delay(1000);
motor_stop();
Serial.println("3");

turn_right();
delay(1000);
motor_stop();
Serial.println("4");

motor_stop();
delay(1000);
motor_stop();
Serial.println("5");
}

```

# Answer
> 2 votes
You need to look more closely at your braces. Use the auto-format tool (Ctrl+T) to help you. For example:

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

// --------------------------------------------------------------------------- Motors
int motor_left[] = {2, 7};
int motor_right[] = {10, 15};
int LDR = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDRValue = 0;      //that’s a variable to store LDR values
int light_sensitivity = 500;    //This is the approx value of light surrounding your LDR
int LDR2 = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDR2Value = 0;      //that’s a variable to store LDR values
int light_sensitivity2 = 500;    //This is the approx value of light surrounding your LDR
int i;
for(i = 0; i < 2; i++){
pinMode(motor_left[i], OUTPUT);
pinMode(motor_right[i], OUTPUT);
LDRValue = analogRead(LDR);
    Serial.println(LDRValue);

    if (LDRValue < light_sensitivity);
    Serial.println("wat");

}   // <------------------------------------ HERE

// --------------------------------------------------------------------------- Loop

// --------------------------------------------------------------------------- Drive

void motor_stop(){

```

Where I marked "HERE" you are closing the `for` loop but you should also be closing `setup`.

You also have two opening braces here:

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

```

Proper indentation is **very helpful** for sorting out these sorts of issues.

---
Tags: programming
---


# Question
Title: Saving library example sketch getting error "you cannot save a sketch into a folder inside itself.."
I'm writing a library, and that library .cpp/.h code is in devel/arduino/libraries/LightBrightLib/. I have test code that calls that library, and an example program using the library. Right now they're in /devel/arduino/lightbright/LightBrightMain/ and /devel/arduino/lightbright/LightBrightLibTest/.

I see most libraries have an examples directory inside the library, so I tried moving mine to /devel/arduino/libraries/LightBrightLib/examples/LightBrightMain/ and /devel/arduino/libraries/LightBrightLib/examples/LightBrightLibTest/

When I do that, and try to save my LightBrightMain.ino file into /devel/arduino/libraries/LightBrightLib/examples/LightBrightMain/, it says "You cannot save a sketch into a folder inside itself. This would go on forever.". And of course it won't let me select the examples directory or any other directory above it.

How do other library makers do this? Maybe they don't use the IDE, or they copy it in outside the IDE, or use symlinks? What does the IDE think it's doing and why is it fighting putting the file where it already is?

NOTE: This is not a file permission problem as I own all files

# Answer
> 0 votes
What I normally do is make the examples in their own folders (ie. inside the sketchbook folder). Then when they are tested I just use the file system to move the folders into the "examples" folder under the library.

> When I do that, and try to save my LightBrightMain.ino file into /devel/arduino/libraries/LightBrightLib/examples/LightBrightMain/,

The IDE makes the folder, so you would (if this works at all) save `LightBrightMain` into the `examples` folder. Don't make a folder of the same name as the sketch. The IDE does that.

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


title: Changing the tick time in FreeRTOS

text:
# Question
Title: Changing the tick time in FreeRTOS
I am trying to use FreeRTOS's vTaskDelay() function in order to periodically execute tasks. The latest version of FreeRTOS came with the "tick" time set to 15 ms. Therefore, the smallest resolution I can delay for is 15 ms. I would like to lower this resolution to at least 1 ms. Is it possible to configure FreeRTOS in this way? I found this answer online : http://www.freertos.org/FreeRTOS\_Support\_Forum\_Archive/November\_2012/freertos\_Problem\_changing\_Tick\_time\_from\_1ms\_to\_10ms\_6231539.html.

But for me, the configTICK\_RATE\_HZ is not defined and it seems to be using a watchdog timer to enforce the 15 ms resolution. I think the forums are referring to an earlier version.

# Answer
See the configTICK\_RATE\_HZ configuration option. Also note it is better to specify times in milliseconds, rather than ticks, so you can change the tick frequency without effecting the timing (other than the resolution of the time).

The `pdMS_TO_TICKS()` macro can be used for that purpose, for example to create a delay of 100ms.

```
const TickType_t xBlockTime = pdMS_TO_TICKS( 100 );
vTaskDelay( xBlockTime );

```
> 2 votes

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


title: Clearing EEPROM

text:
# Question
Title: Clearing EEPROM
I'm trying to clear my EEPROM and am using this code:

```
#include <EEPROM.h>
void setup()
{
// write a 0 to all 4096 bytes of the EEPROM
for (int i = 0; i < 4096; i++)
EEPROM.write(i, 0);

delay(9999999);
}

void loop()
{
}

```

I don't see a problem with it but it is ineffective. Am I missing something?

# Answer
The tutorial here is very clear about how to clear the contents of the Atmel's EEPROM. I only see 2 major difference. The tutorial finds the size of the EEPROM through a function call. Probably much safer. And there is no call to a delay() function.

The tutorial does include lighting up an LED when finished. And @Edgar Bonet is correct that erasing an EEPROM (altering each floating gate with in the chip) does take time. And you have no way to known when the EEPROM clearing is finished in your code.

It is possible you are forcing your code to stop before it is finished. In which case it would appear the EEPROM is not completely cleared.
> 2 votes

# Answer
Thank you all for helping me out. This is what I ended up using (ESP8266 1.0 12E with Arduino IDE):

```
#include <EEPROM.h>
#include <ESP8266WiFi.h>

void setup()
{
  Serial.begin(115200);
  EEPROM.begin(512);
  delay(5000);
  Serial.println("clearing EEPROM...");
  // write a 0 to first 1000 bytes of the EEPROM
  for (int i = 0; i < 1000; ++i) {
    EEPROM.write(i, -1);
 }
  EEPROM.commit();
  delay(5000);
  Serial.println("Reading EEPROM ssid");
  String esid;
  for (int i = 0; i < 64; ++i)
  {
    esid += char(EEPROM.read(i));
  }
  Serial.print("SSID: ");
  Serial.println(esid);
  Serial.println("Reading EEPROM pass");
  String epass = "";
  for (int i = 64; i < 128; ++i)
  {
    epass += char(EEPROM.read(i));
  }
  Serial.print("PASS: ");
  Serial.println(epass);
}

void loop()
{
}

```

It's probably longer than it has to be but I pulled stuff from other sketches I've worked on and prioritize function over form. This writes a "-1" to the first 1000 bytes and then prints the first 128 bytes. Since I am only concerned about the first 50 bytes or so this was sufficient for my needs.
> 0 votes

---
Tags: c++, eeprom
---


# Question
Title: How can I use wifi to wirelessly communicate (and wirelessly code if possible) between multiple arduinos?
I am using arduino as the base for an accelerometer project - the end goal is to have multiple arduinos with accelerometer chips that can wirelessly start and stop collecting data and wirelessly send this data back to the "base" arduino (which will be connected to a computer). Currently we have only two arduinos communicating to test a lot of this, and currently are using a bluetooth node to wirelessly code the accelerometer arduino and Rf nodes to wirelessly send the data back to the arduino connected to a computer which then prints the data it is collecting. How could we replace this with a wifi network?

# Answer
Sending data to a computer using WiFi is simple enough and there are plenty of examples. The simplest way is to set up a web server on the computer and use HTTP POST to send the data. There are "lighter" ways but entail more coding.

You won't do OTA updates on a normal Arduino. Yes, you could use a Yún, but they aren't always the best choice - the Linux side of things does make it a very "heavyweight\* board.

You may be better off using an ESP8266 based system (not wired to an Arduino, but standalone) and programming it direct. Maybe a NodeMCU or something similar. The Arduino core for ESP8266 supports OTA programming direct from the Arduino IDE.
> 1 votes

---
Tags: wifi, communication, wireless
---


title: SoftwareSerial error:

text:
# Question
Title: SoftwareSerial error:
Please help me with this library "Softwareserial". The basic sketch does not work. Please look the errors:

```
    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:128:2: error: #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors

 #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors

  ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'bool SoftwareSerial::listen()':

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:184:23: error: 'SREG' was not declared in this scope

     uint8_t oldSREG = SREG;

                       ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:185:9: error: 'cli' was not declared in this scope

     cli();

         ^

In file included from C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\cores\arduino/delay.h:27:0,

                 from C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\cores\arduino/Arduino.h:76,

                 from C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:43:

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'void SoftwareSerial::setTX(uint8_t)':

C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\variants\arduino_zero/variant.h:62:82: error: invalid conversion from 'PortGroup*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( &(PORT->Group[g_APinDescription[P].ulPort]) )

                                                                                ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:360:18: note: in expansion of macro 'digitalPinToPort'

   uint8_t port = digitalPinToPort(tx);

                  ^

C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\variants\arduino_zero/variant.h:65:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->OUT.reg) )

                                            ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:361:27: note: in expansion of macro 'portOutputRegister'

   _transmitPortRegister = portOutputRegister(port);

                           ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'void SoftwareSerial::setRX(uint8_t)':

C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\variants\arduino_zero/variant.h:62:82: error: invalid conversion from 'PortGroup*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( &(PORT->Group[g_APinDescription[P].ulPort]) )

                                                                                ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:371:18: note: in expansion of macro 'digitalPinToPort'

   uint8_t port = digitalPinToPort(rx);

                  ^

C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\variants\arduino_zero/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portInputRegister(port)    ( &(port->IN.reg) )

                                            ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:372:26: note: in expansion of macro 'portInputRegister'

   _receivePortRegister = portInputRegister(port);

                          ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'void SoftwareSerial::begin(long int)':

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:383:31: error: 'table' was not declared in this scope

   for (unsigned i=0; i<sizeof(table)/sizeof(table[0]); ++i)

                               ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:399:38: error: 'digitalPinToPCICR' was not declared in this scope

     if (digitalPinToPCICR(_receivePin))

                                      ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:401:78: error: 'digitalPinToPCICRbit' was not declared in this scope

       *digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));

                                                                              ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:401:79: error: '_BV' was not declared in this scope

       *digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));

                                                                               ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:402:37: error: 'digitalPinToPCMSK' was not declared in this scope

       *digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));

                                     ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:402:78: error: 'digitalPinToPCMSKbit' was not declared in this scope

       *digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));

                                                                              ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'void SoftwareSerial::end()':

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:417:36: error: 'digitalPinToPCMSK' was not declared in this scope

   if (digitalPinToPCMSK(_receivePin))

                                    ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:418:77: error: 'digitalPinToPCMSKbit' was not declared in this scope

     *digitalPinToPCMSK(_receivePin) &= ~_BV(digitalPinToPCMSKbit(_receivePin));

                                                                             ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:418:78: error: '_BV' was not declared in this scope

     *digitalPinToPCMSK(_receivePin) &= ~_BV(digitalPinToPCMSKbit(_receivePin));

                                                                              ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'virtual size_t SoftwareSerial::write(uint8_t)':

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:453:21: error: 'SREG' was not declared in this scope

   uint8_t oldSREG = SREG;

                     ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:454:7: error: 'cli' was not declared in this scope

   cli();  // turn off interrupts for a clean txmit

       ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:458:26: error: 'XMIT_START_ADJUSTMENT' was not declared in this scope

   tunedDelay(_tx_delay + XMIT_START_ADJUSTMENT);

                          ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'virtual void SoftwareSerial::flush()':

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:501:21: error: 'SREG' was not declared in this scope

   uint8_t oldSREG = SREG;

                     ^

C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:502:7: error: 'cli' was not declared in this scope

   cli();

       ^
PLEASE HELP ME!

```

# Answer
You're trying to use the AVR SoftwareSerial library with an ARM based board. It won't work. Ever.

There should be no need to use SoftwareSerial - the SAMD chips have multiple UART channels - just use one of those.
> 1 votes

---
Tags: softwareserial
---


# Question
Title: Arduino for Weather and Air Monitoring: Casing and Power Source
I am intended to use Arduino to measure Temperature and Humidity (DTH11) and Gases Grove Sensor (Multichannel). Due to weather conditions in UK, I would to get your advice how to shield all of them in water proof box? Do you believe that using Polystyrene is useful? Any recommended power source?

# Answer
> 2 votes
I'd say, use a IP-54 protection plastic case. The IP is a standard, that tells you, how big particles can(not) come into the case.

About powering, depends, how often can you go and switch batteries. If you can, you can plug the cable in the case - drill the hole through and use watertight silicone plug to ensure, it is water resistant.

In case of batteries - use some LiPo batteries with DC-DC converter to minimum voltage. Maybe you could even add a solar panel or two for addional life extension of batteries.

---
Tags: arduino-uno, sensors, wifi, shields
---


# Question
Title: Communication between two Arduinos over RF module
I want to communicate Arduino A to Arduino B by using RF module. But my RF module (Tx- XLPCF20, Rx- XY-R01A) only consist of 4 pins of data pin where it can send 4 bits of data only. So, I want to develop a new encoding to send data by using 4 bits of data. How should i do for the coding since I don't want to use serial write for coding. Any suggestion? Help me please. If u can give me the coding, I'm beyond thankful.

# Answer
> 1 votes
You have 4 channels of raw HIGH/LOW communication. How you use them is up to you.

The simplest method is to use an asynchronous serial protocol:

* Use Serial: Connect the TX of one Arduino to channel 1 at the TX, and RX channel 1 to RX on the other Arduino
* Use SoftwareSerial: The same as above but you choose the pins
* Use VirtualWire: very similar to SoftwareSerial

For higher speeds, since you have 4 channels, you could use a *synchronous* serial communication protocol. It should be perfectly possible to connect three of the channels to SPI and communicate as if it were talking directly to an SPI device - one channel to SCK, one to MOSI and one to SS. The other end has SCK, MOSI and SS but running in slave mode.

No need to "invent" a 4-bit protocol, it's too much work.

---
Tags: arduino-uno
---


title: Permanent connections with Arduino Due

text:
# Question
Title: Permanent connections with Arduino Due
The Arduino Uno (for some models) has the ability to dislodge its IC chip. You can mount this on a piece of perfboard and, in essence, have a permanent connection. I will need the beefier Arduino Due, but I do not know how to make permanent connections with this device. Is there any way to form some kind of permanent connection with this board?

# Answer
> 1 votes
What it sounds like you want is an Arduino Due footprint prototyping shield.

Arduino make one, although it is out of stock, but it gives you an idea of what you are looking for. There are plenty of other designs out there for purchase of varying degrees of complexity.

You solder the pins in place and mount it on top of your Due just like any shield, and solder your wires and components in where you want them.

An alternative option, of course, is to step away from Arduino and investigate some of the many other chips from other manufacturers out there that are considerably more powerful than the 8-bit ATMegas used on the low-end Arduinos, and yet are still available in a DIP footprint - chips like the PIC32MX1xx/2xx series from Microchip - 28 pin DIP (just like the 328P) yet 50MHz, 32-bit power. Yes, it will be a bit of a learning curve, but there are helpful options out there that can assist you, like the chipKIT system including the handy DP32 board from Digilent.

# Answer
> 0 votes
You can disolder the female pin headers from pcb and make permanent connections on the remaining holes.

# Answer
> 0 votes
I think the best thing you can do with this, is that you use temporary wires to connect and test the application and later, when you'll come to part, where you should "make-a-solid", you just solder these wires to the bottom, where pin headers are. I think this is the simplest way to do it.

If you want to do it a bit better, desolder female header pins and solder cables to those holes. It's more electronics-approved that way.

Or the simplest (but not the brighest): Jumper wires can be glued into female header pins, but I strongly unrecommend this option, as same as making a shield for this.

There's another(and most elegant too!) option of making a PCB version of arduino: Add the AtMega, few passive components and proper pads, to solder wires on.

---
Tags: arduino-due
---


# Question
Title: Posting to EEPROM via HTML - ESP8266 Arduino IDE
For those of you familiar with my somewhat steep EEPROM learning curve...thank you for continuing to share your knowledge. I see how it's supposed to work and it's falling into place.

I've run into a new problem and I've spent two nights (~15hrs of Googling/trial and error...mostly error) trying to understand where I'm going wrong.

Below is a chunk of code that take user inputs from a webpage and saves it to EEPROM. It works as intended when only SSID and PASS fields are provided on the form. I added an "owner" field to add my name to the EEPROM (because why not?) and now the PASS field is ignored and the OWNER information is saved to the PASS and OWNER EEPROM locations.

I think it has something to do with the string.indexof("&") and repeated string.lastindexof("=") but I'm still wrapping my head around what these actually do. If I understand it correctly, the second string.lastindexof("=") is actually overwriting the PASS which was saved milliseconds earlier. If this is correct, how do I prevent this? If I'm wrong, why?

```
  s += "<form method='get' action='a'><label>SSID: </label><input name='ssid' length=32><br><label>PASS: </label><input name='pass' length=64><br><label>OWNER: </label><input name='owner' length=32><br><br><input type='submit'></form>";
  s += "</html>\r\n\r\n\r\n";
  Serial.println("Sending 200");
}
else if ( req.startsWith("/a?ssid=") ) {
  Serial.println("clearing eeprom");
  for (int i = 0; i < 128; ++i) {
    EEPROM.write(i, 0);
  }
  String qsid;
  qsid = req.substring(8, req.indexOf('&'));
  Serial.println(qsid);
  Serial.println("");
  String qpass;
  qpass = req.substring(req.lastIndexOf('=') + 1);
  Serial.println(qpass);
  Serial.println("");
  String owner;
  owner = req.substring(req.lastIndexOf('=') + 1);
  Serial.println(owner);
  Serial.println("");

  Serial.println("writing eeprom ssid:");
  for (int i = 0; i < qsid.length(); ++i)
  {
    EEPROM.write(i, qsid[i]);
    Serial.print("Wrote: ");
    Serial.println(qsid[i]);
  }
  Serial.println("writing eeprom pass:");
  for (int i = 0; i < qpass.length(); ++i)
  {
    EEPROM.write(32 + i, qpass[i]);
    Serial.print("Wrote: ");
    Serial.println(qpass[i]);
  }
  Serial.println("writing eeprom owner:");
  for (int i = 0; i < owner.length(); ++i)
  {
    EEPROM.write(96 + i, owner[i]);
    Serial.print("Wrote: ");
    Serial.println(owner[i]);
  }
  EEPROM.commit();

```

To summarize, my questions are:
-what is causing the code to skip over my PASS field and save a duplicate of OWNER into both PASS and OWNER?
-is one \r\n pair required for every field on the html form? If I used 100 fields would I need 100 * \r\n pairs after tag?

If you're interested in seeing the whole shebang, chriscook8 has graciously posted the Access Point sketch for the ESP8266 here (~250 lines). There is also a very helpful discussion about this sketch here.

---

## Edit: 3 July 2016

I've amended the code:

```
s += "<form method='get' action='a'><label>SSID: </label><input name='ssid' length=32><br><label>PASS: </label><input name='pass' length=64><br><label>OWNER: </label><input name='owner' length=32><br><br><input type='submit'></form>";
s += "</html>\r\n\r\n\r\n";
Serial.println("Sending 200");
}
    else if ( req.startsWith("/a?ssid=") ) {
      Serial.println("clearing eeprom");
      for (int i = 0; i < 128; ++i) {
        EEPROM.write(i, 0);
      }
      String qsid = server.arg("ssid");
      String qpass = server.arg("pass");
      String owner = server.arg("owner");
    }
    Serial.println("writing eeprom ssid:");
    for (int i = 0; i < qsid.length(); ++i)
    {
      EEPROM.write(i, qsid[i]);
      Serial.print("Wrote: ");
      Serial.println(qsid[i]);
    }
    Serial.println("writing eeprom pass:");
    for (int i = 0; i < qpass.length(); ++i)
    {
      EEPROM.write(32 + i, qpass[i]);
      Serial.print("Wrote: ");
      Serial.println(qpass[i]);
    }
    Serial.println("writing eeprom owner:");
    for (int i = 0; i < owner.length(); ++i)
    {
      EEPROM.write(96 + i, owner[i]);
      Serial.print("Wrote: ");
      Serial.println(owner[i]);
    }
    EEPROM.commit();
    s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from ESP8266 ";
    s += "Found ";
    s += req;
    s += "<p> saved to eeprom... reset to boot into new wifi</html>\r\n\r\n";
  }
  else
  {
    s = "HTTP/1.1 404 Not Found\r\n\r\n";
    Serial.println("Sending 404");
  }
}

```

I also made the following replacement per your recommendations:

```
//WiFiServer server(80);
ESP8266WebServer server ( 80 );

```

...and receive an error on this line:

```
WiFiClient client = server.available();

```

'class ESP8266WebServer' has no member named 'available'

I'm sure that there is a simple replacement for this. Any idea what it might be?

Otherwise, I think I see where you're going with this and it seems much cleaner than I anticipated.

Thank you!

# Answer
A code snippet for you - will expand later (just got tied up)

```
ESP8266WebServer server ( 80 );
...

else if ( req.startsWith("/a?ssid=") ) {
  Serial.println("clearing eeprom");
  for (int i = 0; i < 128; ++i) {
    EEPROM.write(i, 0);
  }
  String qsid = server.arg("ssid");
  String qpass = server.arg("pass");;
  String owner = server.arg("owner");

  Serial.println("writing eeprom ssid:");
  ... rest of your code

```
> 1 votes

---
Tags: c++, esp8266, eeprom
---


title: Modbus RTU over TCPip

text:
# Question
Title: Modbus RTU over TCPip
I have developed my arduino code using below library. I tested code working fine over modbus RTU slave. Now i am planning to use RS485 to wifi instead of wire connection. In order to get data over web apllication i need to add another layer of modbus TCP-IP. can some one suggest me is it possible to without changing any hardware add library function which can acts like MODBUS RtU over TCP-IP protocol.

if any library avilable please share it I am using WIFI device like below. rs485 to wifi

MODBUS RTU

# Answer
Modbus TCP simply put is a Modbus packet wrapped in a TCP packet.

There is no 'additional layer of Modbus' added on top. If we look at the osi model pictured below you can see there is only one Modbus application layer (i.e modbus slave/server)

Essentially if the wifi-\>RS485 gateway strips the payload from the TCP packets and simply spits it out the serial side then no modifications are necessary (apart from the obvious RS485 transceiver you will need to interface the arduino with the gateway).

What you will need to make sure is that the gateway will only send packets directed to port 502 to the arduino (502 is the Modbus TCP port) as it is possible other IP traffic could cause some drama for the modbus slave.

Additionally, you will have to ensure that you set the slave ID of the arduino to be what is specified by the master. Are you also building the Modbus TCP client? If not it is very possible that the required slave ID is 255 which is not supported by the modbus library you have linked.

Modbus (serial) slave IDs can only be between 1 and 247 for traditional reasons when Modbus was first standardised as it was only envisioned to be on serial, however when Modbus TCP was introduced an additional addressing layer (TCP / IP) meant that the unit ID (slave ID when using Modbus TCP) could be anything from 0 - 255. It is common for some vendors (at least in industrial automation) to use a unit ID of 255 for standard Modbus transactions scanning IO and diagnostic or configuration transactions to be send to other unit IDs (essentially making the TCP server a modbus router, forwarding packets to one of the multiple Modbus servers running on that single slave device)
> 1 votes

---
Tags: arduino-uno, modbus, tcpip
---


title: Power arduino from 5v rail of pc molex

text:
# Question
Title: Power arduino from 5v rail of pc molex
I'm building a small device using arduino that should be connected to my pc via a usb header to exchange data with the PC.

What I'd like to achieve is that arduino turns on when the pc is on, whereas it shuts down when the pc is turned off. If I rely on the usb port to provide power to the arduino that might not happen, since some motherboards still provide power to the usb connections even when the pc is off.

Therefore I'd like to power the arduino using the 5v rail directly from a Molex. I know that theoretically I can connect that rail straight to the 5v pin, but what about power spikes? How can I be sure that the 5v input voltage is properly filtered and stabilized? Would it be better to use a LM317 and transform the 12v rail into 7.5v to feed arduino from the vin?

# Answer
> 3 votes
The 5v of an ATX power supply will be perfectly adequate for powering an Arduino.

It will already be very heavily filtered and stabilised.

---
Tags: power, voltage-level, voltage-protection
---


title: Passing pointers between setup and loop

text:
# Question
Title: Passing pointers between setup and loop
I'm new to the Arduino world. The last time i was programming microprocessors, was back with the Z80 in assembly language.

I am also teaching myself C++ and seems to be going quite well.

I have decided to write my own 'library' for driving 7 segment LED's. The reason for writing my own, rather then using an existing one is to aid with the learning process. I'm quite pleased to say it works ( it may not be the most efficient code)

The books I have on C++ are great, but i do find sometimes the explanation of concepts seem to get lost.

what I would like to know, how do you go about initialising an object class in setup() and using it in loop()? I have this sneaky suspicion that it involves creating the object on the heap, and passing a pointer to the object over somehow.

I could just initialise it once in loop(), and make my own continuous loop afterwards, but there are other things done between the and of a loop() and the beginning of the next loop() (things like timer interrupts).

I will post the code im using, but not the library unless asked to, as it is quite a few lines.

```
# include "Leddisplay.h"
void setup() {

    byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };

    Leddisplay *pRightDigit = new Leddisplay(Digit);

}

void loop() {

    pRightDigit->setDigit(5);
    pRightDigit->displayDigit();

}

```

^^ Obviously this does not compile ^^

```
# include "Leddisplay.h"
void setup() {

}

void loop() {

    byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
    Leddisplay *pRightDigit = new Leddisplay(Digit);

    pRightDigit->setDigit(5);
    pRightDigit->displayDigit();

    for (;;);   // or do.. while within which has other code to repeat
                // but wont allow anything to be executed between loop() iterations

}

```

^^ This does, and runs fine, but may not achieve what I want ^^

I'm not sure if I have used the right wording, or even asked the right question. Thank you for any help in advance. Dave

# Answer
What you have to understand is the concept of *scope*.

Everything (well, almost everything) in C and C++ is enclosed in `{` and `}`. Those define a *scope*, and everything defined within that scope is available to any other scopes defined within that scope.

You can also assume that the whole sketch is surrounded by `{` and `}`. This scope is called the *global scope*. Anything defined within it is available anywhere in your sketch.

So by defining the object in the *global scope* it is available everywhere:

```
# include "Leddisplay.h"

Leddisplay *pRightDigit;

void setup() {
    byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
    pRightDigit = new Leddisplay(Digit);
}

void loop() {
    pRightDigit->setDigit(5);
    pRightDigit->displayDigit();
}

```

However the use of `new` etc is discouraged in low-memory systems. Better is to *statically define* the object:

```
# include "Leddisplay.h"

const byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
Leddisplay pRightDigit(Digit);

void setup() {
}

void loop() {
    pRightDigit.setDigit(5);
    pRightDigit.displayDigit();
}

```

Note that, when statically defined like this, things in the constructor aren't guaranteed to be run at the right time. They should be moved into a `.begin()` function that you then call from `setup()`:

```
# include "Leddisplay.h"

const byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
Leddisplay rightDigit(Digit);

void setup() {
    rightDigit.begin();
}

void loop() {
    rightDigit.setDigit(5);
    rightDigit.displayDigit();
}

```
> 3 votes

# Answer
> ... how do you go about initialising an object class in setup() and using it in loop()?

You declare it in a global context so that it's accessible by both.

But that's not *quite* what you want here:

```
#include "Leddisplay.h"

byte Digit[] = {...};
Leddisplay RightDigit(Digit);

void setup() {
}

void loop() {
    RightDigit.setDigit(5);
    RightDigit.displayDigit();
}

```
> 1 votes

# Answer
Sorry, I cannot comment as I do not yet have enough rep.

This is in response to @Dave Dunnes comment

> The Library I have written can (and does) drive multiple led displays. I also understand then when programming for ucontrollers, you use as little ram as possible. Also, you usually know at compile time, what hardware is available, However, say you only know how many displays there are at runtime. This is why I have created the LED display instance on the heap (I assume on the Arduino, thats RAM, not flash) Let us say at runtime the program would ask you how many displays are connected via the serial terminal, then they will be activated, and a recompile is not an option. Regards, Dave – Dave Dunne 9 hours ago

If you do not know the exact number of segments (or any element really) at build time then you could implement a linked list and dynamically allocate new Leddisplay objects at run time or build the list in to your class. Alternatively you can try try using std::list with the AVR port of the STL (I have not personally tried this).
> 0 votes

---
Tags: arduino-mega, programming, c++
---


# Question
Title: Arduino Uno - combined LCD and keypad interfacing problem
I have a problem with the Arduino Uno.

I need to use a 4x3 keypad and 16x2 LCD together with an Arduino Uno. As 4x3 keypad requires 7 pins, I have defined pins 2, 3, 4, 5, 6, 7 and 8 to it. A 16x2 LCD requires 6 pins but only 5 pins remain (9, 10, 11, 12 and 13). Pins 0 and 1 are used for serial.

Please suggest a probable solution.

# Answer
> 1 votes
You could use a shift register to read the switches as outlined by the excellent tutorial Parallel to Serial Shifting-In with a CD4021BE. Quoting the summary:

> Sometimes you'll end up needing more digital input than the 13 pins on your Arduino board can readily handle. Using a parallel to serial shift register allows you collect information from 8 or more switches while only using 3 of the pins on your Arduino.

So you would only use 3 pins to read the seven switches, which would leave you with 9 pins to play with, for the LCD.

In addition, you could use a similar method for the LCD, using a shift-out register, and use just 3 pins for the 6 inputs of the LCD. A tutorial for that is Alphanumeric LCD with Shift Register on Arduino – part 1, using the AlphaLCD library or 3-Wire Serial LCD using a Shift Register, which has no library, but provides code.

This would leave you with 6 pins free (out of the total 12 pins, if you exclude pins 0 and 1 for serial), after both the switches and LCD are wired up.

Of course, this solution requires you to purchase one or two shift (in and/or out) registers.

The Arduino IDE may come with a built-in library that use shift registers, but I am not sure about that. Maybe someone can confirm, or refute, this?

I hope that this helps.

# Answer
> 0 votes
Am new at this but I am working on a similar work, it is possible to use the pin 0 for your keypad, the pin is a RX pin by default making the pins(0,2,3,4,5,6,7).

As for the LCD I would suggest you use an i2c backpack, it is a parallel to serial converter and means you would only need to use 2 pins (SDA, SCL which would be connected to pin A4, A5)

Try the code below for the keypad (The code is if you have an i2c backpack)

```
#include <Wire.h>
#include <Keypad.h> //keypad library
#include <LiquidCrystal_I2C.h> //library for the backpack

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

//define the Symbols on the buttons of the keypads
  char hexaKeys[COLS][ROWS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};

byte rowPins[ROWS] = {0, 2, 3, 4}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 6, 7, 8}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

void setup(){
  Serial.begin(9600);
  lcd.begin(16,2);
  for(int i = 0; i< 3; i++)
  {
    lcd.backlight();  delay(250);
    lcd.noBacklight();  delay(250);
  }
  lcd.backlight();
}

void loop(){

  char customKey = customKeypad.getKey();

  if (customKey){
    lcd.print(customKey);
  }
}

```

---
Tags: arduino-uno, lcd
---


# Question
Title: Problems returning char array from function, value gets messed up
I use the Base64 library for Arduino (but I don't think the problem is related to the library) and have the following function definition:

```
char* decodeImage(char inputString[], unsigned int inputStringLength) {
  int decodedLength = Base64.decodedLength(inputString, inputStringLength);
  char decodedString[decodedLength];
  Base64.decode(decodedString, inputString, inputStringLength);
  Serial.printf("%s",decodedString); // prints "Base64DecodeExample"
  return decodedString;
}

```

Later on, I use the following snippet to access the function:

```
  char inputString[] = "QmFzZTY0RGVjb2RlRXhhbXBsZQA=";
  char* output = decodeImage(inputString, sizeof(inputString));
  Serial.printf("%s",output); // prints garbage

```

The problem is, that the result of the decoding INSIDE the function seems to be correct, but when I return the value to the calling code, the value get garbled somehow.

I suppose this has something to do with pointer magic or "decaying" of references. Has someone a suggestion?

# Answer
> 6 votes
Your variable `decodedString[]` is created inside the function, used inside the function - and destroyed inside the function before it returns.

See how your function `decodeImage()` returns a `char *`? That's a *pointer* to a character array, not the whole array - and you can't return a whole array. The pointer is successfully returned all right - but what it is pointing to is overwritten by future calls and future created variables.

This is the perennial problem of C programmers: how to return something created inside the function. You have four choices (each with their own problems):

1. You can make the variable global - put it outside the function and let anyone access it. Then you don't even need to return the string - it's already accessible.
2. You can make `decodedString` a permanent part of the function by making it `static`:

```
static char decodedString[64];

```

> Note that the above two solutions have the same two problems:
> a. There is only one array. That means that if the same function is called again, it will *overwrite* the results from last time - use it before you lose it!
> b. You can't calculate the length and then use it - it has to be created at the maximum possible size.
3. You can make the caller pass in the array to fill. Rather than return the array, have another parameter that is the array to fill - and for safety's sake, get them to pass in the size of the array too. You'll have to check that and return an error if it's not big enough - or do something else sensible.
4. You can allocate the memory from a different area that where it's currently being allocated from. That area is called the "heap" - it's just a heap o' memory that you can request chunks from - and don't forget to give it back!

To request memory from the heap, you call the function `malloc` and pass in the number of bytes that you want. It returns a pointer to that lump of memory:

```
char *decodedString = (char *)malloc(decodedLength);

```

Note that `malloc` doesn't know what you're going to use the memory for, so you have to tell the compiler - that's what the `(char *)` before the call to `malloc` does.

But if you use `malloc`, at some stage you must give the memory back with a call to `free`:

```
free(returnedString);

```

The function that did the `malloc` doesn't have to be the function that `free`s it - any function can, as long as some function does! Otherwise you'll run out of heap.

Another thing that you must NOT do is call `free` on the same block twice: that will corrupt the heap, since it will mark the same block on the heap twice, and hand it back out twice later, corrupting the data when it is used again.

### EDIT

There's a C++ version of `malloc` / `free` called `new` / `delete`. You use them similarly:

```
char *decodedString = new char[decodedLength];
...
// And later...
delete [] returnedString;

```

It looks and behaves similarly to `malloc` and `free`, without the ugly `(char *)` type-cast. Note that since an array was allocated with the `new`, you need to call the array version of `delete` by adding the `[]` as shown.

---
Tags: c++, esp8266
---


# Question
Title: How to call class A's method from class B?
I wish to access methods and fields, as well as change them, of class A from class B. Since the main Arduino sketch is not a class, but a list of fields and methods, I created a separate MainClass with a method printStuff() that I want to call from class DoClass. This is how I go about it:

The main sketch:

```
#include "MainClass.h"
MainClass m;
void setup() {
  m.setup();
}
void loop() {
  m.loop();
}

```

MainClass.h:

```
/*
  MainClass.h
*/
#ifndef MainClass_h
#define MainClass_h
#include "Arduino.h"
class MainClass
{
  public:
    MainClass();
    void setup();
    void loop();
    void printStuff();
};
#endif

```

MainClass.cpp:

```
/*
  MainClass.cpp
*/

#include "Arduino.h"
#include "MainClass.h"
#include "DoClass.h"
MainClass::MainClass()
{
  d DoClass(this);
}
void MainClass::setup(){
  Serial.begin(9600);
}
void MainClass::loop(){
  d.callMainClassFunct();
}
void MainClass::printStuff(){
  Serial.println("printing stuff");
}

```

DoClass.h:

```
/*
  DoClass.h
*/
#ifndef DoClass_h
#define DoClass_h

#include "Arduino.h"
#include "MainClass.h"
class DoClass
{
  public:
    DoClass(MainClass m);
    void callMainClassFunct();
  private:
    MainClass _m;
};
#endif

```

DoClass.cpp:

```
/*
  DoClass.cpp
*/

#include "Arduino.h"
#include "MainClass.h"
#include "DoClass.h"

DoClass::DoClass(MainClass m)
{
  _m = m;
}

void DoClass::callMainClassFunct(){
  _m.printStuff();
}

```

This produces a myriad of errors. Each time I change something, a new kind of error appears, as though I was in a vicious cycle. Clearly, I am unfamiliar with C++. It would greatly help me if you could alter my code so that it works, keeping in mind that I would like to both access methods and fields of class MainClass from class DoClass and change those fields from class DoClass.

For reference, in Java, I would achieve the same in the following way:

MainClass.java:

```
public class MainClass{
    DoClass d;

    public MainClass(){
        d = new DoClass(this);
}

    public void setup(){

}

public void loop(){
    d.callMainClassFunct();
}

public void printStuff(){
    Serial.println("print stuff");
}

}

```

DoClass.java:

```
public class DoClass{
       MainClass _m;
       public DoClass(MainClass m){
          _m = m;
       }
       public callMainClassFunct(){
         _m.printStuff();
}

}

```

Passing this to the constructor od DoClass passes the value of the reference pointing to MainClass instantitated in the main sketch file. Then, by prepending the name of the instantiated object (in this case, "m"), followed by a dot, I can simply access and change all values of that object from DoClass (provided those methods and fields are visible to DoClass, which is the case here).

I have posted before about this issue, but did not receive any answers to my specific question and could not comment because I do not have enough reputation. Thank you to those who tried to answer me, but the answers did not pertain to my specific question. This time I have included more information to show my problem more clearly. Thank you in advance for your help.

# Answer
In your Java version, you define `MainClass` like this (my comments added):

```
public class MainClass{ // Define a new Class
    DoClass d;          // Add a member variable to the class
    public MainClass(){
        d = new DoClass(this); // Initialise the member variable
    } // MainClass()
} // MainClass

```

In your C++ you don't do the same thing - but you should! The class needs a `DoClass` member so that you can use it in other `MainClass` functions:

```
// MainClass.h
...
#include "DoClass.h" // Need the .h here - remove it from the .cpp
class MainClass
{
  public:
    MainClass();
    void setup();
    void loop();
    void printStuff();
  private:
    DoClass _d; // Create a private member variable to use
};

```

and

```
// MainClass.cpp
MainClass::MainClass() : // MainClass constructor (note colon)
           _d(*this) // Initialise member
{
} // MainClass::MainClass()

```

Now, you want `DoClass` to be able to use `MainClass`, so you passed it into `DoClass`'s constructor. But `DoClass` cannot have a `MainClass` inside it - `MainClass` already has a `DoClass` inside it! Infinite impossibility! So you need `DoClass` to merely contain a *reference* to the `MainClass` that it sits inside. That's the C++ unary `&` operator (different from the binary `&` operator), which is used similar to the pointer `*` operator:

```
// DoClass.h
...
// Need to advise compiler MainClass exists...
// but can't #include MainClass.h! Infinite loop!
class MainClass;

class DoClass
{
public:
    DoClass(MainClass &m); // Reference to MainClass
    void callMainClassFunct();
private:
    MainClass &_m; // Reference to MainClass
};

```

and

```
// DoClass.cpp
DoClass::DoClass(MainClass &m) : // DoClass constructor - note colon
         _m(m) // Initialise member variable
{
}

```
> 1 votes

---
Tags: class
---