title: Connecting Arduino Arduino to MOSFET

text:
# Question
Title: Connecting Arduino Arduino to MOSFET
I want to use my Arduino Nano to control a 12V peristaltic pump via a BDX33c N-Channel MOSFET. The pump has a maximum current draw of 1,4 A. The Arduino (via VIN) and the pump are powered by a 12V supply. I connected the parts like shown in the schematic diagram.

When I plugged the supply in, the Arduino voltage regulator and the Mosfet got really hot (I could not touch it longer than 1-2 seconds) and the RX-LED was on continously, even after turning it off and on again. The Arduino isn't recognized by my Computer anymore, so I assume it is dead. What did I do wrong with my wiring?

# Answer
> 2 votes
That little blue wire on your breadboard is shorting out the motor. You have most likely now blown the transistor and maybe your power supply. The 12V may also now have made its way into the Arduino through the dead transistor and nuked the rest of it.

Alternatively, the massive base currents imposed by the shorted ground connection may have burned out parts of the Arduino.

# Answer
> 1 votes
> That little blue wire on your breadboard is shorting out the motor.

That is not the problem. That blue wire is actually correct. It connects the source to ground. (-ve)

Your drawing shows the Drain of the Mosfet connected to +12 volts and the Source connected to ground. (the -ve of the supply) If you didn't have the short (blue wire from Source to ground) it still would not have worked.

You can't put an N channel mosfet in the positive side of the supply and control it from a voltage lower than the positive supply. (something the previous answer didn't even mention)

You must have the source connected to ground (as you have) but the drain has to then connect directly to the motor, and the other side of the motor goes to the +12 connection. This would be the correct way, but there still is an important omission. You need to have a diode connected across the motor to control the flyback pulse when the mosfet turns off. Otherwise the voltage spike generated by the motor's inductance will destroy the mosfet switch.

Your blue wire on the breadboard is correct. What is wrong is the red wire to the center terminal of the mosfet. The red wire should be going to the motor. The Blue/yellow connection. The green wire should be going to the mosfet's center pin.And as I said before, there needs to be a diode across the motor, with the cathode (line on the body of the diode) connected to the +ve side of the motor connection.

This is a correct drawing as far as the mosfet and motor connections are concerned. This drawing shows 5 volts being brought to the breadboard to power the motor. In your case this should be the 12 volts from the power supply.

While the beadboard may be adequate for verifying the circuit, it may cause connection problems due to the significant current that the motor will draw. Even if you wired it up properly you may still have issues due to the poor connections.

EDIT:

I looked up the specs for the BDX33B and it is a darlington transistor and not a mosfet. But in the end, all that I said also applies whether it was a bipolar transistor or a mosfet. But you need to include a series resistor as shown in the drawing I provided. You can't drive it direct from a port pin as if it were a mosfet.

Another schematic.

This shows a darlington transistor like the one you listed, and a 12 volt power source.

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


# Question
Title: What does this lines mean in RFID UID Card Reader Code?
I'm currently doing a project using RFID. I'm wondering how this lines of the code work. I know that this has something to do with getting the UID of a scanned/tapped card, but can someone please explain or elaborate to me each line, how it executes? Thank you very much.

```
  String ID = "";
  for (byte i = 0; i < 4; i ++) {
    ID += (rfid.uid.uidByte[i] < 0x10 ? "0" : "")
          + String(rfid.uid.uidByte[i], HEX)
          + (i != 3 ? ":" : "" );
  }

```

# Answer
The code formats UUID as a string of 4 hex bytes (each bytes a pair of hex digits) separated by colons.

```
String ID = ""

```

Blank the string

```
for (byte i = 0; i < 4; i ++){

```

Iterate over the four bytes of the UUID

```
  ID +=

```

Add the following to the string "ID"

```
(rfid.uid.uidByte[i] < 0x10 ? "0" : "") +

```

If the hex number to be displayed is less than 0x10, add a leading '0' to the string 'ID'. This ensures the UUIDs are all aligned and all bytes within the UUID are displayed as two hex digits (even if only one is needed). It uses the ternary condition operator, which is a compact if/then/else that can only return one of two values (rather than executing chunks of code). See https://en.wikipedia.org/wiki/%3F: for more on the ternary condition operator.

```
 String(rfid.uid.uidByte[i], HEX) +

```

Add the UUID to the string 'ID' as HEX.

```
   (i != 3 ? ":" : "" );

```

Another instance of the ternary condition operator. This one adds a colon to the string 'ID' after the hex byte unless the index is 3 (ie the last one).

```
 }

```

End of for loop. This means that the result is nn:nn:nn:nn instead of nn:nn:n:nn: (leave off trailing colon and differing numbers of hex digits).
> 3 votes

---
Tags: rfid
---


title: Digispark ATtiny85 keyboard

text:
# Question
Title: Digispark ATtiny85 keyboard
I have a small project that I have in mind and I'm pretty new with Arduino.

I want to make a small device that if a key was pressed it would do something.

Now I know I could use a button with the device but I want to specifically use a Cherry MX Blue Switch.

So I wanted to know if the test code I wrote up would get me in the right stating place and I want to know where I would wire the key switch onto the board.

From how I have the code written I'm guessing I connect the positive pin from the switch to P0 on the board and the other pin to ground on the board, is this correct?

```
#include "DigiKeyboard.h"

void setup() {
    pinMode(0, INPUT);
}

void loop() {
    // put your main code here, to run repeatedly:
    if(digitalRead(0)==HIGH){
        DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT,KEY_R);
        DigiKeyboard.print("test");
    }
}

```

# Answer
I would suggest to connect one pin of the with to 5v and the other to ground. The Arduino will be able to detect 5v as logic HIGH.

The code looks correct except for better programming technique I would suggest to indent you code, this make debugging easier for longer programs:

```
#include "DigiKeyboard.h"

void setup() {

   pinMode(0, INPUT);

}

void loop() {
  // put your main code here, to run repeatedly:

  if(digitalRead(0)==HIGH){

    DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT,KEY_R);
    DigiKeyboard.print("test");

  }
}

```
> 1 votes

# Answer
Do you want the absolute lowest power consumption? If yes then instead of using a microcontroller, use a dual D type latch. The circuit below will take the first break of the optical beam, turn on the output for that latch, and will block the other latch from turning on.

When the clock input goes high (beam broken) the high on the D input is transferred to Q and -Q will go low. That low will force the output of the other latch to stay low.

To reset the light the push button switch is used to clear the Q output. It is then ready again.

I didn't show the power supply (bypass cap). The chip is a CD74HC74. 14 pins containing two latches.The only current drawn is the LED current and the current of the opto-transistors.
> 0 votes

---
Tags: attiny, keyboard, attiny85, digispark
---


# Question
Title: Calculate sensor unique address with a 8 position DIP Switch
I have a large amount of sensor boards that I need to be able to configure setting unique addresses. Each sensor is attached to it's own arduino, I'm using a 8 position DIP switch for setting the address.

I have tried diferent approaches. When I switch On and OFF I get random values. I understood that I would be able to get up to 255 possible positions, but without being able to get the proper byte data I would have to manually code each possibility, which seems wrong.

Schematic :

Code

```
#include "DipSwitchI2C.h"

DipSwitchI2C::DipSwitchI2C(int address)
{
    _address = address;
}

void DipSwitchI2C::begin()
{
    Wire.begin();
}

int DipSwitchI2C::read()
{
    unsigned int address = 0;
    unsigned int value = 0;

    Wire.requestFrom(_address, 1);
    if (Wire.available())
    {
        value = Wire.read();
    }
    Wire.endTransmission();

    for (int i = 0; i < 8; i++)
    {
        address += (value & (1<<i)) > 0;
    }

    return address;
}

```

# Answer
As @jsotola noted the solution was simple:

```
int DipSwitchI2C::read()
{
    unsigned int address = 1;

    Wire.requestFrom(_address, 1);
    if (Wire.available())
    {
        address = Wire.read();
    }
    Wire.endTransmission();

    return address;
 }

```
> 1 votes

# Answer
Assuming that your switches are on pins 2-9 on an UNO. Change pins to match what you actually have.

```
byte addressVal = 0;
for(int i = 2: i<10; i++){
    addressVal <<= 1;
    addressVal += digitalRead(i);
}

```

This will check each switch and add a 1 to the end of the byte. On each iteration it shifts the contents of that byte 1 place to the left. After it reads all the pins you have a byte with a value 0 to 255 depending on the states of the pins.
> 0 votes

---
Tags: switch
---


# Question
Title: Do some variables not hold their value when a while loop is exited?
Sorry if i'm asking too many silly questions but i'm really stumped on this one. I understand if I set a variable inside a loop that that variable won't be within scope from the outside of the loop.

Usually I find that variables declared outside of a loop will be accessible inside the loop, modifiable within the loop, and hold their value when exiting the loop but in this case that doesn't seem to be happening.

There are books on the sd card. I'm saving the name of each book to an array from within a while loop. When the while loop is exited the array is still null.

How can I solve this? thanks

```
int amtBooks = 5; //this gets set previously but im not going to show all the code

// create an array the size of the amount of books
  char* book[amtBooks] = { NULL };

// assign the name of each book to the array
  int bookNum = 0;
  while (true) {

    File entry =  root.openNextFile();
      if (! entry) {
        break; // no more files
      }

    book[bookNum] = entry.name();

    Serial.println(book[bookNum]); // <--------PRINTS FINE HERE

    bookNum ++;

  }

  root.close(); // close the stream

Serial.println(book[0]); <---ONCE OUT OF THE WHILE LOOP NOTHING DISPLAYS?
Serial.println(book[1]);

```

# Answer
> variables declared outside of a loop will be accessible inside the loop, modifiable within the loop, and hold their value when exiting the loop

This is correct.

> in this case that doesn't seem to be happening.

It is happening. The reason it looks like it doesn't is that `book[bookNum]` is a pointer: the address of some data in memory. You can check that the pointer *does* hold its value by printing it:

```
Serial.println((uintptr_t) book[bookNum]);

```

However, the statement you used:

```
Serial.println(book[bookNum]);

```

has a different meaning. It doesn't print the value of the variable (i.e. the pointer): it prints the characters that are stored at the pointed-to address, up to and excluding the first NUL.

Your problem comes from the fact that when you declare

```
File entry =  root.openNextFile();

```

you have a variable that is local to the loop. Then, when calling the method

```
entry.name()

```

you get a pointer to an array of characters that belongs to the `entry` object. This pointer is only valid as long as the object is in scope. As soon as it gets out of scope (at the end of each loop iteration), the `entry` object is destroyed and all memory belonging to it is released. At this point the pointer you saved is a “dangling” pointer: it points to an area of memory that has already been deallocated.

The proper fix is to allocate yourself the memory you need to hold the character arrays, as in:

```
for (int bookNum = 0; bookNum < amtBooks; bookNum++) {
    File entry = root.openNextFile();
    if (!entry) break;
    const char *name = entry.name();
    book[bookNum] = (char *) malloc(strlen(name) + 1);
    strcpy(book[bookNum], name);
    Serial.println(book[bookNum]);
}

```

If you know in advance the maximum length of a book name, you could follow the advice of Jot and Juraj and statically allocate the maximum space you may need. That would be safer in terms of memory management.
> 1 votes

# Answer
You store a pointer to char array `name` in `File` variable `entry`. The `entry` goes out of scope (is deleted from stack) and your stored pointer points nowhere.

You need `char book[amtBooks][13] = {{0}};` and `strcpy(book[bookNum], entry.name());`
> 0 votes

# Answer
It helps if you know where the variables are located.

Local variables are located on the stack. They are created when entering a function and vanish when exit from a function. They can even be locally inside a `if`, `for`, `while` or other statement when they are declared inside that statement.

Global variables have a fixed memory location. They can be used from every function.

When a pointer is created and it points to nothing, then you may not write data to where that pointer it pointing to.
You create a array of pointers, but you need memory that you can use to store data. For example: `char booknames[5][20]`. An array of text is often copied with strcpy().
> -1 votes

---
Tags: array, variables
---


# Question
Title: Stacking 3 of the same shields on top of each other and instructing them in sync
**Context:** I have an audio track separated into individual channels grouped by frequency and speaker location. I need to play all three of these channels simultaneously and perform instructions like play, stop, repeat, skip across all channels to keep them in sync.

This is part of an outdoor installation so the solution must be modular and robust.

If possible, the most elegant solution I could come up with is to use an Arduino Leonardo and stack 3 Adafruit Music Maker Shield on each other.

**Reasons why I think it might be technically feasible:**

~~1. Each shield can share communication over I2C~~

2. Looking at the VS1053b Datasheet (the IC used in the shield) the chip at max load consumes Maximum 60mA, and typically 37mA. Arduino can drive a max of 500mA so these three shields should consume a small portion of that. The Arduino will also be powered via 12v power supply.

**Details i'm not so clear on:**

1. How will I differentiate between each shield when sending instructions or do I need to even need consider this if I want them to function as one?

# Answer
> 1 votes
The shields use SPI. There are more slave select pins on the shield for different devices of the shield. The first shield can use the default pins, but on next shields you must bend the default pins of the shield to side and connect them with a jumper cable to other set of pins of Arduino.

Then in sketch you need to define the select pins in constructor for each instance of the handling object Adafruit\_VS1053.

```
Adafruit_VS1053_FilePlayer musicPlayer =
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);
Adafruit_VS1053_FilePlayer musicPlayer2 =
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS_2, SHIELD_DCS_2, DREQ_2, CARDCS);
Adafruit_VS1053_FilePlayer musicPlayer3 =
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS_3, SHIELD_DCS_3, DREQ_3, CARDCS);

```

They will be not in microseconds sync since you must instruct them individually.

Use only one SD card because the SD library can't support more of them. Advantages of one SD card are only one cs pin and less active devices on SPI. There is no direct read by the player from SD card on the same shield.

Note: The SPI device is the SD card not the adapter. An empty adapter is nothing on bus so you can put the card for example into the shield on top and do not need bend the SD card cs pins on other shields.

# Answer
> 1 votes
The shield actually uses SPI.

So you will need to trace the chip select and make sure that each shield uses a different arduino pin.

---
Tags: shields, spi, arduino-leonardo, adafruit
---


title: Interfacing with an SSI sensor?

text:
# Question
Title: Interfacing with an SSI sensor?
I'm trying to interface with version RM08S of this rotary encoder using an Arduino Mega. The sensor supports a "Synchro serial interface (SSI), single ended" interface. I'm unfamiliar with this protocol.

Despite the name, it doesn't appear to match the description of the formal SSI or RS-422 specification, since that requires two wires for differential clock and data lines, whereas this sensor only has a single wire for each. This makes it sound more like IIC, but without the bus-like functionality.

Googling finds very few results on interfacing the Arduino to SSI devices, much less any standard libraries. This forum thread asks a similar question, but doesn't seem to resolve the issue.

Since there's just a clock and data line, would reading from this be as simple as toggling clock, and then reading the 10-bits of data from the data line, sequentially with each clock tick, accounting for whatever bits are used to pad the packet?

# Answer
It's just SPI.

```
SPI.begin();
SPI.setDataMode(SPI_MODE2);

// ...

uint8_t h = SPI.transfer(0x00);
uint8_t l = SPI.transfer(0x00);
delayMicroseconds(20); // Indicate EOT
uint16_t v = (h << 8) | l;
v >>= 4; // for 12 bit resolution, 5 for 11 bit, 6 for 10 bit etc.

```

For 8 bit resolution or less you only need one SPI.transfer, and subtract 8 from the right-shift amount.

Wiring is simple: clock to SCK (52 or ICSP 3) and data to MISO (50 or ICSP 1).

The timing diagrams in the datasheet (page 5) describe it all in detail.
> 3 votes

---
Tags: arduino-mega, sensors, spi, rotary-encoder
---


# Question
Title: eclipse photon with cdt-arduino plugin can't upload sketches
i've recently decided to give eclipse-photon-cdt a shot. i use it with the built in arduino plugin, downloaded my feather m0 board config and tried to upload an empty sketch. failed, the console shows it tries to connect but fails. of course arudino ide 1.8.5 succeeds wonderfully. point is if i copy paste the command line activating bossac i get the same result. i also know why. when using scripts i need to use a python scripts that uses serial signaling to reset the feather into bootloader mode. arduino ide does it on his own probably using java. eclipse doesn't do that which sounds like a huge bug to me.

am i missing something ? or did they actually assumed i'll press twice on the reset button on the board each and every time i want to upload a sketch ?

# Answer
> 0 votes
It sounds to me like Eclipse doesn't know how to reboot the board into the bootloader.

Traditional Arduinos automatically boot into the bootloader when the board is reset, and the board resets every time you open the serial port thanks to the USB chip having DTR connected (through a capacitor) to the reset pin of the man MCU.

Chips with a direct USB connection can't do that (boards like the M0 Feather, the Leonardo, etc). Instead they have to be rebooted by opening the serial port at 1200 baud and then closing it again.

With the "traditional" boards the IDE neither knows, nor cares, about rebooting the board - it just happens. However with direct USB boards the IDE has to have specific code to perform the reboot at the right time. The Arduino IDE has that code. However I would guess that the Eclipse plugin either doesn't implement that, or doesn't have the ability to implement it.

So you will have to manually reset the board for programming.

---
Tags: adafruit, eclipse
---


# Question
Title: How do I connect my Luxorparts keypad to my Arduino?
I just bought a 12 digit keypad from Luxorparts and it doesn't come with any schematics showing how it's wired at all. How do I figure out how to connect it to my Arduino?

# Answer
There's a guide here that helped me out: Keypad Tutorial, that will show you the means of figuring out how the keypad is wired. I followed it and figured out that for that specific keypad (the Luxorparts keypad) the setup is as follows:

(From left to right on the keypad pins and on the rows and columns)

Pin1: Not connected
Pin2: Connected to the 2:nd collumn
Pin3: Connected to the 1:st row
Pin4: Connected to the 1:st collumn
Pin5: Connected to the 4:th row
Pin6: Connected to the 3:rd column
Pin7: Connected to the 3:rd row
Pin8: Connected to the 2:nd row
Pin9: Not connected

I modified the example code from the link above to reflect this specific Keypad:

```
#include <Keypad.h>

const byte ROW0 = 3;
const byte ROW1 = 8;
const byte ROW2 = 7;
const byte ROW3 = 5;

const byte COL0 = 4;
const byte COL1 = 2;
const byte COL2 = 6;

const byte ROWS = 4; // Four rows
const byte COLS = 3; // Three columns
// Define the Keymap
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'#','0','*'}
};
// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = { ROW0, ROW1, ROW2, ROW3 };
// Connect keypad COL0, COL1 and COL2 to these Arduino pins.
byte colPins[COLS] = { COL0, COL1, COL2 };

// Create the Keypad
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

#define ledpin 13

void setup()
{
  pinMode(ledpin,OUTPUT);
  digitalWrite(ledpin, HIGH);
  Serial.begin(9600);
}

void loop()
{
  char key = kpd.getKey();
  if(key)  // Check for a valid key.
  {
    switch (key)
    {
      case '*':
        digitalWrite(ledpin, LOW);
        break;
      case '#':
        digitalWrite(ledpin, HIGH);
        break;
      default:
        Serial.println(key);
    }
  }
}

```

To run that, simply connect each pin from the keypad, in order, to the arduino, so the second pin from the keypad goes to the second digital pin on the Arduino and so on.

I asked the question after I'd already figured out the answer in hopes of helping anyone else who bought that specific keypad.
> 1 votes

---
Tags: pins, hardware, input
---


title: How to repeat the code

text:
# Question
Title: How to repeat the code
I want to make my biped robot keep walking, but it only move for twice, this biped robot project is important for my Capstone project. The code below is the code that I used

```
#include <Servo.h>

int HipR_Pin = 9;
int HipL_Pin = 10;

int KneeR_Pin = 5;
int KneeL_Pin = 6;

int AnkleR_Pin = 3;
int AnkleL_Pin = 11;

Servo HipR;
Servo HipL;

Servo KneeR;
Servo KneeL;

Servo AnkleR;
Servo AnkleL;

void setup() {
  HipR.attach(HipR_Pin);
  HipL.attach(HipL_Pin);
  KneeR.attach(KneeR_Pin);
  KneeL.attach(KneeL_Pin);
  AnkleR.attach(KneeR_Pin);
  AnkleL.attach(KneeL_Pin);
}

void loop() {

  for (int i=0; i < 7; i++)
  {
    RightStep1;
    LeftStep1;
    RightStep2;
    LeftStep2;
    RightStep3;
    LeftStep3;
    RightStep4;
    LeftStep4;
  }
  ;
}

void RightStep1()
{
  HipR.write(80);
  HipL.write(80);
  KneeR.write(100);
  KneeL.write(100);
  AnkleR.write(20);
  AnkleL.write(20);

}

void LeftStep1()
{
  HipR.write(90);
  HipL.write(90);
  KneeR.write(70);
  KneeL.write(70);
  AnkleR.write(20);
  AnkleL.write(20);

}

void RightStep2()
{
  HipR.write(70);
  HipL.write(70);
  KneeR.write(80);
  KneeL.write(80);
  AnkleR.write(10);
  AnkleL.write(10);

}

void LeftStep2()
{
  HipR.write(60);
  HipL.write(60);
  KneeR.write(90);
  KneeL.write(90);
  AnkleR.write(20);
  AnkleL.write(20);

}
void RightStep3()
{
  HipR.write(40);
  HipL.write(40);
  KneeR.write(60);
  KneeL.write(60);
  AnkleR.write(10);
  AnkleL.write(10);

}

void LeftStep3()
{
  HipR.write(50);
  HipL.write(50);
  KneeR.write(70);
  KneeL.write(70);
  AnkleR.write(20);
  AnkleL.write(20);

}
void RightStep4()
{
  HipR.write(60);
  HipL.write(60);
  KneeR.write(60);
  KneeL.write(60);
  AnkleR.write(10);
  AnkleL.write(10);

}

void LeftStep4()
{
  HipR.write(70);
  HipL.write(70);
  KneeR.write(50);
  KneeL.write(50);
  AnkleR.write(20);
  AnkleL.write(20);

}

```

# Answer
This may not be a direct answer to your question but... when I see so much code repetition, I cannot help but suggest you try to avoid repeating yourself. All your `Step()` functions do exactly the same *actions*, only with different *data*. You can then factor the actions into a single function, and provide it different data as parameters. There are many ways to achieve this in C++. I am going to show four of them, in order from the most basic to the most esoteric.

The simplest one is to use a plain function and give it the angles as parameters. This is basically what Michel Keijzers’ answer suggests. My take on it would be

```
void Step(uint8_t hip, uint8_t knee, uint8_t ankle)
{
    HipR.write(hip);
    HipL.write(hip);
    KneeR.write(knee);
    KneeL.write(knee);
    AnkleR.write(ankle);
    AnkleL.write(ankle);
}

```

which you can then use in the main loop as

```
Step( 80, 100,  20);  // right 1
Step( 90,  70,  20);  // left 1
...

```

The next step in code modularity would be to group all the angles for a single step into a compound data structure called a `struct`, then the function to perform a step takes a single parameter which is this data structure:

```
struct Step {
    uint8_t hip;
    uint8_t knee;
    uint8_t ankle;
};

void doStep(Step s)
{
    HipR.write(s.hip);
    HipL.write(s.hip);
    KneeR.write(s.knee);
    KneeL.write(s.knee);
    AnkleR.write(s.ankle);
    AnkleL.write(s.ankle);
}

```

These structs would be defined as

```
Step RightStep1 = { 80, 100,  20};
Step LeftStep1  = { 90,  70,  20};
...

```

and used in `loop()` as

```
doStep(RightStep1);
doStep(LeftStep1);
...

```

One step further, you can embed the function within the data structure. The embedded function then becomes a “method” of the data structure which is now called an “object”:

```
struct Step {
    uint8_t hip;
    uint8_t knee;
    uint8_t ankle;
    void perform() {
        HipR.write(hip);
        HipL.write(hip);
        KneeR.write(knee);
        KneeL.write(knee);
        AnkleR.write(ankle);
        AnkleL.write(ankle);
    }
};

```

The structs can be defined just as before, and used as

```
RightStep1.perform();
LeftStep1.perform();
...

```

One last technique involves making the objects themselves behave as functions that can be called. This kind of callable object is called a “functor”, and is kind of syntactic sugar over a method call. We just have to rename the relevant method as `operator()`:

```
struct Step {
    uint8_t hip;
    uint8_t knee;
    uint8_t ankle;
    void operator()() {
        HipR.write(hip);
        HipL.write(hip);
        KneeR.write(knee);
        KneeL.write(knee);
        AnkleR.write(ankle);
        AnkleL.write(ankle);
    }
};

```

The structs are still defined in the same way, but now they can be used as if they were plain functions:

```
RightStep1();
LeftStep1();
...

```

I suggest you use whatever technique you feel the most comfortable with. There is a logic progression though: the more you improve your C++ skills the more comfortable you will be with the latest ones.
> 2 votes

# Answer
In addition to @Gerben's answer, you aren't giving any time for your movements to complete. `.write()` doesn't wait for the movement to complete - it just sets the target angle. You should add enough `delay(...)` calls to wait for your movements to finish before you start a new one.
> 1 votes

# Answer
To call a function you need to add parentheses after the function name.

```
void loop() {

  for (int i=0; i < 7; i++)
  {
    RightStep1();
    LeftStep1();
    RightStep2();
    LeftStep2();
    RightStep3();
    LeftStep3();
    RightStep4();
    LeftStep4();
  }
  ;//<<--also remove this stray semi-colon
}

```
> 0 votes

# Answer
Instead of all the different step functions you can better parameterize them for example

```
void LeftStep4()
{
  HipR.write(70);
  HipL.write(70);
  KneeR.write(50);
  KneeL.write(50);
  AnkleR.write(20);
  AnkleL.write(20);
}

```

will be

```
void LeftStep4()
{
  Move(70, 70, 50, 50, 20, 20);
}

```

and create a function

```
void Move(int hipR, int hipL, int kneeR, int kneeL, int ankleR, int ankleL)
  HipR.write(hipR);
  HipL.write(hipL);
  KneeR.write(kneeR);
  KneeL.write(kneeL);
  AnkleR.write(ankleR);
  AnkleL.write(ankleL);
}

```

The other functions will also be one liners like the first function LeftStep4.
> 0 votes

---
Tags: arduino-uno, programming, motor, servo, time
---


# Question
Title: How to pass 2 parameters with RCSwitch library?
I'm learning Arduino's world, but knowing very little about C and C++.

I'm trying to achieve a little RF transmitter which should send the temperature and humidity from a DHT-11 sensor to a Raspberry Pi.

I'm using the `RCSwitch` library to send information with the Arduino, and the `433Utils` library to receive it on the RPI.

Using those 2 libraries demos, I was able to send an integer, holding temperature or humidity information (`mySwitch.send("00001010");`), and read it on the RPI.

**But how can I send both informations so that the RPI will know which one is the temperature and the humidity ?**

I know I could just send both and assume the lowest is the temperature, but this would be very messy and not very rewarding.

## EDIT :

Following Edgar's answer in https://arduino.stackexchange.com/a/52992/11604, I know write:

```
void send_string(const char *str){
    int i = 0;
    for (char *p = str; *p; p++ ) {
        mySwitch.send((i<<8) + *p, 16);
        i++;
    }
}

void loop() {
    delay(1000);
    h=40.650;
    t=32.0078;
    hic=33.586;
    String x = "$H" + String(h) + "T" + String(t) + "HI" + String(hic);
    send_string(x.c_str());
}

```

Works perfectly ! (see his complete answer for the RPI-side code)

# Answer
The library you have chosen is not designed for transmitting information between nodes. It is intended for sending simple ON/OFF commands to RF-connected switches. Bending it to send data in the way you want would be difficult. Not impossible, but difficult.

Instead you should be considering a more suitable system, such as the popular RadioHead library. It appears to have Raspberry Pi support out of the box:

> Raspberry Pi Uses BCM2835 library for GPIO http://www.airspayce.com/mikem/bcm2835/ Currently works only with RH\_NRF24 driver or other drivers that do not require interrupt support. Contributed by Mike Poublon.

Alternatively a small Arduino as an interface between the RF module and the Pi may be another option.
> 1 votes

---
Tags: programming, rf
---


title: Stepper Motor with Limit Switches

text:
# Question
Title: Stepper Motor with Limit Switches
I have the code below which is my attempt to control a stepper motor direction that moves a carriage to the right and left. In addition there are limits at each end of the travel that when activated stops movement in the respected direction. My problem is that the motor works just fine in the left and right directions but I can only get one of the limit switches to work. I'd appreciate any suggestions.

```
int PUL = 7; //define Pulse pin
int DIR = 6; //define Direction pin
int ENA = 5; //define Enable Pin
int RGT = 3;
int LFT = 2;
int potPin = A5;
int count = 0;
int interval = 1000;
int val = 0;
int Spd = 500;

#define Limit01 8  // Pin 2 connected to Limit switch out
#define Limit02 9  // Pin 3 connected to Limit switch out

void setup() {
  pinMode (PUL, OUTPUT);
  pinMode (DIR, OUTPUT);
  pinMode (ENA, OUTPUT);
  Serial.begin(9600);
}

void loop() {

  if (digitalRead(LFT) == LOW) {  //  If joystick is moved Left
    if (digitalRead(Limit01) == HIGH) {} // check if limit switch is activated

    else {  //  if limit switch is not activated, move motor clockwise

      digitalWrite(DIR, LOW);
      digitalWrite(ENA, HIGH);
      digitalWrite(PUL, HIGH);
      delayMicroseconds(500);
      digitalWrite(PUL, LOW);
      delayMicroseconds(500);
    }
  }

  if (digitalRead(RGT) == LOW) { // If joystick is moved right

    if (digitalRead(Limit02) == HIGH) {} // check if limit switch is activated

    else {  //  if limit switch is not activated, move motor counter clockwise

      digitalWrite(DIR, HIGH);
      digitalWrite(ENA, HIGH);
      digitalWrite(PUL, HIGH);
      delayMicroseconds(500);
      digitalWrite(PUL, LOW);
      delayMicroseconds(500);

    }
  }
}

```

# Answer
What I understood from your question is you want only one limit switch to control the stepper motor in both directions.So here is the code that might be helpful for you in that case:

```
int dirpin_T1 = 2;
int dirH_T1 = 3;
int steppin_T1 = 4;
int limit = 10; // ASSUME LIMIT-SWITCH IS PLACED AT RIGHT CORNER
void setup() {
  pinMode(limit,INPUT);

  pinMode(dirpin_T1, OUTPUT);
  pinMode(dirH_T1, OUTPUT);
  pinMode(steppin_T1, OUTPUT);

}

void loop() { //STEPPER TRAVELLING LEFT TO RIGHT

    digitalWrite(dirpin_T1, LOW );
    digitalWrite(dirH_T1, LOW);
   do
   {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);

   }(digitalRead(limit)==HIGH); //AS LIMIT-SWITCH PRESSED MOTOR STOPS
  delay(500);
  //WHEN LIMIT-SWITCH IS LOW CHANGE THE DIRECTION OF MOTOR ROTATION
  if(digitalRead(limit)==LOW)
  {
      digitalWrite(dirpin_T1, LOW ); //CHANGE MOTOR DIRECTION (LOW TO HIGH)
      digitalWrite(dirH_T1, HIGH);
     for(int i=0; i<36000;i++)
      { //please try changing value of i as it depends on how much rotations you want your motor to step forward

      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
     }

  }
}

```

The simple logic would be to move the motor in one direction until limit-switch is HIGH. And to move it to the other direction when its LOW i.e already pressed.Correct me if I am wrong and try modifying the code as per this logic.However you need to change your code depending upon what type of driver you are using. Right now I am using TB6560 driver.You can use if loop instead of do while loop to make it easier to understand.
> 1 votes

# Answer
Use while ( condition) { code to execute } making sure the code itself is "short" not to overrun the condition

If you use while construct instead of do / while you are checking the condition first before code execution. while( not at limit switch) move stepper one step Also the limit switch active state should be ground, not +V. Safety issue. If you accidentally ground the signal it will be valid, if the signal path is grounded already , by accident, putting +V to it won't be detected.
> 0 votes

---
Tags: motor, stepper
---


title: Passing out an argument

text:
# Question
Title: Passing out an argument
I can't figure out why `test` is not passed properly to `test1`

```
#include <Arduino.h>

char *test1;
char *status_reply(char *test) {
        int ans_rel = 1;
        int ans_led = 0;
        int ans_sw = 1;
        sprintf(test,"%d%d%d",ans_rel,ans_sw,ans_led);
        Serial.println(test);
}

void setup() {
        Serial.begin(9600);
        status_reply(test1);
        Serial.println(test1);
}

void loop() {
        // put your main code here, to run repeatedly:
}

```

# Answer
This is not about Arduino. It is C. You have only a pointer to char now. You must allocate memory for the c-string.

`char test1[128];`

If you pass pointer to sprintf, the function will write to memory where the pointer points. Something somewhere in memory will be overwritten and the following print will print the string, but later the memory will be used for something else and your c-string disappear.
> 2 votes

---
Tags: string
---


title: LCDs larger than 20x04 and 5" diagonal

text:
# Question
Title: LCDs larger than 20x04 and 5" diagonal
Are there any i2c LCD screens that are larger than 2004 characters and larger than 4.8 x 2.7 x 1.2 inches in dimensions?

I have the Sainsmart 2004 LCD but it can't display all the information that I need. Maybe a 20x8 character screen? Because the screen will be viewed from a distance of about 50cm, the screen size should be at least 5" in diagonal.

# Answer
Naked displays... search e.g. Ebay for "40x4 lcd" (maybe enable "worldwide" search)...

...naked... so not i2c ... but Arduino libs for these displays exist (e.g.: liquidcrystal440), so add an Arduino-Pro or such and you can have i2c... basically they are two 40x2 displays on the same spi bus selected by different chip select lines...
> 1 votes

# Answer
The 44780 display chip used by these devices has 80 bytes of storage, which is why you can scroll the 2x16 side to side to show up to 40 characters per line. however 4x20 is 80 and that's the limit of the chip.
> 1 votes

# Answer
There are ST7920 based displays which may come close to what you are looking for. They have a similar parallel (4 or 8 bit) interface to the HD44780 based displays (as you have been using), but also support a 3-wire SPI-like interface.

A quick google found the datasheet here: https://www.lcd-module.de/eng/pdf/zubehoer/st7920\_chinese.pdf

They have both graphics and text modes, and most of the displays appear to have 128x64 pixels, giving 16x8 characters assuming 8x8 font, although it appears the native text font is 16x8 pixels.

While it might be more complicated to use these in graphics mode, they are probably the closest to the HD44780 based displays in appearance (large monochrome pixels), unlike other large displays which will probably have more (smaller) pixels than you need.

See also https://playground.arduino.cc/Code/LCD12864
> 0 votes

---
Tags: lcd, i2c
---


# Question
Title: How can I connect the Tamiya double gearbox to Arduino Uno?
I'm working on building my first robot. this is my first foray into DIY electronics. I already have an Arduino Uno, and I have ordered the Tamiya double gearbox here. My goal is to control the gearbox to move the robot, but from what I've already read, I need to have something between the Ardiuno and the motors. It seems like people have trouble doing that because the included motors are low voltage, so the Arduino motor shield won't easily work.

I'm looking for a clear solution to making this thing run, in the simplest way possible. One thing I'm considering is replacing the motors in the gearbox with these motors. If I do that, am I right in thinking I could run them from the Arduino motor shield?

If there is a simpler (or cheaper!) way of making it work than being stuck on the Arduino Motor shield, I'm game for that. I've just gravitated to that solution because it seems simpler as an electronics noob. (I haven't bought that shield yet.) But I'm really open to other solutions, so if you can, I'd appreciate the advice!

# Answer
Here's what I've found about both the motor shield and the motors:

* Motors are 3-6V and will use a lot of amperage. **This may be a problem with a mobile robot.** You'll have to figure out a power source that can provide 4+ amps... on battery power that's a lot. Personally, I would go with a continuous rotation servo for a compact, light robot.
* Motor sheild can provide 2x 2A channels at 5-12 V (Source) using the two `+` and `-` terminals on the bottom left side of the shield. You must connect external power, because USB can't provide enough power. I can't find if the motor shield will limit current if it goes over, but if you do use the gearbox, I'd recommend another route for control that's 1/6rd the price.

This chip was recommended by Pololu on the product page.

**Time to whip out your soldering iron!** Really, soldering is a great investment and you'll get to a point soon where you'll *need* one; there will be no other alternative. Luck for you, you only have to solder 16 joints. Headers are included.

Diagrams from Pololu's site:

> \*(Click to enlarge ^^^)\**

<sub>\*I added a little text to this image.</sub>
> 3 votes

# Answer
The FA130 type electric motors in the Tamiya Double Gearbox Kit (No. 70168) are 1.5v-3v DC motors with current ratings of 0.20A (no load), 0.66A (@ max. efficiency) and 2.2A (stall), see 1.5-3V DC Motor 6990 RPM. They are not high current motors.
> 1 votes

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


title: Running code through functions

text:
# Question
Title: Running code through functions
I am making a led cube where sequential lighting is used. So basically i need to repeat my commands for a given time. After much reasearch nothing turned up so decided to ask here.

---

Here is the code i need to reproduce in a working format

```
void loop(){
  runfor(500){
    DigitalWrite(5,HIGH);   //this is the command to be executed in other
                            //function
  }
}
void runfor(uint32_t duration){
  int timer = millis();
  while((millis()-timer)<=duration){
  //DigitalWrite(5,HIGH); will execute here
  }
}

```

So basically DigitalWrite(or any other code if used) will be repeatedly executed for 500 milliseconds

# Answer
> 4 votes
**EDIT** due to misunderstanding the question.

If you want to be able to pass instructions into a function, you will have to have a function for each set of instructions (that is, you cannot pass arbitrary statements as a function parameter), and then you adjust your `runfor()` function to accept a pointer-to-a-function parameter.

```
typedef void (*callback_function)(void);  // defining the type here makes the code easier to read when used in other places.

void runfor(uint32_t duration, callback_function patternCode){
  uint32_t timer = millis();
  while ((millis()-timer)<=duration) {
    //get these commands from caller function
    patternCode();
  }
}

void pattern1() {
  // Light pattern #1
}

void pattern2() {
  // Light pattern #2
}

void setup() {
  // Setup code
}

void loop() {
  runfor(1000, pattern1);
  runfor(2000, pattern2);
}

```

---

**ORIGINAL ANSWER**

Your starting pseudo-code is nearly there.

```
void runfor(uint32_t duration){
  uint32_t timer = millis();
  while ((millis()-timer)<=duration) {
    //get these commands from caller function
  }
}

```

Changes I made:

1. change `int` to `uint32_t` to accommodate all possible values of `millis()`.
2. change `for` keyword to `while`, which is the correct keyword for the loop type you want.
3. added semicolon after your `timer` assignment, per C syntax.

---
Tags: programming
---


# Question
Title: Can client IP address be obtained from Arduino Ethernet2 library for W5500 during client.connected() call?
I've found posts explaining how to get client IP by modifying the W5100 Ethernet library and the Adafruit CC3000 library but not the Ethernet2 lib for W5500 chip, which is different enough that the W5100 mod won't work. I suspect the TCP Socket struct will contain it, but haven't been able to find its declaration anywhere to confirm this so I can modify the library to make it accessible.

# Answer
Use the new update of the 'old' Ethernet library. It is version 2.00 and you can install or update it in the Library Manager in IDE. Note, **it is not Ethernet2 library**. The new Ethernet library supports W5500 and has `client.remoteIP()`.

example

```
  if (client.connect(server, 80)) {
    Serial.print("connected to ");
    Serial.println(client.remoteIP());

```

> New features in version 2.0.0 Auto-detection of W5100, W5200, and W5500 Ethernet hardware.
> 1 votes

# Answer
This solution works: http://forum.arduino.cc/index.php/topic,82416.0.html if "W5100.readSnDIPR(\_sock, remoteIP);" is replaced with "w5500.readSnDIPR(\_sock, remoteIP);" \[note the lower case 'w'\]. I didn't think it would because I can't find readSnDIPR() in the Ethernet2 library source, but after reviewing the Wiznet 5500 data sheet (https://www.mouser.com/pdfdocs/w5500\_ds\_v100e.PDF) I realized it was probably a read of the "Socket n Destination IP Address" register and decided to try it and see if it linked. It did, and successfully returns the remote IP after connecting.
> 0 votes

---
Tags: programming, networking, ethernet-shield
---


# Question
Title: RF remote control using VirtualWire on ATtiny85 running at 8MHz on internal oscillator
I'm trying to make an RF remote control using ATtiny85 running at 8MHz on internal oscillator, this cheap RF 434MHz transmitter module (like the one below), and VirtualWire lib, **but had no success so far**.

So, before I go any further, **is it possible to use VirtualWire with ATtiny85 running at 3.6V and 8MHz with its internal oscillator? If so, how?**

I've found a few scattered sources of information on the Net about it, but couldn't make much sense of it.

I have build ATMega328 versions of the receiver and transmitter using VirtualWire without any major problems. Both modules talk to each other will very little data drop out. Now, when I tried to replace the ATMega328 transmitter with a smaller version using the ATtiny85, I'm having problems.

Here are the symptoms:

1. The major one seem to be that when I add the VirtualWire include, **my sketch seems to slow down a lot**. So I figure it's a timing issue. But I'm not sure what the problem is.
2. I put a scope on ATtiny85 pin 6 (PB1) but **I don't see anything being transmitted**. I think I've messed up with the pin names.
3. I can make the LED blink and also can read the buttons without problems.

Here are the schematics and the board design for the remote controller:

The board is currently powered by 2 AA NiMH batteries that are currently at 2.6V. I can make the ATtiny85 blink with that voltage. I plan to power the RC with a 3.6V CR2 lithum battery.

Here are more details of my development enviroment:

* Arduino IDE 1.05
* I'm using ATtiny cores from here
* I'm programming the ATtiny85 using an Arduino UNO R3 as ISP, without problems (it's working as I can make the ATtiny85 blink an LED).

And here's my code:

```
#include <VirtualWire.h>

#define VCC_PIN  A1
#define BTN_PIN  A2
#define LED_PIN  A3
#define TXD_PIN  PB1

#define BLINK_UP_TIME  25

#define BUTTON_NONE  0
#define BUTTON_1     1
#define BUTTON_2     2
#define BUTTON_3     3
#define BUTTON_4     4
#define BUTTON_5     5
#define BUTTON_6     6

void setup()
{
  pinMode(BTN_PIN, INPUT);
  pinMode(TXD_PIN, OUTPUT);
  pinMode(VCC_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);

  // leave RF transmitter off for now
  digitalWrite(VCC_PIN, LOW);

  // Initialise the IO and ISR
  vw_set_tx_pin(TXD_PIN);
  vw_setup(2000);    // Bits per sec

  // let the user know we are alive: heartbeat
  blink(3, 50);
  delay(1000);
}

uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;

void loop()
{
  byte button = ReadButtons();
  if (button != BUTTON_NONE) {
    // transmit button pressed
    digitalWrite(LED_PIN, HIGH); // Flash a light to show transmitting
    digitalWrite(VCC_PIN, HIGH); // turn tranmitter on
    delay(10);
    buf[0] = button;
    vw_send(buf, 1);
    vw_wait_tx(); // Wait until the whole message is gone
    digitalWrite(LED_PIN, LOW); // turn off LED
    digitalWrite(VCC_PIN, LOW); // turn tranmitter off
  }
  delay(100);
}

byte ReadButtons()
{
  unsigned int buttonVoltage = analogRead(BTN_PIN);
  byte button = BUTTON_NONE;   // return no button pressed if the below checks don't write to btn
  if      (buttonVoltage < 10)   {    button = BUTTON_1; }
  else if (buttonVoltage < 200)  {    button = BUTTON_2; }
  else if (buttonVoltage < 400)  {    button = BUTTON_3; }
  else if (buttonVoltage < 550)  {    button = BUTTON_4; }
  else if (buttonVoltage < 720)  {    button = BUTTON_5; }
  else if (buttonVoltage < 900)  {    button = BUTTON_6; }
  else if (buttonVoltage > 1000) {    button = BUTTON_NONE; }
  return( button );
}

```

So, **What's wrong with my setup?**

# Answer
> 3 votes
I tried those Tiny cores you are using and had a lot of problems. I switched to http://code.google.com/p/arduino-tiny/ and it seems much better. Create a second Arduino installation folder and add the arduino-tiny cores. The pin name constants are like PIN\_A0, PIN\_A1,...,PIN\_B1, etc. So, try that out.

I looked briefly at the VirtualWire code and there are ifdefs specifically for the Attiny85, so it should work. Here is a derivative project with working ATTINY85 examples: http://cosa-arduino.blogspot.de/2013/03/news-virtual-wire-interface.html

# Answer
> 3 votes
Updated 26-08-2018: added tx(false); at the end of send. Without it, the TX pin could remain high, flooding the 433MHz band and making any other communication on it almost impossible!!!

Although these are all pretty old posts, I've still been struggling to get VirtualWire or its successor RadioHead working on an Attiny85. Typically the problem is that VirtualWire uses timer 0 and thereby breaks other stuff.

Now, for RX you typically don't want to spend all your processing cycles waiting for bits to come in, so you want it to be interrupt-driven, but for TX you can often do without that ... So, I did a bit of reverse-engineering of the VirtualWire TX code and implemented it as a simple send routine which can be used without needing a dedicated timer-interrupt. Using the code below on Attiny85 and an Arduino Uno as receiver with the normal VirtualWire library and the same baudrate, works just great for me, so if someone else can benefit from it, then here it is (including some code to read out an ultrasonic distance sensor and driving some leds - up to the reader to strip out what he doesn't need):

```
#include <util/crc16.h>

#define LED_PIN           3
#define LED2_PIN          4

#define TX_PIN            2
#define TX_BAUDRATE       2000
#define TX_MICROINTERVAL  (1000000UL/TX_BAUDRATE)
#define TX_MAXLEN         12

#define TRIGGER_PIN       0
#define ECHO_PIN          1

inline void led(const bool onOff) { digitalWrite(LED_PIN, onOff ? HIGH : LOW); }
inline void led2(const bool onOff) { digitalWrite(LED2_PIN, onOff ? HIGH : LOW); }
inline void tx(const bool onOff) { digitalWrite(TX_PIN, onOff ? HIGH : LOW); }
inline void trigger(const bool onOff) { digitalWrite(TRIGGER_PIN, onOff ? HIGH : LOW); }

const uint8_t header[8] = { 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, 0x38, 0x2C };
const uint8_t conv4to6[16] = { 0x0D, 0x0E, 0x13, 0x15, 0x16, 0x19, 0x1A, 0x1C,
                               0x23, 0x25, 0x26, 0x29, 0x2A, 0x2C, 0x32, 0x34 };

void rawSend(const uint8_t * p, uint8_t len) {
  while (len--) {
    const uint8_t val = *p++;
    for (uint8_t mask = 1; mask != 0x40; mask <<= 1) {
      tx(val & mask);
      delayMicroseconds(TX_MICROINTERVAL);
    }
  }
}

void send(const uint8_t * buf, const uint8_t len) {
  //  First create the payload ...
  static uint8_t payload[(TX_MAXLEN+3)*2];
  uint8_t * p = payload;
  uint16_t crc = 0xFFFF;
  uint8_t v = len + 3;
  crc = _crc_ccitt_update(crc, v);
  *p++ = conv4to6[v >> 4];
  *p++ = conv4to6[v & 0x0F];
  for (uint8_t l = len; l--;) {
    v = *buf++;
    crc = _crc_ccitt_update(crc, v);
    *p++ = conv4to6[v >> 4];
    *p++ = conv4to6[v & 0x0F];
  }
  crc = ~crc;
  v = (uint8_t)crc;
  *p++ = conv4to6[v >> 4];
  *p++ = conv4to6[v & 0x0F];
  v = (uint8_t)(crc >> 8);
  *p++ = conv4to6[v >> 4];
  *p++ = conv4to6[v & 0x0F];

  //  Now transmit the header and the payload ...
  rawSend(header, sizeof(header));
  rawSend(payload, (len + 3)*2);
  tx(false);
}

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(LED2_PIN, OUTPUT);
  led(false);
  led2(false);

  pinMode(TX_PIN, OUTPUT);
  tx(false);

  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  trigger(false);
}

int measure() {
  trigger(false); delay(10); trigger(true); delay(10); trigger(false);

  //  We support up to 6m, i.e. 6000mm, so that would take
  //  6000mm * 2 / 0.34mm/ms = 35294ms to get to the end
  //  and back, hence let's use a timeout along those
  //  lines ...
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 36000);
  if (!duration || (duration > 35500)) return 0;
  return (int)(duration * 34 / 200);
}

int bufferedMeasure() {
  static int lastVal = 0;
  static bool toggle = true;
  int newVal = measure();
  if (newVal) {
    led2(toggle);
    toggle = !toggle;
    lastVal += (newVal-lastVal)/10;
  }
  return lastVal;
}

// the loop routine runs over and over again forever:
void loop() {
    //  Measure the distance ...
    int val = bufferedMeasure();
    if (val) {
      static unsigned long data;
      led(true);
      data = 0xD1570000UL|val;
      send((const uint8_t *)&data, sizeof(data));
      led(false);
    } else {
      led(true); delay(100); led(false); delay(100);
      led(true); delay(100); led(false); delay(100);
      led(true); delay(100); led(false);
    }
    delay(1000);
}

```

# Answer
> 1 votes
Try the manchester library instead. This post includes all the necessary info except wiring diagrams: Manchester Library Won't Compile for Attiny85

# Answer
> 1 votes
I spent some time getting VirtualWire to work on attiny84. I see two issues with your code:

1. Since the tiny85 only has one timer, that one is being used by both VirtualWire and `millis`/`micros`. So your delays won't work as expected.
2. VirtualWire uses default values for vw\_ptt\_pin (10) and vw\_rx\_pin (11). Those pins don't exist on the attiny85. When `vwsetup` calls `pinMode` with these values, it causes writes to arbitrary memory addresses. This is likely to make your sketch behave unpredictably. To fix set `vw_set_ptt_pin()` and `vw_set_rx_pin()` to pins that exist on the tiny85 or modify the VirtualWire source.

---
Tags: remote-control, attiny, virtualwire, rf
---


# Question
Title: How should you predict the battery size required for a project?
I am using an Arduino nano along with an ESP8266. The nano is connected to an OLED display and a keypad. The ESP8266 uploads the data entered from the keypad onto a server. I wish to make the device portable; i.e. add a battery to it so that it can last for at least 8 hours.

How can I calculate the rating for the LiPo battery to use? I understand that it is very important to know the current rating of the devices in use.

How can I make an approximate guess?

# Answer
Yes, you need to know the average current draw over the period of an hour (or over a period that you then extrapolate to an hour). That is the *mAh* (milliamps per hour) that your circuit draws.

It can be hard to calculate the actual current, though, since it is always changing depending on what is actually happening in your system at the time. So I would suggest picking up a cheap current monitoring USB dongle from eBay / Amazon / Wherever (one with an LCD screen that gives mAh, such as this one and use that to get the total mAh of your system over an hour.

Multiply that mAh by 8 (the number of hours you want it to run for), and that will give you the minimum mAh for your battery. And then add some more as a safety margin, since the capacity of a battery is subject to many things (like temperature, age, etc), and the rated value is only a rough guide.

For instance, if you find your circuit uses on average 387mAh, then a battery of 3600mAh should be adequate.
> 2 votes

# Answer
Current consumption is measured in Amperes, battery capacity in specified in Amperes per hour.
> 0 votes

---
Tags: esp8266, arduino-nano, power, nodemcu, battery
---


# Question
Title: Why is there no embedded c code in arduino libraries?
When I took a look at how the arduino libraries were coded I expected to see register names like I/O registers(PINx,DDRx,PORTx) and other such registers with values assigned to them but instead I saw normal C code with functions and a class.

Why isn't there any embedded C in the structure of the library? Am I misunderstanding something very basic? Please help me understand.

# Answer
If you take a look at the Arduino core library (e.g., the AVR version of wiring.c), you will see lots of low-level register access. That's why the core code is specific to a processor architecture.

Other libraries are built on top of the core API in order to be portable.
> 1 votes

# Answer
Because the Arduino API abstracts those things.

If you put that kind of low-level code into a library the library becomes non-portable. By sticking to the Arduino API (digitalWrite, pinMode, etc) the library can be used on all boards.
> 0 votes

---
Tags: library, c
---


# Question
Title: setting output analog/digital pin to ground
So I need to automaically eject a CD from a Blu-Ray drive, I have a wire welded on the drive's card that if manually connected for a split second (pulse) to the ground of that same card on the drive, will eject the CD. Now in order to do that automatically I'm using an Arduino Nano and I connected that wire to an analog pin "d1" set its mode to Output and connected the grounds of both Arduino and drive together. Here's my code

```
int ds1 = A2; //pin that indicates the existence of the CD inside the drive if HIGH and its inexistance otherwise
int d1 = A3;  //pin connected to the wire that if connected to ground ejects the CD

void setup() {
  Serial.begin(9600);
  pinMode(ds1, INPUT);
  pinMode(d1, OUTPUT);
  while((!analogRead(ds1))) //if the CD isn't inside the drive wait
  {}
}

void loop() {
  analogWrite(d1,0); //eject CD
  delay(500);
  while(!analogRead(ds1)) //if the CD isn't inside the drive wait
  {}
  delay(1000);
}

```

I'm thinking that maybe setting the pin to 0 doesn't necessarily mean I connected it to the gnd, it's just a possibility if you see anything wrong with the code or have any suggestion please help me

# Answer
> 1 votes
Yes, setting a pin to OUTPUT and setting it LOW effectively connects the pin to ground (via a few ohms of resistance).

There's a couple of things wrong with your code, though, which you should address:

* Use digitalWrite() not analogWrite().

analogWrite(pin, 0) is effectively the same as digitalWrite(pin, 0), but it's ambiguous to someone reading your code.

* You never "release" the pin, so once it goes LOW it stays LOW. You should emulate *open drain* by setting it to INPUT when not using it.
* You should get into the habit of putting repeated code into functions to make it more understandable what's going on.

For example:

```
void setup() {
  Serial.begin(9600);
  pinMode(ds1, INPUT);
  pinMode(d1, INPUT);
  waitForCD();
}

void loop() {
  triggerEject();
  waitForCD();
  delay(1000);
}

void triggerEject() {
  pinMode(d1, OUTPUT);
  digitalWrite(d1, LOW); // Press the button
  delay(100); // This is how long the button is pressed for
  pinMode(d1, INPUT); // Release the button
}

void waitForCD() {
  while(!analogRead(ds1)) //if the CD isn't inside the drive wait
  {}
}

```
* `!analogRead(ds1)` will only ever be true if the voltage at pin A2 is exactly zero volts. If you really want to read an analog voltage here you should find a threshold value that the value is compared to:

while (analogRead(ds1) \< 100)) {}

Or it may be that you actually want to use `digitalRead()`...

---
Tags: arduino-nano, analogwrite, digitalwrite
---


# Question
Title: ssPin, resetPin, updatePin, ps0, ps1, osk - was not declared in this scope
The code below produces the error:

> ssPin was not declared in this scope

This error is repeated for all elements of DDS, i.e. `ssPin`, `resetPin`, `updatePin`, `ps0`, `ps1` and `osk`

Can anyone spot the problem?

```
#include <SPI.h>
#include <AD9954.h>
AD9954 DDS(ssPin, resetPin, updatePin, ps0, ps1, osk);

void setup() {
SPI.begin();
SPI.setClockDivider(4);
SPI.setDataMode(SPI_MODE0);
delay(500); // let things get set up...

DDS.initialize(400000000); // initialize DDS with 400 MHz clock

}

void loop() {

 DDS.setFreq(25000000); // set DDS to 25 MHz
  delay(2000);

}

```

# Answer
> 0 votes
The line:

```
AD9954 DDS(ssPin, resetPin, updatePin, ps0, ps1, osk);

```

does not have any content above it which declares that those variables exist. You can declare them like

```
const uint8_t ssPin, resetPin, updatePin, ps0, ps1, osk;

```

You'll likely also want to assign values to them, corresponding to the pins being used:

```
const uint8_t ssPin=4, resetPin=5, updatePin=6, ps0=7, ps1=8, osk=9;

```

(the actual values should be the pin numbers being used in your particular case.)

The file `AD9954.h` declares these variable names as private inside the class. They aren't available for use outside the class. The call to `DDS(...)` is the constructor, where you pass in pin definitions, and the values get assigned to those variables inside the class. But you can pass in literals or other variables in the constructor. You could even declare the same variable names in your main source file, but you can't ever directly access private variables from outside the class.

---
Tags: arduino-due
---


# Question
Title: Atmel studio 7 vs Arduino IDE for register level coding?
Which one is better to get started with register level embedded c coding? Also which one is used professionally?

# Answer
> 2 votes
I actually wouldn’t recommend either for professionally developing for Atmel chips. Although Atmel Studio is a nice enough IDE (the simulator is amazing!), it does make it *very* difficult to unit test your code or to set up a build server. I would personally recommend you set up a Make (or possibly CMake) based setup directly on top of the `avr-gcc` tool chain and then simply use the text editor of your choice.

As for learning about programming against raw registers, I have to recommend Atmel Studio and one of their XPlained evaluation boards. Atmel Studio includes a simulator that actually shows you, bit by bit, the current state of the registers.

# Answer
> 1 votes
Atmel Studio for professional. Arduino is for fun and is normally the first step into embedded c programming using the atmega328 (Arduino)

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


# Question
Title: OLED display crashes when connecting USB
I got an 16x2 OLED Display (DEP 16201-Y , compatible to the HD44780 controller) for my Arduino Uno and I got it to work in 4-bit Mode, but just if the USB isn't connected and it is powered by a 9V power supply.

So my routine is:

* Connect USB and power supply
* Upload Code
* --\> Doesn't work
* Disconnect USB and power supply
* Just connect power supply
* --\> Works
* Connect USB
* --\> Display crashes

So basically: If the arduino is connected via USB to my PC, with or without an additional power supply, the display won't work properly, it will crash or the Arduino even restarts itself. (some kind of memory error?)

I have no possible explanation for this..

Thanks for your help.

**EDIT:** I'm running Ubuntu Mate Kernel 4.4.0-43-generic 64bit

If I plug in the cabel without power, display works fine. If I plug in the cabel with 5V, but the PC is shut down, the display works fine. For the display to crash, the pc has to be running.

Test code:

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);

void setup()
{
    //lcd.clear();
    lcd.begin(16, 2);
    lcd.clear();
    lcd.setCursor(0,1);
    lcd.print("Hello there");
    delay(1000);
}

void loop()
{
    lcd.setCursor(0,1);
    lcd.print("Hello World");

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

    delay(1800);

    lcd.clear();

}

```

# Answer
When your computer boots, or when you plug the board in with it booted, most likely the serial port that gets created (/dev/ttyACM0) is opened by the process `modem-manager`. That will cause the Arduino to reset giving you the same results you see when you reset the board in other ways.

I have had no end of trouble in the same manner with a green version of the same screen. The best results I have had is to control the power to the display and power it up at every boot. You can do it with a simple P-channel logic level MOSFET or PNP transistor:

simulate this circuit – Schematic created using CircuitLab

If you chose, say, D3 (as an example) as your control GPIO you would go:

```
void setup() {
    pinMode(3, OUTPUT);
    digitalWrite(3, LOW);
    delay(1000); // Give it time to settle after powering up
    ... rest of setup code ...
}

```

You can also then use it to save power (if you want to) by turning the display off - simply set the pin back to INPUT and it will be turned off by R1.
> 2 votes

# Answer
I had the same problem but solved it with with the following code:
The `noDisplay(); display();` seems to reset the screen to the correct position.

```
void LCDInit()
{
  lcd.begin(DISPLAY_LINE_LENGHT, DISPLAY_LINES);
  // We need to do  this to reset the OLED display
  lcd.noDisplay();
  lcd.display();
  lcd.clear();
}

```
> 0 votes

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


title: Push button control of multiple relays

text:
# Question
Title: Push button control of multiple relays
I'm new to arduinos and have not been able to find/create a working bit of code for my project. I'd like to control several different relays (standard 5v optical relays) with push buttons. I want one pushbutton1 to turn on/off relay1, pushbutton2 to turn on/off relay 2, etc.

I ran into troubles using delay statements as debouncers because I guess it locked out the remainder of the code while it ran? I then tried to use a flagging approach covered here:

https://github.com/VRomanov89/EEEnthusiast/blob/master/03.%20Arduino%20Tutorials/01.%20Advanced%20Button%20Control/ButtonSketch/ButtonSketch.ino

```
const int numOfInputs = 2;
const int inputPins[numOfInputs] = {2,3};
const int outputPin = 10;

int LEDState = 0;
int inputState[numOfInputs];
int lastInputState[numOfInputs] = {LOW,LOW};
bool inputFlags[numOfInputs] = {LOW,LOW};
int inputCounters[numOfInputs];

long lastDebounceTime[numOfInputs] = {0,0};
long debounceDelay = 50;

void setup() {
  for(int i = 0; i < numOfInputs; i++) {
    pinMode(inputPins[i], INPUT);
    digitalWrite(inputPins[i], HIGH); // pull-up 20k
  }
  Serial.begin(9600);
  pinMode(outputPin, OUTPUT);
}

void loop() {
  setInputFlags();
  resolveInputFlags();
  resolveOutputs();
}

void setInputFlags() {
  for(int i = 0; i < numOfInputs; i++) {
    int reading = digitalRead(inputPins[i]);
    if (reading != lastInputState[i]) {
      lastDebounceTime[i] = millis();
    }
    if ((millis() - lastDebounceTime[i]) > debounceDelay) {
      if (reading != inputState[i]) {
        inputState[i] = reading;
        if (inputState[i] == HIGH) {
          inputFlags[i] = HIGH;
        }
      }
    }
    lastInputState[i] = reading;
  }
}

void resolveInputFlags() {
  for(int i = 0; i < numOfInputs; i++) {
    if(inputFlags[i] == HIGH) {
      // Input Toggle Logic
      inputCounters[i]++;
      updateLEDState(i);
      printString(i);
      inputFlags[i] = LOW;
    }
  }
}

void printString(int output) {
      Serial.print("Input ");
      Serial.print(output);
      Serial.print(" was pressed ");
      Serial.print(inputCounters[output]);
      Serial.println(" times.");
}

void updateLEDState(int input) {
  // input 0 = State 0 and 1
  if(input == 0) {
    if(LEDState == 0) {
      LEDState = 1;
    }else{
      LEDState = 0;
    }
  // input 1 = State 2 to 6
  }else if(input == 1) { // 2,3,4,5,6,2,3,4,5,6,2,
    if(LEDState == 0 || LEDState == 1 || LEDState > 5) {
      LEDState = 2;
    }else{
      LEDState++;
    }
  }
}

void resolveOutputs() {
  switch (LEDState) {
    case 0:
      digitalWrite(outputPin, LOW);
      break;
    case 1:
      digitalWrite(outputPin, HIGH);
      break;
    case 2:
      analogWrite(outputPin, 30);
      break;
    case 3:
      analogWrite(outputPin, 70);
      break;
    case 4:
      analogWrite(outputPin, 100);
      break;
    case 5:
      analogWrite(outputPin, 155);
      break;
    case 6:
      analogWrite(outputPin, 255);
      break;
    default:
    break;
  }
}

```

But was unable to alter the code to get it to work... could someone help me write a bit of code which will allow me to do what I want it to do? I'd rather not buy a matrix-style shield to accomplish this, but I will if I have to.

What I want to do:

* Turn on relay1 by pressing momentary pushbutton1
* Turn off relay1 by pressing momentary pushbutton1
* Turn on relay2 by pressing momentary pushbutton2
* Turn off relay2 by pressing momentary pushbutton2
* etc.
* etc.

Thank you in advance!

# Answer
To use this sketch, you will need the Bounce2 Library, and two N.O. switches connected between GND and the Arduino Digital Pins specified. I'm not sure if there is a limit to the number of Bounce2 objects you can create. Have a look at the Bounce2.h and Bounce2.cpp files.

```
#include <Bounce2.h>
byte buttonOneState = 0;
byte buttonTwoState = 0;
const byte buttonPin1 = 4;
const byte buttonPin2 = 5;
const byte debouncerInterval = 50;

// Instantiate ONE OR MORE Bounce2 object(s).
Bounce debouncer = Bounce();
Bounce debouncer2 = Bounce();

void setup(){
  Serial.begin(9600);
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  debouncer.attach(buttonPin1);
  debouncer.interval(debouncerInterval);
  debouncer2.attach(buttonPin2);
  debouncer2.interval(debouncerInterval);
}

void loop(){

  // Button 1
  if(debouncer.update()){
    if(debouncer.read() == 0){
      if(buttonOneState == 0){
        Serial.println("Turn Relay 1 ON");
        buttonOneState = 1;
      }
      else{
        Serial.println("Turn Relay 1 OFF");
        buttonOneState = 0;
      }
    }
  }

  // Button 2
  if(debouncer2.update()){
    if(debouncer2.read() == 0){
      if(buttonTwoState == 0){
        Serial.println("Turn Relay 2 ON");
        buttonTwoState = 1;
      }
      else{
        Serial.println("Turn Relay 2 OFF");
        buttonTwoState = 0;
      }
    }
  }

}

```
> 0 votes

# Answer
You can use this Button library from JChristensen (in GitHub)

You only need to read the brieve (altough usefull) documentation and you can control, no only the state of many buttons, you also can read the time that the buttons are pressed.

Hope you can solve your little problem :D

TIP: Try with 50ms of delay when you instantiate the *button object*
> 0 votes

# Answer
Here is the final solution I've implemented:

```
/*  Thanks to VE7JRO for giving me this solution to my problem.
 *  Thread found at https://arduino.stackexchange.com/questions/55540/push- button-control-of-multiple-relays
 */

#include <Bounce2.h>
byte buttonOneState = 0;
byte buttonTwoState = 0;
byte buttonThreeState = 0;
byte buttonFourState = 0;
const byte buttonPin1 = 2;
const byte buttonPin2 = 3;
const byte buttonPin3 = 4;
const byte buttonPin4 = 5;
const byte relayPin1 = 9; //Relay pin 1
const byte relayPin2 = 10; //Relay pin 2
const byte relayPin3 = 11; //Relay pin 3
const byte relayPin4 = 12; //Relay pin 4
const byte debouncerInterval = 50;

// Instantiate ONE OR MORE Bounce2 object(s).
Bounce debouncer = Bounce();
Bounce debouncer2 = Bounce();
Bounce debouncer3 = Bounce();
Bounce debouncer4 = Bounce();

void setup(){
  Serial.begin(9600);
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  pinMode(buttonPin3, INPUT_PULLUP);
  pinMode(buttonPin4, INPUT_PULLUP);
  debouncer.attach(buttonPin1);
  debouncer.interval(debouncerInterval);
  debouncer2.attach(buttonPin2);
  debouncer2.interval(debouncerInterval);
  debouncer3.attach(buttonPin3);
  debouncer3.interval(debouncerInterval);
  debouncer4.attach(buttonPin4);
  debouncer4.interval(debouncerInterval);
  pinMode(relayPin1, OUTPUT); //Define pin as output
  pinMode(relayPin2, OUTPUT); //Define pin as output
  pinMode(relayPin3, OUTPUT); //Define pin as output
  pinMode(relayPin4, OUTPUT); //Define pin as output
}

void loop(){

  // Button 1
  if(debouncer.update()){
    if(debouncer.read() == 0){
      if(buttonOneState == 0){
        Serial.println("Turn Relay 1 ON");
        digitalWrite(relayPin1, HIGH);
        buttonOneState = 1;
      }
      else{
        Serial.println("Turn Relay 1 OFF");
        digitalWrite(relayPin1, LOW);
        buttonOneState = 0;
      }
    }
  }

  // Button 2
  if(debouncer2.update()){
    if(debouncer2.read() == 0){
      if(buttonTwoState == 0){
        Serial.println("Turn Relay 2 ON");
        digitalWrite(relayPin2, HIGH);
        buttonTwoState = 1;
      }
      else{
        Serial.println("Turn Relay 2 OFF");
        digitalWrite(relayPin2, LOW);
        buttonTwoState = 0;
      }
    }
  }

  // Button 3
  if(debouncer3.update()){
    if(debouncer3.read() == 0){
      if(buttonThreeState == 0){
        Serial.println("Turn Relay 3 ON");
        digitalWrite(relayPin3, HIGH);
        buttonThreeState = 1;
      }
      else{
        Serial.println("Turn Relay 3 OFF");
        digitalWrite(relayPin3, LOW);
        buttonThreeState = 0;
      }
    }
  }
  // Button 4
  if(debouncer4.update()){
    if(debouncer4.read() == 0){
      if(buttonFourState == 0){
        Serial.println("Turn Relay 4 ON");
        digitalWrite(relayPin4, HIGH);
        buttonFourState = 1;
      }
      else{
        Serial.println("Turn Relay 4 OFF");
        digitalWrite(relayPin4, LOW);
        buttonFourState = 0;
      }
    }
  }

}

```
> 0 votes

---
Tags: button, relay
---


title: "'Serial' does not name a type" error

text:
# Question
Title: "'Serial' does not name a type" error
I'm getting a `"'Serial' does not name a type"` error when this program is compiled. I need for the 8 channels of voltage to be displayed. I'm sure it's a simple fix, however I'm still learning Arduino programming. I thank you for your help.

```
int pin_Out_S0 = 8;
int pin_Out_S1 = 9;
int pin_Out_S2 = 10;
int pin_In_Mux1 = A0;
int Mux1_State[8] = {0};
//float Mux1_State[i] =0;
int RawValue=0;
float Voltage = 0;
void setup() {
  pinMode(pin_Out_S0, OUTPUT);
  pinMode(pin_Out_S1, OUTPUT);
  pinMode(pin_Out_S2, OUTPUT);
  pinMode(pin_In_Mux1, INPUT);
  Serial.begin(9600);
}

void loop() {
 RawValue = analogRead(pin_In_Mux1);
 Voltage = (RawValue * 5.0) / 1024; //scale the ADC
  updateMux1();
  //Serial.println(Mux1_State);
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
      //vout = (value * 5.0) / 1024.0;
    }
  }
}

void updateMux1 () {
  for (int i = 0; i < 8; i++){
    digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
    digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
    digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
    Mux1_State[i] = analogRead(pin_In_Mux1);
  }
}
Serial.print("Raw  Value = " );
Serial.print(RawValue);

```

# Answer
Your last two lines are not in any function. This confuses the compiler. You need to move those two statements inside a function.

Because those statements refer to `RawValue`, I'm guessing you want to put them in `loop()`, where RawValue is being updated.

Also, remember that the IDE will tell you on which line the error is, which is helpful when debugging compilation errors.
> 10 votes

# Answer
Please put these lines inside the loop() function block:

```
Serial.print("Raw  Value = " );
Serial.print(RawValue);

```

Should look something like:

```
void loop() {
 RawValue = analogRead(pin_In_Mux1);
 Voltage = (RawValue * 5.0) / 1024; //scale the ADC
  updateMux1();
  //Serial.println(Mux1_State);
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
      //vout = (value * 5.0) / 1024.0;
    }
  }
  Serial.print("Raw  Value = " );
  Serial.print(RawValue);
}

```

That should at least remove the first issue with your code.

Cheers!
> 1 votes

# Answer
In addition to the good answers by Mikael and Uint, everything needs to be inside {curly braces} otherwise the IDE does not know where it belongs. If you didn't want the last 2 lines in your loop segment you could put them in a separate `void xxxx ()` section to be called when the time is right (by using an ISR with an `enableinterrupt` function for example).
> 1 votes

---
Tags: serial, programming
---


title: Shutdown the LED of my GY-85 sensor

text:
# Question
Title: Shutdown the LED of my GY-85 sensor
I would like to shutdown the LED of my GY-85 (gyroscope) component. Is it possible?

# Answer
According to this schematic, no. The LED is connected directly to power.

You will need to physically remove the LED to turn it off.
> 3 votes

---
Tags: gyroscope
---


# Question
Title: "not declared in this scope" error message
Error message `'dir1PinL' was not declared in this scope.` keeps coming up. Any ideas?

```
#include "Arduino.h"

/*motor control*/
void go_Advance(void)  //Forward
{
  digitalWrite(dir1PinL, HIGH);
  digitalWrite(dir2PinL, LOW);
  digitalWrite(dir1PinR, HIGH);
  digitalWrite(dir2PinR, LOW);
}

void go_Left(void)  //Turn left
{
  digitalWrite(dir1PinL, HIGH);
  digitalWrite(dir2PinL, LOW);
  digitalWrite(dir1PinR, LOW);
  digitalWrite(dir2PinR, HIGH);
}

void go_Right(void)  //Turn right
{
  digitalWrite(dir1PinL, LOW);
  digitalWrite(dir2PinL, HIGH);
  digitalWrite(dir1PinR, HIGH);
  digitalWrite(dir2PinR, LOW);
}

void go_Back(void)  //Reverse
{
  digitalWrite(dir1PinL, LOW);
  digitalWrite(dir2PinL, HIGH);
  digitalWrite(dir1PinR, LOW);
  digitalWrite(dir2PinR, HIGH);
}

void stop_Stop()    //Stop
{
  digitalWrite(dir1PinL, LOW);
  digitalWrite(dir2PinL, LOW);
  digitalWrite(dir1PinR, LOW);
  digitalWrite(dir2PinR, LOW);
}

/*set motor speed */
void set_Motorspeed(int speed_L, int speed_R)
{
  analogWrite(speedPinL, speed_L);
  analogWrite(speedPinR, speed_R);
}

//Pins initialize
void init_GPIO()
{
  pinMode(dir1PinL, OUTPUT);
  pinMode(dir2PinL, OUTPUT);
  pinMode(speedPinL, OUTPUT);

  pinMode(dir1PinR, OUTPUT);
  pinMode(dir2PinR, OUTPUT);
  pinMode(speedPinR, OUTPUT);
  stop_Stop();
}

void setup()
{
  init_GPIO();
  go_Advance();//Forward
  set_Motorspeed(255, 255);
  delay(5000);

  go_Back();//Reverse
  set_Motorspeed(255, 255);
  delay(5000);

  go_Left();//Turn left
  set_Motorspeed(255, 255);
  delay(5000);

  go_Right();//Turn right
  set_Motorspeed(255, 255);
  delay(5000);

  stop_Stop();//Stop
}

void loop()
{
}

```

This is the entire error message:

```
Arduino: 1.8.6 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Advance()':

smartcar-lesson1:20:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, HIGH);

                ^

smartcar-lesson1:21:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,LOW);

                ^

smartcar-lesson1:22:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,HIGH);

                ^

smartcar-lesson1:23:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,LOW);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Left()':

smartcar-lesson1:27:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, HIGH);

                ^

smartcar-lesson1:28:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,LOW);

                ^

smartcar-lesson1:29:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,LOW);

                ^

smartcar-lesson1:30:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,HIGH);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Right()':

smartcar-lesson1:34:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, LOW);

                ^

smartcar-lesson1:35:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,HIGH);

                ^

smartcar-lesson1:36:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,HIGH);

                ^

smartcar-lesson1:37:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,LOW);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Back()':

smartcar-lesson1:41:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, LOW);

                ^

smartcar-lesson1:42:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,HIGH);

                ^

smartcar-lesson1:43:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,LOW);

                ^

smartcar-lesson1:44:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,HIGH);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void stop_Stop()':

smartcar-lesson1:48:16: error: 'dir1PinL' was not declared in this scope

   digitalWrite(dir1PinL, LOW);

                ^

smartcar-lesson1:49:16: error: 'dir2PinL' was not declared in this scope

   digitalWrite(dir2PinL,LOW);

                ^

smartcar-lesson1:50:16: error: 'dir1PinR' was not declared in this scope

   digitalWrite(dir1PinR,LOW);

                ^

smartcar-lesson1:51:16: error: 'dir2PinR' was not declared in this scope

   digitalWrite(dir2PinR,LOW);

                ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void set_Motorspeed(int, int)':

smartcar-lesson1:57:15: error: 'speedPinL' was not declared in this scope

   analogWrite(speedPinL,speed_L);

               ^

smartcar-lesson1:58:15: error: 'speedPinR' was not declared in this scope

   analogWrite(speedPinR,speed_R);

               ^

C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void init_GPIO()':

smartcar-lesson1:64:10: error: 'dir1PinL' was not declared in this scope

  pinMode(dir1PinL, OUTPUT);

          ^

smartcar-lesson1:65:10: error: 'dir2PinL' was not declared in this scope

  pinMode(dir2PinL, OUTPUT);

          ^

smartcar-lesson1:66:10: error: 'speedPinL' was not declared in this scope

  pinMode(speedPinL, OUTPUT);

          ^

smartcar-lesson1:68:10: error: 'dir1PinR' was not declared in this scope

  pinMode(dir1PinR, OUTPUT);

          ^

smartcar-lesson1:69:11: error: 'dir2PinR' was not declared in this scope

   pinMode(dir2PinR, OUTPUT);

           ^

smartcar-lesson1:70:11: error: 'speedPinR' was not declared in this scope

   pinMode(speedPinR, OUTPUT);

           ^

exit status 1
'dir1PinL' was not declared in this scope

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

# Answer
> 2 votes
It doesn't look like you've created any variable with that name in your code. That's what that error message usually means. You must create a variable and give it a value before you can use it elsewhere. Go find any good C++ tutorial and go through the first bit of it and you will learn these sorts of basics pretty quick.

Your code would need a line at the top that looks something like:

```
int dir1PinL = 2

```

or whatever number value you want that variable to have depending on what pin you're actually talking about there. Similar for the other variables you are trying to use.

---
Tags: arduino-uno
---


# Question
Title: ESP8266 12-E can't connect to any Access Point with converted variables from strings to char arrays
**I'm using an esp8266 12-E nodemcu** I wrote a code that scans the available WiFi networks, print them through serial communication,ask the user which network he wants to connect to and then the password for that network. The problem is that the nodemcu won't connect to that network. I think that the problem is when I convert the strings **buffer\_pw** and **buffer\_ssid** to the char arrays **password** and **ssid**. Why does it give problems to connect?

```
#include <ESP8266WiFi.h>

int num_ap; //number of access points
String buffer_ssid = "empty"; //temporary stores the ssid in here because then it has to be converted in a char array
String buffer_pw = "empty"; //temporary stores password and same thing as^^
bool askPW = false; //"Did I already ask the password?"
bool connesso = false; //"Did I already connect?"

void setup()
{
  Serial.begin(9600);
  WiFi.mode(WIFI_STA); //put the nodemcu in sta mode so that it can connect to access points
  WiFi.disconnect();   //it disconnects from any access point it was connected to
  Serial.println("Setup completo");
  num_ap = WiFi.scanNetworks(); //scans for access points
  if (num_ap == 0)   //if there aren't any access points available
  {
    Serial.println("Nessun Access Point rilevato");
  }
  else //if there are some access points available
  {
    Serial.println("Access Point rilevati:");
    delay(200);
    for (int i = 0; i < num_ap; i++)
    {
      Serial.println(" ");
      Serial.print(i + 1);
      Serial.print(") ");
      Serial.print(WiFi.SSID(i)); //print access point's ssid
      Serial.print(" ");
      Serial.print("(Potenza segnale: ");
      Serial.print(WiFi.RSSI(i)); //prints access point's rssi(strength of signal)
      Serial.print(")");
      delay(50);
    }
    delay(500);
    Serial.println(" ");
    Serial.println(" ");
    Serial.println("A quale Access Point ti vuoi connettere?");

  }
}

void loop()
{
  if (buffer_ssid == "empty") //if the variable has the standard value "empty" so if the user has already given an ssid. I need this to execute  this piece of code once
   {
    if (Serial.available() > 0)
     {
      buffer_ssid = Serial.readString();  //stores user input(the ssid) in buffer_ssid
      if (buffer_ssid != "empty") //if the variable isn't empty(if the code has successfully saved the ssid) prints the ssid
       {
        Serial.println(buffer_ssid);
       }
     }
   }

  if(buffer_ssid != "empty") //if the user has given an ssid
  {
   if(askPW == false) //if the code has asked the password(I need this in order to execute this piece of code once)
    {
     Serial.println("Inserire la password per connettersi all'Access Point, se non serve premere spazio e invio"); //"insert the password"
     askPW = true;
    }
    if (Serial.available() > 0)
    {
      buffer_pw = Serial.readString(); //saves user input(the password) in the variable buffer_pw
      if(buffer_pw != "empty") //if the code has successfully saved the password so it hasn't the standard value "empty"
      {
        Serial.println(buffer_pw);
      }
    }
  }

  if (buffer_pw != "empty" && buffer_ssid != "empty") //if buffer_ssid and buffer_pw aren't "empty", so if the user inserted them
  {
    if(connesso == false) //in order to execute this piece of code once
    {
     //converts the strings buffer_ssid and buffer_pw in char arrays(I have to do this because WiFi.begin() doesn't accept strings)
     char ssid[buffer_ssid.length()];
     buffer_ssid.toCharArray(ssid,buffer_ssid.length());
     char password[buffer_pw.length()];
     buffer_pw.toCharArray(password,buffer_pw.length());
     //start connecting
     Serial.println("Connessione in corso");
     Serial.println(ssid); //prints ssid
     Serial.println(password);//prints password so I know that they were converted succesffully
     WiFi.begin(ssid,password);//start connecting
     while(WiFi.status() != WL_CONNECTED) //while it's not connected
     {
      Serial.print(".");
      delay(500);
     }
      Serial.println("Connesso!"); //"Connected!"
      Serial.println("Il mio ip locale: ");
      Serial.print(WiFi.localIP()); //nodemcu's local IP

    }
    connesso = true;  //set connesso to true so that this piece of code doesn't loop
  }
}

```

# Answer
> 1 votes
Problem is that you set to `toCharArray` the length of the String. But the second parameter is the maximum allowed length of the output and there is then no space for the terminating zero and string is cut at last character.

The function toCharArray knows the size of the String. The second parameter should be the size of the char array `buffer_ssid.toCharArray(ssid, sizeof(ssid));`

And next problem could be that you copy the CR/LF characters from input into ssid and password. You can see it in debug printouts.

---
Tags: esp8266, c++, wifi, c, nodemcu
---


# Question
Title: How to connect Mg995 and arduino nano since nano can only output 40mA at max?
Datasheet for Mg995 shows:

```
Current draw at idle 10MA
No load operating current draw 170MA
Stall current draw 1200MA

```

Maximum current that an arduino nano can output is 40mA.
So, what intermediary component should I use to make the connection between the two work?

# Answer
The servo has 3 Pins to connect: Vcc, GND and PWM. The power, which actually drives the servo is drawn through the power lines Vcc and GND. The PWM pin, which is connected to an Arduino output pin, does not draw mich current. It is only for the PWM (-like pulsed) signal, which tells the servos driver, which angle is requested. But you should not power the servo through the Arduino. You have to connect it directly to a power supply with the correct voltage, because some parts of the Arduino can get fried, when drawing too much current through it.

So all in all: Connect the PWM pin directly to an Arduino output pin and supply the power from the source directly to the servo, not going through the Arduino.
> 1 votes

---
Tags: arduino-nano, servo, current
---


# Question
Title: Arduino Uno won't upload code and overheats
We are using an Arduino Uno R3 connected via USB to a computer. The main problem is that we can't upload any code to the board. We get this error in the Arduino IDE console:

> avrdude: ser\_open(): can't open device ".\COM1": The system cannot find the file specified Problem uploading to board. Visit http://www.arduino.cc/en/Guide/Troubleshooting#upload

My computer may not recognize the board, the IDE won't find any port (COM) and on the board I got the three LEDs turned on, they don't even blink, they stay turned on as long as I have connected the Arduino to the computer. Apart from that, the Arduino heats too much and too fast. I don't have anything connected to it yet. I've tried resetting the board with its built-in button, I've also tried changing the USB cable, even the computer, different system architecture and OS. I don't to want to mess up the board even more, so I don't know what to do. Could you point out what's the problem with my board?

If you need more information, I will try to post as much as you need to help me out.

# Answer
> 3 votes
The fact that it doesn't blink the LED when plugged in or reset indicates that the bootloader of the main microcontroller no longer works.
The fact that the computer no longer recognizes the board as a serial port means that the USB-to-Serial interface doesn't work.
The fact that it heats up tells you that at least one of the chips on the board is dead.

I'm afraid that you'll have to get yourself a new Arduino.

# Answer
> 0 votes
First of all (with unplugged Uno) visually (and maybe with help of some magnifying glass) check, that really there is nothing stuck there, what should not be (tin ball, pice or wire or such) and that all copper lines on PCB are OK (and not shorted or broken). Also check all chips, resistors etc. are visually clean, good soldered and undamaged. If something looks damaged or burned, the it is probably damaged and should be replaced anyway.

If you connect it (I suggest USB charger, to be sure to not damage computer) and the main chip (MCU) is hot, I think, that it is dead.

If some other chip is hot and MCU not so much, then maybe the MCU is not dead, but something else is broken. (probably the hot part, but maybe also some resistor/capacitor shortcuted)

The way it is now makes it is dead for you anyway, so there is not much to came worse.

I would try to connect it only to USB charger (to not damage expensive computer by bad luck) and measure voltage on various points of the board (from ground). There should be 5V straight at 5V pin, also on the same 5V on ISP head, one pin of USB connector and on all power pins on MCU and the other chip between it and USB (new R3 have some atmega there too).

Take schema for that and try to measure on the right places. Be carefull to not shortcut anything with your voltmeter rod (it is easy to connect two legs with it and it may damage something not damaged yet). You can try to check voltage anywhere safely, on some places there should be 0V, on some 5V, but in default setup (no program working yet) the i/o pins are INPUT on boot, so just High resisteance and no strong voltage on them (you should get probably weak 0V until there is some interference).

If you identify (or thing so) wrong part, you can try to replace it with new one - good training even if you botch it and you risc youst price of the new part. Even the MCU can be changed with good soldering pen and some effort. The schema is simple, but the legs are tiny and many of them.

As it is effectively dead for you now, the worse what can happen is, that you burn the new part too and throw it all away (as you would anyway). The best what can happen is that you repair it and it will work flawlessly.

I build some "arduinos" from the SMD chip and other parts on home made PCBs - all worked well. So If you want some entertainment and practise, it is not bad think to try.

If you do not want risc the price of new MCU, but want the practise, yout take away and thyen resolder the (already broken) MCU - it would not repair it, but you can see for yourself, if you think you are able do similar experiments and if you enjoy it.

---

I found, that some chineese cheap clones have voltage stabilisers, that can break on shortcut and then do anything (usually the output is then shortcuted to input, so the power goes full where only stabilised 5V should be, but also can shortcut to ground, burn to total resistance, or something random between)

It is usually not good idea have arduino connected to two powersources (like external power source for servos AND USB for programming it) at the same time, as there may be different voltage on both and big currents between in some cases. If you need more power for servos (or something) and USB for serial/programming, then better there should be no direct connection between the external source power and Arduino +5V/+3.3V or any pin - just common ground, everything other separated by at least transistor (base on pin, collector on external source) or so.

---
Tags: arduino-uno, serial, usb, rx-pin
---


title: NodeMCU minimum supply voltage)

text:
# Question
Title: NodeMCU minimum supply voltage)
I have read several articles an datasheets, but I couldn't find an affordable answer...

This is my problem: I need to power a NodeMCU (on Vin pin) with 3xAA batteries. Which is the minimum operating voltage at Vin accepted by NodeMCU? In other words, which voltage drop from 4.5 will let NodeMCU still working? thanks.

# Answer
> 2 votes
The NodeMCU uses the SPX3819 3.3v voltage regulator.

That regulator, according to the datasheet has a dropout of maximum 700mV, but much less at lower currents.

Taking the maximum, that means that you need to supply 3.3 + 0.7 = 4V to the board for the regulator to regulate properly. However, it is doubtful you will be using *that* much current, so probably nearer a 350mA dropout - which means 3.3 + 0.35 = 3.65V.

However, the ESP8266 itself will work down to 2.5V - so if you operate the board with the regulator out of regulation (not recommended, but it should work fine), you could probably go as low as 2.8 to 3V without problems.

---
Tags: nodemcu
---


# Question
Title: Trying to power 100 Arduino's from single power line
I'm trying to power up to 100 Arduinos that will be spread across a 25m wall using a single power line.

The idea is each Arduino will have a few a few buttons, leds & an oled screen and will all communicate to a master server using rs485.

```
====[A0]====[A1]====[A2]====[A3]====[A4]== ... ==[A99]

```

I've already followed this brilliant post http://www.gammon.com.au/forum/?id=11428 to implement the data connection using an rs485 bus.

However I'm struggling to understand how I could power multiple Arduino's from the one line and not introduce surges/ground loops from the difference in group potential caused by the long power line.

Would I have to isolate each Arduino and rs485 driver? Or is there a simpler solution?

# Answer
You are already using a differential signalling system that doesn't care about ground levels, so you don't need to worry about that side of things.

As for power distribution - a strategy known as *point of load regulation* is what you want. That is where you supply a higher voltage (but lower current) power feed to one, or in this scenario more likely a group of, boards and regulate that power down using a switching regulator to a lower voltage (5V) and higher current.

This has the advantage that:

* You are only worrying about small groups of Arduinos, not the whole lot
* You can use thinner wires to feed in the power to a group
* You get less losses from wire resistance at high currents

For 100 Ardunos you may want to have maybe 10 to a group with a 3A switching regulator for each group, giving an average of 300mA per board (depending on your current needs, of course - you may want less per group and more groups to give more average current per board).

In that example you'd have a total output current limit of 30A in 10 sections at 5V. That equates to (P=V×I) 150W. So a 200W 24V power supply would be adequate.

At 24V, 150W would demand 6.25A (plus some more to account for the efficiency of the regulators, so call it 8A - hence the desire for a 200W supply).

For 3A you need *at least* 24AWG wire - but preferably considerably thicker - maybe 18AWG. The 8A for the 24V would need minimum 15AWG, preferably bigger - although you don't need that size all the way to the end of your chain of regulators. If you had each regulator wired directly back to the power supply individually that would only need thin wires (absolute minimum 30AWG, which is tiny - though to keep losses to a minimum you'd want more like 20AWG).

So for simplicity and to reduce your wire costs, just stick to one size all the way through so you're buying only one gauge of wire (so you get a bigger discount for buying more). You could quite easily use:

* 18AWG direct from the PSU to each POL regulator (24V, 0.8A)
* 18AWG from each POL regulator to all Arduinos in a group (5V, 3A)

Of course, this is all using numbers plucked out of thin air, and you'd need to adjust it to fit your specific project, but you get the idea - higher voltage to a group, regulate to 5V, then 5V to each Arduino in the group. You don't need to care about grounding etc because you're using RS-485.
> 9 votes

---
Tags: power, rs485
---