# Question
Title: Dual power supply using Arduino uno and nano
I had a very vague thought. I was wondering if I could I create a dual power supply using an Arduino uno and a nano. Can the ground terminals of both the boards be shorted and the 5 volt terminals be used as +5v and -5v . Is this possible? Would it damage the board??

# Answer
No, because both 5V terminals are +5V.

If both boards are powered by completely isolated power supplies then you could connect the +5V of one to GND on the other. One will then have all its signals and logic negative to your ground level, but normal compared to its own ground level. Managing it though and keeping things separate (no shared ground between two sets of peripherals, etc), would be tricky. And the moment you plug one into your computer the whole lot could go up in smoke.
> 2 votes

---
Tags: arduino-uno, arduino-nano
---


title: Stop led from blinking when running

text:
# Question
Title: Stop led from blinking when running
I don't get it. I'm new to Arduino, but not to programming. I don't understand why led pin 13 keeps blinking.

here is my code..

```
#include <Servo.h>

// X servo angle will stay in [min_x, max_x] range
// Y servo angle will stay in [min_y, max_y] range
// to be adjusted to the size of your living room

float min_x = 5;
float max_x = 50;
float min_y = 5;
float max_y = 35;
int min_freeze = 200;
int max_freeze = 3000;
float minimal_movement = 5;

// finding center of square for starting point
int random_delay;
float x_position = min_x + (max_x - min_x)/2;
float y_position = min_y + (max_y - min_y)/2;
float x_old_position = x_position;
float y_old_position = y_position;
float x_new_position;
float y_new_position;
float x_speed;
float y_speed;
int movement_time;

// Instantiating two servos
Servo x_servo;
Servo y_servo;
int pos = 0;

void setup() {
  y_servo.attach(6);  // attaches the y servo on pin 6 to the servo object
  x_servo.attach(9);  // attaches the x servo on pin 9 to the servo object
  pinMode (13, OUTPUT);
  digitalWrite (13, HIGH);  // switch on  the laser

  //Place the servos in the center at the beginning
  y_servo.write(y_position);
  x_servo.write(x_position);

}

void loop() {
  movement_time = random(10,40);
  random_delay = random(min_freeze, max_freeze);
  x_new_position = random(min_x+minimal_movement, max_x-minimal_movement);
  y_new_position = random(min_y+minimal_movement, max_y-minimal_movement);

  if( (y_new_position > y_old_position) && (abs(y_new_position - y_old_position) < 5 )) {
    y_new_position = y_new_position + minimal_movement;
  }  else if ( (y_new_position < y_old_position) && (abs(y_new_position - y_old_position) < 5 )) {
    y_new_position = y_new_position - minimal_movement;
  }

  if( (x_new_position > x_old_position) && (abs(x_new_position - x_old_position) < 5 )) {
    x_new_position = x_new_position + minimal_movement;
  }  else if ( (x_new_position < x_old_position) && (abs(x_new_position - x_old_position) < 5 )) {
    x_new_position = x_new_position - minimal_movement;
  }

  x_speed = (x_new_position - x_old_position)/movement_time;
  y_speed = (y_new_position - y_old_position)/movement_time;
  for (pos = 0; pos < movement_time; pos += 1) {
      x_position = x_position + x_speed;
      y_position = y_position + y_speed;
      x_servo.write(x_position);
      y_servo.write(y_position);
    delay(10);
  }
  x_old_position = x_new_position;
  y_old_position = y_new_position;
  delay(random_delay);

}

```

Nowhere in this sketch, the line "digitalWrite (13, LOW);" is contained, yet I am unable to keep the LED on solid without blinking when the Arduino is looping. I've other people do it, with this code, I don't get what I'm missing!

Windows 7 64bit, Arduino Uno board, Arduino 1.8.9 program

# Answer
I tried your sketch on an Arduino Uno, with no servos connected, and the LED on pin 13 did not blink.

DataFiddler makes a good point in their comment. To be sure you are actually uploading the sketch, try uploading the `Blink` sketch that comes with the IDE. Change the delays from 1000ms to 200ms then upload it. The difference in flash rates should confirm or deny the ability to successful upload sketches.

You don't say which servos you are using, so I'll assume they are SG90. I'm not sure if the data sheet for every SG90 servo is the same, but if you look at this one, SG90 Specifications, you'll see the "stall current" can be between 570mA and 730mA, **each**. If you are powering them from the Uno, it can't supply that much current. Another limiting factor is the computer's USB maximum current output, (if you are powering the Uno with a USB port). FWIW, my computer can only provide 500mA per USB.

I would suggest powering the servos with a separate power supply, then see what happens.
> 3 votes

---
Tags: arduino-uno
---


title: RGB and Potentiometer

text:
# Question
Title: RGB and Potentiometer
How do I start this program???

```
int x=0;
int P1=A5;
int P2=A4;
int P3=A3;
int R1=3;
int G1=5;
int B1=6;
int R2=9;
int G2=10;
int B2=11;
int sValue1;
int sValue2;
int sValue3;
int oValue1;
int oValue2;
int oValue3;
int timer(1000);

void setup() {
 pinMode(P1,INPUT);
 pinMode(P2,INPUT);
 pinMode(P3,INPUT);
 pinMode(R1,OUTPUT);
 pinMode(G1,OUTPUT);
 pinMode(B1,OUTPUT);
 pinMode(R2,OUTPUT);
 pinMode(G2,OUTPUT);
 pinMode(B2,OUTPUT);

}

void loop() {

sValue1=analogRead(P1);
sValue2=analogRead(P2);
sValue3=analogRead(P3);

oValue1=map(sValue1,0,1023,0,255);
oValue2=map(sValue2,0,1023,0,255);
oValue3=map(sValue3,0,1023,0,255);

if ((sValue1=0)&&(sValue2=0)&&(sValue3=0));
{
  setColor1(0,255,255);
  delay(timer);
  setColor2(255,0,0);
}
}

void setColor1(int red1, int green1, int blue1){
  {
    analogWrite(R1,red1);
    analogWrite(G1,green1);
    analogWrite(B1,blue1);
  }
}

void setColor2(int red2, int green2, int blue2){
  {
    analogWrite(R2,red2);
    analogWrite(G2,green2);
    analogWrite(B2,blue2);

  }
}

```

# Answer
Arduino has created binary numbers: B1, B101, B00111, and so on.

It is documented in the reference page "Integer Constants".
The "B1" is defined in "binary.h".

They should not have done that. Not a single C++ software engineer thinks that it was a good addition. The C++ language is perfectly fine for creating binary values: 0b1, 0b101, 0b00111, and so on.

It is not your fault, you can blame Arduino. Because of this, you should **never** create variables with the name: B1, B101, B00111, and so on.
> 2 votes

# Answer
1. Install Arduino IDE
2. New sketch
3. Paste code
4. Connect the Arduino board to your PC
5. Upload sketch
> 0 votes

# Answer
> Also i get Error compiling from this program

Obviously B1 is already defined as something, like your A5, A4 and A3 are.
You will very likely have the same issue with B2.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Why Smart Plugs don't require setting port forwarding on router and how to accomplish this with NodeMCU (ESP8266)
I have a NodeMCU (ESP8266) board that I use to control some devices over the internet. To be able to access it I have to enable port forwarding on my router and set the port manually like in the image below:

But with Smart Plugs (that use a cloud based app) I don't have to set up anything on my router. I am only required to type my Wi-Fi password. So my question is how Smart Plugs are accessed over the router (why they don't need manual port forwarding setting), and how to apply this to my NodeMCU so I don't have to set port forwarding manually.

# Answer
> 7 votes
Port forwarding is required to allow a device outside your router to access a device inside a router that performs NAT (Network Address Translation).

When a NodeMCU is acting as a simple server to respond to requests, it is inside your network, and so the port-forwarding is required so that your phone or computer on the Outside can access it.

However, for the cloud-based "smart" devices, it is different. The smart device opens a connection from itself to a server (the cloud) outside your network. In this case, the router understands that a new two-way connection is created between the cloud server and your smart device.

The only communication to your smart device is from the cloud server to the smart device. If you have an app on your mobile device or computer, that app or website only accesses the cloud server, when then passes the instruction on to your smart device. Reverse direction for status info from the smart device to your app, etc.

These smart devices rely on the infrastructure of their creators to continue to work. There are no LAN-to-LAN connections from the client to the device. Everything goes through the Internet to the remote cloud server, and back.

Many home routers support a protocol called uPNP, that allows a device inside the network to request port forwarding to itself. Some routers require this to be explicitly enabled, because it's a security risk to allow any device to be able to open holes in your firewall/router.

To have your NodeMCU device do this, look for libraries for ESP8266 that implement uPNP. I did a quick search and found https://github.com/ofekp/TinyUPnP though I cannot vouch for it's effectiveness or safety.

---
Tags: nodemcu
---


title: Can a ESP8266 and a HC-SR04 be friends?

text:
# Question
Title: Can a ESP8266 and a HC-SR04 be friends?
I have some existing code that I've been using with an Uno and a HC-SR04. In order to make my project less expensive, I'm trying to port everything over to a ESP8266-01.

The last hang up I've been running into is that it appears that the ESP8266 doesn't support the pulseIn function.

```
duration = pulseIn(echoPin, HIGH);

```

Any idea on how I can change the pulseIn function with interrupts or something else?

Lastly I've done a lot of searching for using a HC-SR04 with a ESP8266 and while there are a couple examples out there, I haven't seen anyone do it with Arduino code...

# Answer
> 1 votes
`pulseIn()` is actually a very simple function. As long as there is a microseconds counter of some form available you can easily enough roll your own.

Also, I don't know which implementation of the ESP8266 plugin you are using, but the one I use has pulseIn available.

# Answer
> 0 votes
I had trouble with pulseIn() until the proper initializing code was put in setup().
As follows:
pinMode(TRIGGER, OUTPUT);
digitalWrite(TRIGGER, LOW);
delay(2);
pinMode(ECHO, INPUT);
TRIGGER and ECHO were initially defined at top of code with other variables as follows:
#define TRIGGER 13 // Data pin D7
#define ECHO 12 // Data pin D6
My HC-SR04 board was wired to D7 and D6, but D1 and D2 are often used.
Project was a 'Tide' reporting system. A work in progress. Also found HC-SR04 board was unstable if using 3.3vdc as VCC. Works better if the HC-SR04 board VCC is tide to Vin on the ESP8266 board.

---
Tags: sensors, arduino-ide, esp8266
---


# Question
Title: softwareserial between arduino uno and esp8266
I have an Arduino UNO and HUZZAH ESP8266 module. I need to send data between Arduino UNO and ESP module via Software Serial. Right now I have the ESP module write data and Arduino UNO display data, but not working. When I run the Arduino UNO and open its Serial Monitor, nothing is printed using below source code.

1. ESP8266 RX PIN connected to Arduino UNO PIN 2.
2. ESP8266 TX PIN connected to Arduino UNO PIN 3.
3. Using the FTDI cable that came with HUZZAH ESP8266 to power this module. I just individually connected the RX and TX pins to the ARDUINO PIN 2 and 3 as mentioned above.

Any ideas what why not working? Below is code for both modules. Thanks,

Arduino UNO

```
#include <SoftwareSerial.h>

SoftwareSerial ESPserial(2, 3); // RX | TX

void setup(void){
  //Start hardware Serial communication
  Serial.begin(115200);

  //Start the software serial for communication with the ESP8266 component
  ESPserial.begin(57600);

}

void loop(void){

if (ESPserial.available()){
  Serial.println("ESP available!!!");
  Serial.println(ESPserial.read());
}

}

```

HUZZAH ESP8266

```
#include <ESP8266WiFi.h>

#include <SoftwareSerial.h>

SoftwareSerial ESPserial(2, 3); // RX | TX

void setup(void){
  //Start the software serial for communication with the Arduino UNO component
  ESPserial.begin(57600);

  //TODO: setup Wifi
}

void loop(void){
   ESPserial.write("This message generated by ESP module.");
   delay(500);
}

```

# Answer
> 4 votes
Make sure that:

1. RX pin on the Arduino UNO is connected to the TX pin on the ESP8266.
2. TX pin on the Arduino UNO is connected to the RX pin on the ESP8266.
3. Baud rate should be set to the same value from both the Arduino and ESP8266.

I don't know about your arduino but looking at this schematic, your RX and TX should be swapped.

# Answer
> 2 votes
Adding to the above answer. UNO's TX is at 5V , while ESP8266 's RX is at 3.3V, as it is a 3.3V module. So its better to use a resistive divider to bring UNO' TX to 3.3V and then feed to ESP's RX, instead of directly connecting them eachother.

# Answer
> 0 votes
//ESP

```
#include "SoftwareSerial.h"

SoftwareSerial ArduinoUno(D2,D3); //Rx, Tx

void setup() {

Serial.begin(9600);

ArduinoUno.begin(4800);

pinMode(D2, INPUT);

pinMode(D3, OUTPUT);

}

void loop() {

}

/******************************************************************************/

```

//UNO

```
#include "SoftwareSerial.h"

SoftwareSerial ArduinoUno(3,2); //Rx, Tx

void setup() {

Serial.begin(9600);

ArduinoUno.begin(4800);

}

void loop() {

  if(ArduinoUno.available() > 0){

    //float val = ArduinoUno.parseFloat();

    Serial.println(ArduinoUno.read());

  }

  delay(30);

}

```

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


title: RGBs and Potentiometers

text:
# Question
Title: RGBs and Potentiometers
I think my if statement can't be read here in my program. The RGBs should light up and change color when the potentiometer is turned but instead the RGBs just light up immediately and change color simultaneously. How do I fix this?

```
int POT1=A0;
int POT2=A1;
int POT3=A2;
int Red1=9;
int Green1=10;
int Blue1=11;
int Red2=3;
int Green2=5;
int Blue2=6;
int sValue1=0;
int sValue2=0;
int sValue3=0;
int oValue1=0;
int oValue2=0;
int oValue3=0;
int value1=0;
int value2=0;
int value3=0;
int timer(250);

void setup() {
 Serial.begin(9600);
 pinMode(Red1,OUTPUT);
 pinMode(Green1,OUTPUT);
 pinMode(Blue1,OUTPUT);
 pinMode(Red2,OUTPUT);
 pinMode(Green2,OUTPUT);
 pinMode(Blue2,OUTPUT);

}

void loop() {

sValue1=analogRead(POT1);
sValue2=analogRead(POT2);
sValue3=analogRead(POT3);

oValue1=map(sValue1,0,1023,0,255);
oValue2=map(sValue2,0,1023,0,255);
oValue3=map(sValue3,0,1023,0,255);

if ((sValue1<=127)&&(sValue2<=127)&&(sValue3<=127));
{
  setColor1(0,255,255); //red
  setColor2(255,255,0); //blue
  delay(timer);
  value1=0;
  value2=0;
  value3=0;

}

if ((sValue1<=127)&&(sValue2<=127)&&(sValue3>127));
{
  setColor1(255,255,0); //blue
  delay(timer);
  setColor2(255,0,255); //green
  delay(timer);
  value1=0;
  value2=0;
  value3=1;
}

if ((sValue1<=127)&&(sValue2>127)&&(sValue3<=127));
{
  setColor1(255,0,255); //green
  delay(timer);
  setColor2(0,255,255); //red
  delay(timer);
  value1=0;
  value2=1;
  value3=0;
}

if ((sValue1<=127)&&(sValue2>127)&&(sValue3>127));
{
  setColor1(0,255,255); //red
  delay(timer);
  setColor2(255,0,255); //green
  delay(timer);
  value1=0;
  value2=1;
  value3=1;
}

Serial.print("POT 1=");
Serial.print(value1);
Serial.print("\t POT 2=");
Serial.print(value2);
Serial.print("\t POT 3=");
Serial.print(value3);

if ((value1==0)&&(value2==0)&&(value3==0))
{
 Serial.print("\t RGB1=");
 Serial.print("RED");
 Serial.print("\t RGB2=");
 Serial.print("BLUE");
}

else if ((value1==0)&&(value2==0)&&(value3==1))
{
  Serial.print("\t RGB1=");
  Serial.print("BLUE");
  Serial.print("\t RGB2=");
  Serial.println("GREEN");
  Serial.println(" ");
}

else if ((value1==0)&&(value2==1)&&(value3==0))
{
  Serial.print("\t RGB1=");
  Serial.print("GREEN");
  Serial.print("\t RGB2=");
  Serial.println("RED");
  Serial.println(" ");
}

else if ((value1==0)&&(value2==1)&&(value3==1))
{
  Serial.print("\t RGB1=");
  Serial.print("RED");
  Serial.print("\t RGB2=");
  Serial.println("GREEN");
  Serial.println(" ");
}

}

void setColor1(int red1, int green1, int blue1){
  {
    analogWrite(Red1,red1);
    analogWrite(Green1,green1);
    analogWrite(Blue1,blue1);
  }
}

void setColor2(int red2, int green2, int blue2){
  {
    analogWrite(Red2,red2);
    analogWrite(Green2,green2);
    analogWrite(Blue2,blue2);

  }
}

```

# Answer
I haven't traced through your if statement logic in detail to see what you are trying to do, BECAUSE I found that you have statements like this:

```
//            Get rid of this semicolon in every if statement.
//            |
//            V
if (condition); {
    //        ^
    //        |

    //Code that will always be executed
}

```

You should **NOT** have a semicolon after an if statement like that. That says "if (condition) then do nothing" (A semicolon creates a blank "do-nothing" statement that becomes the code that is executed if the if statement is true. Then the code in the braces gets executed every time.)

It is parsed as:

```
if (condition) <empty_statement;>

{
    code that always executes
}

```

That is one of the hidden "nasties" of C and it's close cousins like C++, Java, and Objective-C. Another nasty is typing:

```
if (a=b)

```

...when you mean `if (a==b)`. (The first version puts the value of b into a, and then evaluates b as a boolean. If it's 0, the if statement is treated as false. If it's non-zero, the if statement is evaluated as true.

Another one is the fall-through cases in C `switch` statements. If you forget to add a `break` statement at the end of each case it falls through to the next case.
> 0 votes

---
Tags: arduino-uno
---


title: arduino is skipping the if statement

text:
# Question
Title: arduino is skipping the if statement
Hi guys I am new to this language and i just tested the code to control a servo motor Can anybody help me please ? here is the code

```
void setup() {

  servo_test.attach(3);
  pinMode(9, INPUT);

}

void loop() {

 if ( digitalRead (9 == HIGH)) {

   for(angle = 0; angle < 180; angle += 5)    to 180 degrees
  {
    servo_test.write(angle);
    delay(5);
  }

  delay(4000);
  for(angle = 180; angle>=1; angle-=5)      to 0 degrees
  {
    servo_test.write(angle);               specified angle
    delay(5);
  }

    delay(4000);
}

}

```

It is just like the arduino completely ignore the if statement and start the loop wheter pin 9 is in high or low state even if i wire it directly to gnd

# Answer
> 0 votes
In your code this line:

```
 if ( digitalRead (9 == HIGH)) {

```

...is likely passing the function "digitalRead()" the value zero as "9 == HIGH" is likely false.

Likely what you want to do is check if the value returned by the function "digitalRead()" is high. Try:

```
 if ( digitalRead (9) == HIGH) {

```

...instead.

---
Tags: motor, pins
---


title: STM8 Development Board with Arduino IDE

text:
# Question
Title: STM8 Development Board with Arduino IDE
I got one of these cheap STM8 boards from China and was hoping to find a way to use this with arduino code.  Does anyone know of an arduino boot loader and board package that works with them ?

# Answer
Start the Arduino-IDE. In File-\>Preferences, Settings tab, enter

https://github.com/tenbaht/sduino/raw/master/package\_sduino\_stm8\_index.json

Open Tools-\>Board:...-\>Boards Manager

Find Sduino by typing 'sd' into the search line

Click on the list entry

Click on Install.

This link is more comprehensive

https://tenbaht.github.io/sduino/
> 2 votes

# Answer
There is a bootloader on those chips to slow serial programming. A much easier way to to get a stlink debugger.

There are also some packages that allow Arduino styled programming on those chips. I wrote one myself that runs on iar and I think at least one on sdcc.

Those chips are really nice.
> 1 votes

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


title: I2C potentiometer mess

text:
# Question
Title: I2C potentiometer mess
I bought a few MCP4651 dual 8 bit I2C pots for a project. After browsing the arduino libraries and finding nothing,"No big deal" I thought to myself ... I've already written I2C libraries for other parts that were much more complicated! (e.g: ADS1219 24 bit ADC)! so just load up the datasheet and watch the memory maps and commands! ok, there are some stuff on page 49 which seem useful! oh boy was I ever wrong! this data sheet looks like nightmare! the worst documentation for any I2C device I've seen so far. The commands I wrote based on that did absolutely nothing!

I found a code for controlling an I2C pot in one of the arduino examples which is something like this:

```
#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte val = 0;

void loop() {
  Wire.beginTransmission(44); // transmit to device #44 (0x2c)
  // device address is specified in datasheet
  Wire.write(byte(0x00));            // sends instruction byte
  Wire.write(val);             // sends potentiometer value byte
  Wire.endTransmission();     // stop transmitting

  val++;        // increment value
  if (val == 64) { // if reached 64th position (max)
    val = 0;    // start over from lowest value
  }
  delay(500);
}

```

I decided to just try it and see what happens (changed the address to the correct value) and crazy enough it actually worked! so I hacked this piece of code to get the first pot to work!

```
void setPot0(int n){
  if (n>256) n=256;
  if (n<0) n=0;
  Wire.beginTransmission(address);
  if (n<256){
    Wire.write(0x00);
    Wire.write(n);
  } else{
    Wire.write(0x01);
    Wire.write(0);
  }
  Wire.endTransmission();
}

```

and somehow this works! I still can't find this pattern in any of the pages on datasheet, but hey! it works so I'm not gonna complain about that? I still haven't managed to make the pot1 to work, only pot0 ... if you can make sense of how the commands and data bytes should be like, please help me. It's so much more clear in T.I datasheets; you just use the command to write to the register you want and they detail what each register does:

Edit: here is a link to the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/22096b.pdf

# Answer
> 3 votes
The registers are listed in table 4-1. Clearly enough.

The command byte format is shown in chapter 6. That command byte includes the operation and the register number, as well as upper bits for registers that expect more than 8 bits of data.

Two bytes are needed to set a register. The first 4 bits are the register number (0000 for wiper 0, 0001 for wiper 1, and 0100 for the TCON register). The next two bits are the operation as shown in figure 7-1. 00 for a simple write. The next two bits are the upper 2 bits of the data. Following that are the lower 8 bits of data.

So to write a pot 0 value of 0x23 you would write:

```
0x00 0x23

```

To write a pot 1 value of 0x65 you would write:

```
0x10 0x65

```

To write a pot 1 value of 0x13D you would write:

```
0x11 0x3D

```

You can make a simpler function to wrap it for you:

```
void writePot(uint8_t address, uint8_t pot, uint16_t val) {
    Wire.beginTransmission(address);
    Wire.write((pot & 3) << 4 | ((val >> 8) & 3));
    Wire.write(val & 0xFF);
    Wire.endTransmission();
}

```

---
Tags: arduino-nano, i2c, potentiometer
---


# Question
Title: How do I grab data from my Arduino device using a Python program?
We are currently creating a system which can log student attendance using RFIDs. Currently, we have the RFID Scanner set up (MFRC522 reader and Arduino UNO microcontroller). The database for the student's info and time-logging is also already set up. We are; however, having problems with accessing the data the Arduino is sending. We want the Arduino device to send us the Tag IDs via a USB Connection and have set it up to send the relevant data through the Serial Port. However, we cannot access this data using a Python program with this code.

```
import serial

x = 1
while(x == 1 ):
    ser = serial.Serial("COM3", baudrate = 9600, timeout = 0)
    if(ser.is_open):
       print("Serial Port in Use")
    else:
       print("Card ID: " + ser.read)

```

We are attempting to read from Port COM3 (the SP the Arduino uses). If the serial port is in use, the program outputs the "Serial Port in Use" (for testing purposes only, to be removed in final code) and if not, it will output the Card ID. However, through this, we run into the problem of being unable to use the same serial port with the Arduino (we are running on Windows). We tried using a serial port splitter but replacing the "COM3" with the name of the virtual port does not work.

We would prefer not to use Processing and would be open to simply avoiding the use of a serial port completely.

# Answer
It isn't a good idea to open serial in a loop. It can be opened once at the start (or you can retry once per few seconds, if it fails).

Also the method `is_open` should return `true` if the serial was successfully opened so you can use it.

Maybe some working example would be a good way to start.
> 0 votes

---
Tags: arduino-uno, rfid
---


# Question
Title: Arduino Problem with using SoftwareSerial and SPI
I am using an external ADC (via SPI) and also a GPS receiver (Software Serial). I tried each one of them and it's working fine. Now, when I try to integrate both of them in one sketch, I can only make the ADC work, the GPS is not receiving something.

```
void setup()
{
  pinMode(ADS1220_CS_PIN, OUTPUT);
  pinMode(ADS1220_DRDY_PIN, INPUT);

  Serial.begin(115200);
  ss.begin(9600);

  //while(!Serial);
  //SPI.begin();                           // wake up the SPI bus.
  //SPI.setBitOrder(MSBFIRST);
  //SPI.setDataMode(SPI_MODE1);

  //ADS1220.begin();
  Wire.begin();
  delay(1000);  // Give things time to "warm-up"

  delay(1000);
  pre_time = millis(); //store current time to be used as "previous" time
}

```

I found out that in the setup(), when I comment out all those SPI functions, the GPS returns something. What seems to be wrong with this? thank you so much for any help

# Answer
> 2 votes
SoftwareSerial is **very** inefficient. AltSoftSerial is best. See this answer for a complete list of alternatives.

You may want to look at my NeoGPS library. It is smaller, faster and more accurate than all other libraries. The examples are structured better. You don't show your whole sketch -\_-, but the loop structure could be your real problem. Be sure to read the Troubleshooting page for more suggestions.

# Answer
> 1 votes
I managed to solve this just by changing the Rx pin to digital pin 4 from digital pin 10, I don't know what causes the problem but it did the job for me

# Answer
> -1 votes
For the Arduino to be SPI master, the SS pin (D10) must be an output. Using it as software serial input (Rx) is no good. If you had used it as the Output, Tx, you would likely have been ok. I try to use 10 as SS for the first SPI device I have connected all the time to avoid that pitfall.

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


title: How to interface MPU9250 and NodeMcu?

text:
# Question
Title: How to interface MPU9250 and NodeMcu?
I am trying to send MPU sensor data to Pubnub IOT platform but not able to do it since there is some unknown problem. There is no error in code but following issue pops up in com port:-

It looks like sensor reading needs to be in JSON Format but no sure how to do it. I Just need it in raw imu sensor reading for now so how do i get it.

Here is the code:

```
#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>
#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP
#include "MPU9250.h"

const char *ssid =  "mym404";     // replace with your wifi ssid and wpa2 key
const char *pass =  "786110786";

const char * pubkey = "my key";
const char * subkey = "my key";

const char * pubchannel = "demo_keyset";
const char * subchannel = "demo_keyset";

MPU9250 IMU(Wire,0x68);
int status;

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(115200);

       Serial.println("Connecting to ");
       Serial.println(ssid);

       WiFi.begin(ssid, pass);
       while (WiFi.status() != WL_CONNECTED)
          {
            delay(500);
            Serial.print(".");
          }
      Serial.println("");
      Serial.println("WiFi connected");

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);

    while(!Serial) {}

  // start communication with IMU
  status = IMU.begin();
  if (status < 0) {
    Serial.println("IMU initialization unsuccessful");
    Serial.println("Check IMU wiring or try cycling power");
    Serial.print("Status: ");
    Serial.println(status);
    while(1) {}
  }
}

void loop() {
    // read the sensor
  IMU.readSensor();
  // display the data
  Serial.print(IMU.getAccelX_mss(),6);
  Serial.print("\t");

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "String(IMU.getAccelX_mss())");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

```

What do you guys think?

# Answer
The error you're reporting is coming from your call to `PubNub.publish()`. You could have diagnosed the problem by taking outputting and inspecting what you were passing to it.

Your line:

```
PubNonSubClient *pclient = PubNub.publish(pubchannel, "String(IMU.getAccelX_mss())");

```

is not going to work. You're sending the string `"String(IMU.getAccelX_mss())"` to PubNub rather than the value of `IMU.getAccelX_mss()` as a `String`. Take the quotes off it:

```
PubNonSubClient *pclient = PubNub.publish(pubchannel, String(IMU.getAccelX_mss()));

```

If for some reason the number has to be returned as a string, the code would look like:

```
PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"" + String(IMU.getAccelX_mss()) + "\"");

```
> 1 votes

---
Tags: esp8266, wifi, nodemcu, json, iot
---


# Question
Title: How to use the ESP32 WROOM GPIOS above #18 with arudino ide?
I am using the Arduino IDE version 1.8.8 I am trying to control an ESP32-wroom. The gpios for pins 16 and 17 are working. I have some relays on GPIO's 18 and 19 that I'd also like to be able to control. I also have no control over GPIO's that are over 17 I've tried 18 through 27 and I can't toggle them.

```
#define relayPin3 18
#define relayPin4 19

int relayflag = 0;
void loop() {
  delay(1000);
  if (relayflag == 0){
    digitalWrite(relayPin3, LOW);
    digitalWrite(relayPin4, HIGH);
    relayflag =1;
  }
  else
  {
    digitalWrite(relayPin3, HIGH);
    digitalWrite(relayPin4, LOW);
    relayflag = 0;
  }

}

```

I noticed that GPIO's 18 and 19 are also shared with spi ports.

Does the digitalWrite command work for any GPIO or is it in use by another library? Is there some other command to get access to the GPIO's I need to use? Some library I need to modify.

# Answer
> 3 votes
Found the answer, albeit a simple one. This is my first go around with arudino so it will look ridiculous to those who program microprocessors (including myself)

You need to declare the pin to be an output before use. The inconsistent thing is, this only happens sometimes. For some of the pins you don't need to use pinMode for them to work.

```
  pinMode(relayPin1, OUTPUT);

```

---
Tags: esp8266
---


# Question
Title: Help decrypting AES string from arduino rf module in python
Please excuse any glaring errors in my code, I'm new to both C and python.

I'm trying to send an encrypted message from my arduino uno via a DHT22 sensor and an rf module using the radiohead ask and AESlib libraries to a raspberry pi with a usb RTL-SDR using the rtl\_433 library and a python script.

I think (but I could very well be wrong) I have the Arduino side working properly and it feels as though I'm pretty close on the python side, however I don't seem to be decrypting the message properly.

An example of the string before being encrypted might be:

"55.55,24.99,0001"

Here is the code on the Arduino side:

```
#include <AESLib.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "DHT.h"
#include <RH_ASK.h>
#include <Base64.h>

#define DHTPIN 2

#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
RH_ASK driver;

bool takeSensorReading = true;
float h;
float t;
String str_humid;
String str_temp;
String str_out;
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
char data[32];
char endChar[1] = "Ʊ";

void setup() {
  driver.init();
  dht.begin();
  Serial.begin(9600);
}

void loop() {
  delay(5000);

  int messagelength = sizeof(str_out);
  byte plain[messagelength];

  h = dht.readHumidity();
  // Read temperature as Celsius
  t = dht.readTemperature();

  // Convert Humidity to string
  str_humid = String(h, 2);

  // Convert Temperature to string
  str_temp = String(t, 2);

  // Combine Humidity and Temperature
  str_out = str_humid + "," + str_temp + ",0001";

  str_out.toCharArray(data, 32);
  aes256_enc_single(key, data);

  /*aes256_dec_single(key, data);*/
  Serial.println(data);
  int encryptedStringLength = sizeof(data);

  int encodedLength = Base64.encodedLength(encryptedStringLength);
  char encodedString[encodedLength];
  Base64.encode(encodedString, data, encryptedStringLength);
  Serial.print("Encoded string is:\t");
  Serial.println(encodedString);

  driver.send(strcat( (uint8_t *)encodedString, endChar ), 33);
  driver.waitPacketSent();

  takeSensorReading = !takeSensorReading;
}

```

and here is the python code:

```
import subprocess
import json
import base64
from Crypto.Cipher import AES

BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]

def print_no_newline(string):
    import sys
    sys.stdout.write(string)
    sys.stdout.flush()

def decrypt(enc):
    private_key = str(bytearray([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]))
    iv = enc[:16]
    cipher = AES.new(private_key, AES.MODE_CBC, iv)
    return unpad(cipher.decrypt(enc[16:]))

p = subprocess.Popen(['rtl_433', '-f', '433720000', '-F', 'json'],stdout=subprocess.PIPE,bufsize=1)
# rtl_433 -f 433720000 -F json
try:
    for line in iter(p.stdout.readline, ""):
        lineStripped = str(line).strip()
        try:
            jsondata = json.loads(lineStripped)
            time = jsondata["time"]
            payload = jsondata["payload"]
            if len(payload) == 33:
                payloadstring = ''
                for a in range(len(payload)):
                    payloadstring += chr(payload[a])
                payloadstring += "AAAAAAAAAA="
                print payloadstring
                encrypted = base64.b64decode(payloadstring)
                print encrypted
                decrypted = decrypt(encrypted)
                print decrypted
        except Exception as err:
            print "oh no, something went wrong"
            print("error: {0}".format(err))
except KeyboardInterrupt:
    p.kill()

p.wait()
p.stdout.close()
```

Here is an example of the erroneous output of the decrypt function:

"@g�އ�6S���25zD"

Any help you could give me in decoding the message from the Arduino in the python script would be really appreciated.

Thanks

Richard

\*EDIT

I thought if it helps I could provide a bit more context around the transmission stages that the message goes through:

After the initial data string is constructed from the temperature and humidity sensor eg "55.55,24.99,0001" that 16 byte message is added to a 32 byte char array and encrypted using the aes128\_enc\_single method. The encrypted message is then base63 encoded The encrypted char array is then combined with an extra unencrypted character "Ʊ" (which I thought I could use to crudely validate the message) and sent via the radiohead ask send method:

`driver.send(strcat( (uint8_t *)encodedString, endChar ), 33);`

On the pyhton/reciever end I run a sub process `rtl_433 -f 433720000 -F json`

and listen for the output line by line. A example of the output of the rtl\_433 command would look something like this: `{"time": "2019-03-05 00:00:00", "model": "RadioHead ASK", "len": 33, "to": 255, "from": 255, "id": 0, "flags": 0, "payload": [111, 110, 109, 57, 120, 86, 52, 79, 121, 78, 71, 52, 48, 122, 117, 88, 67, 52, 77, 118, 85, 81, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65], "mic": "CRC"}`

rtl\_433 converts the message into an array of ASCII or Unicode characters.

I have then tried to convert the characters in the recieved array back into standard characters: `payloadstring += chr(payload[a])` added padding to the message: `payloadstring += "AAAAAAAAAA="` then base64 decoded the result: `encrypted = base64.b64decode(payloadstring)` and then finally decrypt that: `decrypted = decrypt(encrypted)`

Hopefully that info might be helpful in flagging up where I have gone wrong.

# Answer
> 1 votes
By inspection only:

You are using an Initialization Vector and CBC mode in your Python code, but no IV and single block encryption in your Arduino code.

I think if you use MODE\_ECB in your Python it will ignore the IV and match the Arduino code.

From a look at the AESLib github it appears your key should be exactly 16 bytes - yours is 32. I haven't looked at the code to see whether it will just ignore the rest, but the Python code definitely won't, so you should probably do what it says and use 16, and adjust your Python code to match.

Since the above wasn't enough to get it working, I would suggest divide-and-conquer: Use an online AES-128 encyrptor/decryptor such as aesencryption.net or encode-decode.com or infoencrypt.com to validate and cross-check your Arduino encryption and Python decryption functions. With a bit of luck you can at least fix them one-by-one, against a known-good reference. Perhaps with a bit of fiddling you may be able to work out where it's going wrong.

I presume the humidity value may not change much, and I have a feeling that sending several messages with the same start can substantially weaken the encryption but I'm no crypto expert and perhaps it's still adequate for your purposes.

---
Tags: arduino-uno, python
---


title: Using two leds with one push button

text:
# Question
Title: Using two leds with one push button
How can I make the code of this project where I will press one time a button, to turn on the first led (and turn off second led) and when other one press to turn on second led (and turn off the first led).

# Answer
> 2 votes
You can do this by keeping the 'state' saved in a variable. Depending on it's state, the button will have a different effect.

After this effect, the state is updated, so that next iteration it will behave according to the other state.

```
state = led1
if(buttonpressed){
   if(state == led2){
     led1On();
     led2Off();
     state = led1;
   }else{
     led1Off();
     led2On();
     state = led2;
   }
}

```

---
Tags: led, c, arduino-leonardo, programming-sequence
---


title: Can I program an ATtiny87 with Arduino

text:
# Question
Title: Can I program an ATtiny87 with Arduino
I have a project, and I want to use an ATtiny167(ATtiny87), I know that an Arduino can progam ATtiny84 (84/44/24), ATtiny85 (85/45/25), and ATtiny2313 (4313). **but I don't know if it can program an ATtiny87?**

thank you for your help.

# Answer
There is a json for ATtiny 167 at https://playground.arduino.cc/Main/ArduinoOnOtherAtmelChips

So add that json to your preferenses.
> 2 votes

---
Tags: attiny
---


title: Powering 150 WS2812B LED strips

text:
# Question
Title: Powering 150 WS2812B LED strips
I just bought an Elegoo Uno R3 today and delved into programming Arduinos. For my first project I'd like to power a 5m LED strip (30 LED/m). I've learned that an individual neopixel needs around 60 mA, and i'm gonna assume this means that to power all 150, I need 9A. I'm extremely new to all this (and electrical stuff in general) and not exactly sure how to go on about giving 9A worth of power to the strips and the Arduino. Any help to get me on the right track would be appreciated.

# Answer
> 2 votes
Your math looks right to me. You need a 9A power supply if you're going to drive all 150 LEDs at %100 brightness on all 3 channels.

I'd suggest using a separate 500mA 5V regulated power supply for the Arduino. Switching 9A of load on and off on the LED power supply is going to cause quite a bit of variation in the voltage on that 9A supply, and the simplest way to keep the power supply to the Arduino clean is to make the 2 power supplies completely different.

# Answer
> 0 votes
Connect the power supply in multiple places to the LED strip. The two ends and the middle at least. That will keep all the current from having to flow thru all of the strip. If try to power it from just one end, the power traces in the strip might act as a fuse and blow open. Or it might survive, but act like a low-ohm resistor and the chips farther down the string will see less voltage (because voltage down the trace = current x resistance) and may appear dim, or act weirdly, or not turn on at all.

---
Tags: arduino-uno
---


title: Uploading bootloader to ATMEGA328 P

text:
# Question
Title: Uploading bootloader to ATMEGA328 P
I have a duemilanove which originally had a 168. I have some ATMEGA328 P chips and I've put one into the duemilanove. I am using a Uno as a programmer for the duemilanove. I am running Arduino 1.8.2 on a PC which I understand doesn't need a capacitor installed on the Uno. I've uploaded the sketch which makes the Uno an ISP, I have edited the avrdude.conf file, have wired up in accordance with http://www.crash-bang.com/resource/bootload-atmega328/ and the tutorial on this site. When I run burn bootloader using the preferences set to verbose, the returned signature is correct for the P version of the chip I believe (0x95 0x14) and this is the value I have put into the avrdude.conf file. However, avrdude is still insisting it is expecting to receive 0x95 0x0F and will not burn the bootloader. I have no idea where it is getting this value from (I've even tried editing the iom328p.h file...). Any ideas?

# Answer
The signature bytes are:

ATmega328 0x1E 0x95 0x14

ATmega328P 0x1E 0x95 0x0F

So it looks you have the wrong bytes for the 328P.
> -1 votes

---
Tags: arduino-uno, atmega328, bootloader, arduino-duemilanove
---


title: Metal detector using Arduino

text:
# Question
Title: Metal detector using Arduino
Is anyone out there building serious metal detectors with the Arduino? By "serious" I mean metal detectors with phase sensitivity to discriminate between ferrous and non-ferrous metals, etc. Seems like the Uno is a good platform for a smart metal detector project.

Update: Arduino allows me to control phase discrimination which allows ferrous metals to be rejected. I already know it can be done with an analog phase shift circuit. Also Arduino can perform target ID function with readout to 16x2 LCD display.

# Answer
A set of posts on Instructables uses an Arduino Nano to generate a Phase Induction pulse, with a capacitor instead of a dump resistor to set up a decaying oscillation, which is then limited with diodes and detected by the analog comparator with interrupts. The comparator interrupts then count the frequency of the decaying ringing oscillation producing some ferrous/non-ferrous discrimination, and the duration of the ringing, producing some signal strength and size information.

The tricks in the Pulse Induction LC-trap system of using the analog comparator would be applicable to detecting phase shifts and detecting crossings in sync with a timer-based output.
> 1 votes

---
Tags: arduino-uno
---


title: First Arduino Uno - Immediate Problems

text:
# Question
Title: First Arduino Uno - Immediate Problems
I'm new to Arduinos but researched thoroughly before buying one. Just for context I'm an IT Professional with 20 years in the game, I'm comfortable with Linux/Unix, Windows, Raspberry Pi's, electronics, hardware, software and monitoring/switching COM ports.

I've purchased my first Arduino (actually a Elegoo Uno R3 clone) and have just tried it out of the box connected to two different systems; one Windows 7 64bit Enterprise the other Kubuntu. Despite having the correct COM port selected on both I'm getting similar error messages:

```
**avrdude: ser_open(): can't open device "\\.\COM15": The system cannot find the file specified.**

```

or

```
**avrdude: ser_open(): can't open device "\\.\COM6": Access is denied.**

Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

Yes I have tried different COM ports.

Yes I have tried turning off Firewalls

Yes I have tried different USB cables.

I have a solid green LED and a intermittently blinking orange LED.

The suggested Troubleshooting guide + many Forum Threads do not seem to cover this exact error I'm encountering - well they do but they tend to be people with the simple issue of them not selecting the correct COM port or having the same COM port tied up with another task. Then choose the correct port and it works. I'm confident I have the correct COM port and when I click Get Board Info it pulls down the correct board information and serial number etc.

On the Linux system I was seeing a similar behavior with slightly different wording: Permission Denied

On my Windows 7 system I run as a Standard User (as one should, not as an Administrator), but regardless I have tried running the Arduino application normally and as an Administrator user but it has the same result. And it seems strange that it encounters the same style of error across multiple different operating systems.

Have I just been really unlucky and got a dud for my first Arduino or am I missing something obvious?

Thanks for your time and help.

# Answer
> 5 votes
On Linux "Permission Denied" generally means one of two things:

1. You're not in the `dialout` group (or you haven't logged out and logged in since), or
2. Something else is using the serial port.

For 1:

```
sudo usermod -a -G dialout ashley
<log out or reboot>

```

For 2:

The most common culprit is `ModemManager`. The simplest cure is to uninstall it:

```
sudo apt-get remove modemmanager

```

---
Tags: arduino-uno
---


# Question
Title: Light Sensor - how to wait for specific setting then continue on Leonardo?
I have an analog light sensor working on my Micro Pro Leonardo board. I want to reach a part of my code which include keyboard presses where it monitors to see when an LED flashes and then continues the code from there.

Could someone give me a code example of how I can do that?

Currently I'd have something like....

```
  Keyboard.write(KEY_RETURN);
  delay(800);
  Keyboard.write(KEY_TAB);
  delay(150);
  Keyboard.write(KEY_TAB);
  delay(150);
  Keyboard.write(' ');
    }

//Code here to wait until LED flashes, registers as 30 or less on the light sensor. Then carry on with code below once this happens

  BootKeyboard.press(KEY_LEFT_GUI);
  BootKeyboard.press('r');
  delay(40000);
  BootKeyboard.releaseAll();

```

etc

I know the light sensor is `AnalogValue = analogRead(A0);` and I assume it's some kind of "If" statement which loops until the value because less than what is defined but have no idea how this would be written.

# Answer
> 1 votes
One method:

while (analogRead(A0) \< setting){ // sit in this loop taking readings until get one that is \>= to setting }

---
Tags: sensors, arduino-leonardo
---


# Question
Title: Electric meter with Arduino and RS485 module
I'm a Arduino newbie. I have an Electric meter with an RS485 output. I want to get the MeterID value over the RS485 module and the Arduino. I just have document from manufacturer.

```
Sent by computer : 68 99 99 99 99 99 99 68 01 02 67 F3 C3 16.
Return from meter : FE 68 99 99 99 99 99 99 68 81 08 67 F3 A6 9B 34 4B 33 33 6F 16.

```

My Arduino code:

```
#include <SoftwareSerial.h>

#define SSerialRX        10
#define SSerialTX        11
#define SSerialTxControl 3
#define RS485Transmit    HIGH
#define RS485Receive     LOW

SoftwareSerial RS485Serial(SSerialRX, SSerialTX);
byte request[] = {0x68, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x68, 0x01, 0x02, 0x67, 0xF3, 0xC3, 0x16};
int byteRead;

void setup()
{
  Serial.begin(9600);
  RS485Serial.begin(1200);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Receive);
  delay(20);
  Serial.println("Get Meter Address App");
}
void loop()
{
  digitalWrite(SSerialTxControl, RS485Transmit);
  RS485Serial.write(request, sizeof(request));
  delay(2000);
  digitalWrite(SSerialTxControl, RS485Receive);
  delay(2000);
  if (RS485Serial.available())
  {
    byteRead = RS485Serial.read();
    Serial.println(byteRead, HEX);
  }
}

```

Serial Monitor show:

I'm using combo like this topic modbus-rtu-controller-monitoring-with-arduino-and-rs485-module. My code is in C# below. I used the code before and it worked fine, but on the computer I use a COM port (Baudrate 1200, data 8bits, Parity EVEN, Stopbit 1) with an RS485-R232 converter:

```
#Send data
dataOUT = WriteData("68 99 99 99 99 99 99 68 01 02 67 F3 C3 16");
serialPort_Meter.Write(dataOUT, 0, dataOUT.Length);

#WriteData method
private static byte[] WriteData(string hex)
{
return hex.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();
}

#Read data
private static string ReadData(SerialPort serial)
{
byte[] buffer = new byte[serial.BytesToRead];
serial.Read(buffer, 0, buffer.Length);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
sb.AppendFormat("{0:X2} ", buffer[i]);
return sb.ToString();
}

```

# Answer
> 0 votes
Using readBytes would do the same as your C# code. `readBytes` is blocking. It will wait for every byte until timeout. Default timeout is 1 second. If the count of bytes is smaller then the size of the buffer, it will wait a second after the last byte received. You can set the timeout with `RS485Serial.setTimeout(500);` (500 milliseconds for example).

```
void loop()
{
  digitalWrite(SSerialTxControl, RS485Transmit);
  RS485Serial.write(request, sizeof(request));
  RS485Serial.flush();
  digitalWrite(SSerialTxControl, RS485Receive);
  int recvLen = RS485Serial.readBytes(buffer, sizeof(buffer));
  for (int i = 0; i < recvLen; i++) {
    Serial.println(buffer[i], HEX);
  }
}

```

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


# Question
Title: Ultrasonic sensor underwater calibration
Does anyone knows how to calibrate AJ-SR04M using the Arduino? I am working on AUV. underwater reading from current code; it is giving continuous 20cm while moving inches. http://shop2.hanjindata1.cafe24.com/product/aj-sr04m-ultrasonic-ranging-module/206/

# Answer
If I understand your question correctly, your problem is probably that the working range of the AJ-SR04M sensor is **20cm - 500cm**.

The sensor uses the same transducer to create the sound pulse and to listen for the echo. It needs time to switch from one mode to the other, which explains why your sensor can't measure distances of less than 20cm.

---

The speed-of-sound in water is about 5x the speed of sound in air. More specifically, at 20 degrees Celsius the speed-of-sound in air is approximately 343 meters per second, while the speed-of-sound in water is approximately 1482 meters per second.

This will cause the sensor to 'under-report' the distance in water. The minimum distance will also be approximately 5x the minimum distance in air.

---

As an aside, you will also need to make allowance for the differences in the characteristic impedance and absorption between sound and water.

It's worth reading the paper Underwater Sound by P. Vigoureux (Proceedings of the Royal Society of London. Series B, Biological Sciences, Vol. 152, No. 946) for a discussion of all the factors involved.
> 3 votes

---
Tags: arduino-uno, arduino-mega, sensors, automatization, calibration
---


# Question
Title: How to get the weather kit with anemometer working using arduino (UNO)?
I tried to build a weather station with anemometer and My setup is, SwitchDoc Labs' anemometer kit (which is equivalent to sparkfun anemometer kit) connected to the grove weather-pi board with rtc clock DS3231 installed on which is connected to arduino UNO.

According to http://www.switchdoc.com/wp-content/uploads/2016/07/WeatherBoard\_CurrentSpecification.pdf and their official tutorial https://www.switchdoc.com/2015/01/weather-arduino-weatherpiarduino/, if I use grove weather-pi board's JP2 connections to connect to the UNO/Mega2560 board then it suggests as following (in my case its UNO)

diagram 1 diagram 2

```
GroveWeatherPi_board    Mega        Uno     Units
    JP2/1 ->            A0          A0      WindVane
    JP2/2 ->            D2          D3      RainBucket
    JP2/3 ->            D5          D2      Anemometer
    JP2/4 ->            GND         GND     GND

```

And the supposedly working sketch/library is https://github.com/switchdoclabs/SDL\_Weather\_80422 which only compiles on arduino-IDE without issue if I use the fork https://github.com/soligen2010/Adafruit\_ADS1X15 instead of the original https://github.com/adafruit/Adafruit\_ADS1X15 with it but even then the wind-speed and wind-direction unit or to say the whole anemometer part just do not work or in other words, do not give any reading. I have tested the units individually up to the arduino pins with LED light on breadboard, they are sending signals/responding and also mounted the whole project on a Mega2560 as well but results remained unchanged.

I am assuming the pin-outs defined in the https://github.com/switchdoclabs/SDL\_Weather\_80422 are messed up then but how to redefine it in the sketch/library because in the ino sketch file, these are the pin-out definitions for primarily Mega2560

```
#define pinLED     13  // LED connected to digital pin 13
#define pinAnem    18  // Anenometer connected to pin 18 (not used in the diagram!) - Int 5 - Mega   / Uno pin 2
#define pinRain    2   // Anenometer connected to pin 2 - Int 0 - Mega   / Uno Pin 3
#define intAnem    5   // int 0 (check for Uno), according to the above two diagrams' comparison, for UNO this pin also goes to the pin 2
#define intRain    1   // int 1 (not used in the diagram! Then why? Its a TX pin)

```

Where the pinAnem and intAnem both indicates pin 2 for UNO according to the above two diagrams.

When I connect the I2C vcc pin from grove-weather-board to UNO's 5 volts instead of 3.3 volts as shown, the wind direction gets fixed but still no wind-speed reading.

So what are the corrections I need to do in the SDL\_Weather\_80422 library or in the connection diagram in this case?

# Answer
> 0 votes
According to the above setup only rain bucket unit works.

And as jsotola mentioned both the anemometer and the rain bucket sensors are simple switches, so a simple sketch can be written that reads the switch state and light LED (pin13) if the switch is activated and turns off LED if switch is not activated and that can be done for each of the switches separately.

But instead I took a shortcut.

Fixes:

1. The wind vane part (on analog pin A0) starts working only when I connect the I2C vcc pin to ***5 volts*** pin instead of 3.3 volts pin of UNO.
2. Had to ditch the https://github.com/switchdoclabs/SDL\_Weather\_80422 library's wind\_speed reading method and adopting and merging into the http://cactus.io/hookups/weather/anemometer/davis/hookup-arduino-to-davis-anemometer-wind-speed code and adding up the wind\_gust function from https://github.com/sparkfun/Weather\_Shield/blob/master/Firmware/Weather\_Shield\_Weather\_Station\_V12/Weather\_Shield\_Weather\_Station\_V12.ino makes the anemometer with rain-bucket with the exact same setup fully functional.

---
Tags: arduino-uno, arduino-ide, adafruit
---


# Question
Title: Parse a large json response with ESP8266
I'm doing a project where my `Arduino` uses an external `ESP8266` wifi module (with `AT` firmware) to send http requests and receive server response.

I'm trying to get an NBA scoreboard, and here's what my Arduino sends to ESP:

```
> AT+CIPSTART=0,"TCP","data.nba.net",80
0,CONNECT

OK

> AT+CIPSEND=0,103
SEND OK

> GET /data/10s/prod/v1/20190214/scoreboard.json HTTP/1.1
Host: data.nba.net
Connection: keep-alive

+IPD,0,1460:HTTP/1.1 200 OK..
.............................
...here comes the response...
.............................

```

Now the code works fine, and I'm able to get the `json` file needed. The problem is that the response is sometimes too long and the file gets truncated, thus the response is incomplete. The file itself is sometimes pretty large, but I only need a few numbers from it (current teams + current score). So my questions are:

1. I use `readString()` method (of `SoftwareSerial` object instance) to read the response. Is there a way to parse the response chunk by chunk without loading everything in my ESP memory?
2. Is there a way to limit the response?
3. Are there any alternatives to the method I'm using? Maybe parsing the website (`nba.com` or `espn.com/nba`) directly? If so, how can I do that?
4. Maybe there's a way to write a separate (free) online API to parse `json`, constraint the response and send the small version upon request?

**PS.** I tried doing the same without `AT` firmware, flashing the module with a code that used `HTTPClient` directly (with `ESP8266WiFi.h` and `ESP8266HTTPClient.h` libraries):

```
HTTPClient http;
http.begin(request);
if (http.GET() > 0) {
    response = http.getString();
}
http.end();

```

That didn't help much. I'm still running out of memory since I'm directly loading the response to memory with `getString()`.

**PPS.** Just in case it matters, I'm using `ATmega2560` and a small `ESP-01` module (similar to this).

# Answer
> 1 votes
Ok, so I was able to do this. Here's the workaround.

Let's say the `GET` response is a flat string containing large `.json` file with all the commas and curly brackets. The idea is to read it byte-by-byte and instead of storing it just find the `key` you need and extract its `value`.

We want to find the field containing, say, "97.5 FM" from `http://data.nba.net/data/10s/prod/v1/20190223/scoreboard.json` (that's at the very end), skip 3 bytes (which is just " | ") and then read and `Serial.print` 4 bytes (which is "1280")\*. We would do something like this (of course make sure to connect to wifi and include `<ESP8266HTTPClient.h>`:

```
HTTPClient http;
http.begin("http://data.nba.net/data/10s/prod/v1/20190223/scoreboard.json");
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK)
  Serial.println(getValue(http, "97.5 FM", 3, 4));

```

where the `getValue()` function is defined as follows:

```
String getValue(HTTPClient &http, String key, int skip, int get) {
  bool found = false, look = false;
  int ind = 0;
  String ret_str = "";

  int len = http.getSize();
  char char_buff[1];
  WiFiClient * stream = http.getStreamPtr();
  while (http.connected() && (len > 0 || len == -1)) {
    size_t size = stream->available();
    if (size) {
      int c = stream->readBytes(char_buff, ((size > sizeof(char_buff)) ? sizeof(char_buff) : size));
      if (len > 0)
        len -= c;
      if (found) {
        if (skip == 0) {
          ret_str += char_buff[0];
          get --;
        } else
          skip --;
        if (get <= 0)
          break;
      }
      else if ((!look) && (char_buff[0] == key[0])) {
        look = true;
        ind = 1;
      } else if (look && (char_buff[0] == key[ind])) {
        ind ++;
        if (ind == key.length()) found = true;
      } else if (look && (char_buff[0] != key[ind])) {
        ind = 0;
        look = false;
      }
    }
  }
  return ret_str;
}

```

You can call this `getValue()` whatever many times you like, but the strings you're looking for need to be only after each other, because the response to `GET` is read byte-by-byte just once.

There is probably (i.e., most likely) a better way of doing this, but this approach works and it's pretty fast, so...

---

* This, of course, is just an example, and you can overload this `getValue()` function definition to, say, read until it gets a curly bracket or whatever.

# Answer
> 0 votes
Check out the Streaming JSON Parser. It's designed to parse large JSON objects on processors with little memory. You'll just read one character at a time from the HTTP connection rather than the whole response; pass the character to the library and it'll call code you provide every time it sees an array, object, key or value. Then you can extract just the pieces you want without the overhead of loading it all in memory at once.

The library has good examples that'll show you how to use it.

---
Tags: esp8266, wifi, http, atmega2560, json
---


# Question
Title: Need help combining two sketches (HC05 and temperature)
I have a project where I have to combine 4 sensors and get data wireless via Bluetooth (HC05). I just want help with combining just 1 sensor sketch and the Bluetooth sketch. I want the data from the temperature sensor to be displayed on my phone.

Temperature sensor code:

```
#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 2

OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();
}

void loop(void)
{
  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  Serial.print(" Requesting temperatures...");
  sensors.requestTemperatures();
  Serial.println("DONE");

  Serial.print("Temperature is: ");
  Serial.print(sensors.getTempCByIndex(0));
  delay(1000);
}

Bluetooth code:

#include <SoftwareSerial.h>
SoftwareSerial BT(11, 10);
int ledPin = 8;
int state = 0;

void setup()

{
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
BT.begin(9600);
}

void loop() {
  if(BT.available() > 0){
  state = BT.read();

  }
    if (state == '0'){
      digitalWrite(ledPin, LOW);
      BT.println("LED: OFF");
      state = 0;
    }
    else if (state == '1'){
      digitalWrite(ledPin, HIGH);
      BT.println("LED: ON");;
      state = 0;

    }
}

```

# Answer
> 0 votes
Instead of writing it all out, I give some tips:

* First combine the content of both `setup` functions. You can remove duplicate lines (e.g. `Serial.begin(9600);` is needed only once. Keep the order in a logical way.
* Than combine the content of both `loop` functions. However, the delay could cause a problem. Replace this by keeping a variable with the current time, and check when it's at least a second ago you checked the temperature sensor, if so, measure the sensor (and update the variable to the current time).

So you get something like:

```
unsigned long lastSensorMeasurement;

void setup()
{
   // Combination of both setup functions

   lastSensorMeasurement = millis();
}

void loop()
{
   // Process sensor
   if (lastSensorMeasurement + 1000 >= millis())
   {
      // Code for sensor as in loop
   }

   // Process Bluetooth
   // Code for bluetooth as in loop
}

```

---
Tags: arduino-uno, bluetooth, temperature-sensor
---


title: Too little current to trigger a relay?

text:
# Question
Title: Too little current to trigger a relay?
I try to use this relay with a Arduino Mega. I connected with jumper cables

* 5V pin to DC+,
* GND to DC- and
* Digital Pin 13 (because its a lucky number) to IN.

The power LED from the relay is lighting green.

I run this code, which should trigger the relay every 3s for 3s:

```
int pinOut = 13;

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

void loop() {
  digitalWrite(pinOut, LOW);
  delay(3000);

  digitalWrite(pinOut, HIGH);
  delay(3000);
}

```

When initializing the sketch, the red light (from the relay) is flashing and the relay is clicking. But afterwards nothing happens.

With my multimeter I check the currents:

* 5V to GND = ~5V
* Pin13 to GND, when not connected to relay = ~4.7V
* Pin13 to GND, when connected to relay = ~1.2V

The relay needs 5V and 5mA triggering current. I don't think the Arduino is not suited, since they promote the relay Arduino.

Any ideas? Do I need some kind of resistor? Or is the USB port from the laptop not sufficient? I used two different Arduino Mega's with two different relays. By the way i don't have a big background in electric.

# Answer
You are using pin 13, but you set pin 10 as an OUTPUT.

`pinMode(10, OUTPUT);`

Try changing that to

`pinMode(pinOut, OUTPUT);`

PS by not setting pin 13 to OUTPUT, `digitalWrite(pinOut, HIGH);` enables the internal pull-up, instead of "connecting" it to 5V. The internal resistors are around 35kOhm. So pulling a bit of current through them will result in a lower voltage at the pin.
> 2 votes

---
Tags: arduino-mega, relay
---


# Question
Title: Serial.read() doesnt work in IF statement
I am working with an XBee module, so naturally, I started my void loop with AT command testing.

```
void loop() {
    digitalWrite(Sleep_Rq,LOW);

```

A +++ with a guard time of 1 sec before and after it, sets xbee module in command mode.

```
delay(1000);
xbeeSerial.write("+++");              // Enter Command Mode
delay(1000);

```

This part of the code, puts the serial data into string variable x in the form of a String.

```
while(xbeeSerial.available()) {
    x = xbeeSerial.readString();
}

```

Serial.println() is returning OK onto the serial monitor.

```
Serial.println(x);

```

But when I compare x with OK nothing happens, 1 doesn't appear on the serial monitor.

```
if(x=="OK")
  {
   Serial.println(1);
  }
}

```

I tried swapping "OK" with 4F4B (ascii equivalent of OK), 20299 (decimal value). I also tried changing datatype of x from String to word and compared x with 0100111101001011. I also tried changing the IF condition as,

```
if(Serial.println(x)=="OK")
    {
     Serial.println(1);
    }

```

and many more techniques with no luck to be found.

# Answer
Your problem is that you are assuming that all you see in the Serial Monitor is all there is. You see "OK", so you expect to compare the text that comes in with "OK".

However it's not. Serial communication (at least, text based serial communication) generally includes some kind of line ending marker. That could be any combination of Carriage Return (`\r`) and/or Line Feed (`\n`). Different devices use different combinations.

As it turns out the XBee uses '\r' as the line ending marker.

There are two ways of dealing with it:

1. Include the line ending in your comparison (`"OK\r"`), or better,
2. Incorporate the line ending in the reading.

The second point there involves the use of `readStringUntil()`:

```
String x = xbeeSerial.readStringUntil('\r');

```

That is a more reliable way of reading the response since it reads everything up to the line ending, rather than reading until it times out with nothing else to read. You should find your whole program runs smoother with that method.
> 1 votes

---
Tags: arduino-uno, serial, xbee
---


# Question
Title: Does this sound like a good approach to decoding a dumb keypad?
**The background:**

---

I bought a "dumb" 8-pin 4x4 keypad for use in a project. (This one: https://www.sparkfun.com/products/14881 It has a wire connected to each row, and a wire connected to each column. When you press a key, it connects a row pin and a column pin. You have to use GPIO outputs to send +5V down one row/column at a time, and then use inputs to look for a HIGH on a corresponding set of pins from the other dimension, which indicates a connection between a specific row/column pair.)

I found a framework, MultitapKeypad, that at first appeared perfect. It is a nice clean C++ object with a simple main method, getKey(), that returns a struct with information about the key the user pressed. It detects long presses and repeat presses, things I plan on using.

However, when I looked into it I found things were not as good on the inside. The getKey method uses a while (no key pressed) loop that loops forever. The author's solution to not locking up the Arduino any time you are waiting for a keypress is to provide a callback function that the library calls from the while loop.

The idea of turning a sketch's control flow completely upside down and having to do all your app's event handling from the callback of a keypad class just seems wrong. Then control flow from the app's main loop has to go through the keypad's callback when I'm waiting for keys, or through some other flow otherwise.

The framework also makes use of delay() in it's debouncing, another no-no for apps that manage multiple things at once.

I was therefore thinking of writing my own keypad handler.

My current project, a power controller for lights, chargers, and a humidity controlled warm air dryer will run all of those things simultaneously. It has a back-lit LCD for a display, and uses a motion sensor and photoresistor to turn lights on when it detects motion in low light.

It puts the LCD to sleep if it doesn't detect motion or any user input from it's various switches for an extended period.

When I integrate a keypad into the project I would also like to add keypresses to the list of things that keeps the display awake. I don't see an easy way to do that with the LCD library I was using.

---

**My proposed design:**

I was thinking of wiring the keypad with all of the row pins connected to a 9th pin with diodes, anodes pointed towards the 9th pin. I'd set that 9th pin up in INPUT\_PULLUP mode and attach it to an interrupt, set to trigger on FALLING signal (or perhaps CHANGE. See below.) The row pins would all also be configured as INPUT\_PULLUP. The column pins would all be set up as outputs, and driven LOW.

When the user pressed a key, it would connect one of the column pins to a row pin. That would pull that row pin's input LOW, and also pull the interrupt pin LOW, triggering the ISR (Interrupt service routine).

In the ISR I would use port registers to switch all the column pins to HIGH, and then toggle one column pin at a time back to LOW, looking for a row pin to also drop LOW. If one and only one column going LOW triggers one and only one row to go LOW, I know only one button is pressed, and know the row/column combo, and hence the key that was pressed. If multiple columns trigger a row, or more than one row drops to LOW, I know more than one key is pressed. (I could use that info to report multi-key presses if I need to, although \>2 keys at a time gets messy fast.)

Once I have a key I could add the key code for that key to a simple ring buffer and set a "key ready" flag. (My ring buffer might contain structs with more than just a key code, like up/down events, time stamps, etc.)

The rest of my sketch could then query my keypad for "key ready" and read one or more keys as needed. I'd provide housekeeping functions for clearing the key buffer, a way to detect buffer overflows, etc.

I guess I'd actually want interrupts on both falling and rising state change, so I could detect key up events and track the duration of key presses.

I'd also need to add debouncing of some sort or another. I could use a simple RC filter on each input pin, but I don't have a lot of room left on my project breadboard and that would require 4 capacitors and 8 resistors.

From what I've read the millis() function is a little slow and best avoided in ISR routines. Is there a fast alternative to get the current clock value directly in an ISR? If so I could use software to debounce the keys.

Are there any obvious flaws in my plan? Does using an ISR like this sound reasonable? The Keypad actually doesn't short the row/column pins together. It uses variable resistances between the row/column combinations, I guess so that you can use a voltage divider and an analog input to figure out which key was pressed based on the measured voltage. The docs for the keypad say the resistance for a row-column pair varies from 10 to 625 ohms. I'm assuming that the key resistance is low enough that even with signal diodes in the circuit, the closed switch resistance should be enough to pull my interrupt pin and my row pins to LOW.

I suppose I could also tie all the columns and all the rows together, hook it to a voltage divider, and see if I could decode the key using an analog input. That would let me do all that decoding with a single pin.

Alternatively, are there other keypad frameworks that handle 3x4 and 4x4 keypads and offer things like repeated taps, long taps, and allow you to trigger events on ANY key press (So I could keep my LCD display awake.)

# Answer
> -1 votes
I made a simple RF remote control using a very similar method with a 4x4 kepyad, with diodes connected together to trigger an interrupt and read a keypress. After any keypress, the interrupt woke the processor (unmodified 8 MHz Promini with Atmega328P), it used keypad.h library to detect the pressed key, sent that out via a short RF burst (433 MHz transmitter) using the library (8 years ago now, drawing a blank on the name) that became the Radiohead library (find it on github), then went back to sleep. Lasts about a month on 2000mAH (or so?) LiPo battery that is secured to the bottom of the board.

As I recall, I had to write the outputs opposite of their normal state before going to sleep mode for the interrupt to work correctly, then restore them before reading the keypad.h value. Then put them back in opposite state before going back into sleep mode. Works well, but I only transmit one key at a time. I don't have complete details here, can post them when I get home later. You can see a picture of the remote at the bottom of this site - sorry about the scrolling, I managed to overwrite my index.html file that had link/tabs to jump to the various areas that my son did up for me. http://www.crossroadsfencing.com/BobuinoRev17

---
Tags: isr, keypad, demultiplex
---


# Question
Title: Power external daughter board from Arduino only powered by USB?
Been searching for an answer, but I see lots of talk about it, but not clear answers. Can somebody clarify this? If I power the Arduino only via USB, can I put a small daughter board? and power it from the Power connector(5V)

**Update:**

Thanks for the answers I'm using a Genuino UNO and it does power the daughter board my meter was kaputt, got a good one and it is fine even hooked a breadboard circuit to the 5V and GND and it works!!!

# Answer
> 0 votes
Yes. USB is limited to 500mA, the Arduino like an Uno has a 500mA fuse to protect the USB source.

The Arduino itself can use 25-50mA of that, or more depending on what you have connected to the IO pins.

---
Tags: arduino-uno, power, genuino
---


title: Access denied when Uploading

text:
# Question
Title: Access denied when Uploading
I went to upload my sketch to my Uno (r3), but unusually, the Upload Console returned this error:

```
avrdude: ser_open(): can't open device "\\.\COM4": Access is denied.

```

Just started seeing this, cannot upload.

# Answer
> 6 votes
There might be another device has already connected to that port. It could even be a terminal emulator which is left connected from last debugging session.

Otherwise, make sure that your UNO is really presented on COM4 by checking with "Device Manager". if not, change the port where it is available.

# Answer
> 1 votes
I'm using a windows 10 and had this happen randomly. I closed several other applications and it started working again.

# Answer
> 0 votes
You have selected the wrong COM port. Go to Tools -\> Port -\> Select the right port. If you do not know the port number disconnect the Arduino, open the same menu again and look what is listed there, write down if you can't remember, now plug your Arduino back in and select the option that wasn't there before.

---
Tags: arduino-uno, ide
---


# Question
Title: Can you use an Arduino to control the output current and voltage of a DC/DC converter?
I am using an arduino to create a device that outputs a specific current and voltage. I was wondering if there are any devices out there such as dc/dc buck boost converters that can be controlled by arduino to output desired powers. I am looking for something rated for at least 50 watts that can carry at least 3 amps of current.

Thank you all in advance!

# Answer
Yes, and it's actually far simpler than most realize. I've tried digitpots, but they are quite un-linear and only handle 5v, unless you spend $$$. Early on, i had soldered an LDR in parallel to a buck converter's adjustment pot, and fed that PWM. It worked to somewhat adjust the vout, but had a lot of ripple and was not linear. I had gotten an MCU-controlled linear PSU going, that wasn't too hard, but i always wanted a buck. Just recently, i've found an awesome method and built several MCU-controlled SMPSs. You don't have to have any special parts or de-solder anything!

Basically, you:

* use a buck/boost (or dual) with a built-in V-adj potentiometer.
* use a lowpass to convert the MCU's PWM output into a 0-vcc signal.
* feed smoothed PWM voltage to a unity gain opamp to buffer available current.
* create a common ground between MCU and SMPS.
* feed the buffered 0-vcc control through a resistor into the pot's wiper, ~200-1k.
* the amount of "injected" voltage will be inversely proportional to the SMPS's output voltage.

Since most SMPS's feedback is in the area of 1-2.5v, the 0-3.3/5v output of the MCU works well to provide or take away feedback from the regulator. The best part about this scheme is that output voltage regulation is maintained by the SMPS's hardware, the MCU just sets an offest. In short, you can set it to 10v via the MCU, attach a big load, and the voltage stays at 10v!

I've used this technique on the xl4005 and the xl4015, but i would imagine it would work for just about any common driver package.
> 2 votes

---
Tags: arduino-uno, power
---


# Question
Title: How to upload sensor data on pubnub IOT with JSON Format?
I am trying to send MPU9250 sensor data to Pubnub IOT platform using node mcu, but not able to do it since the sensor data is not in JSON format. I know about publishing string but don't know about variable.

About Pubnub Library - https://github.com/pubnub/arduino

This is the part which I need help in:-

```
IMU.readSensor();

PubNonSubClient *pclient = PubNub.publish(pubchannel, IMU.getAccelX_mss());

```

But above line has error so how do i send imu sensor data to pubnub? All connections are right and sensor is working since I tested it.

# Answer
> 1 votes
This is the format which helped me to upload the data successfully. I didn't knew what JSON format was and got stuck. In case if someone stumbles on a similar problem.

```
char buf[5] = {};

sprintf(buf, "\"%d\"", IMU.getAccelX_mss());

PubNonSubClient *pclient = PubNub.publish(pubchannel, buf);

```

---
Tags: wifi, nodemcu, json, iot
---


# Question
Title: How to read analog pins from a second Arduino
I've run out of analog pins on Arduino Uno and don't have time to order new parts. I've heard you can connect two Arduinos and I have access to another UNO. If I did that, could I read the analog pins of the second Uno on the first one?

I'm planning to control 7 servos with separate potentiometers.

# Answer
> 1 votes
Yes that is possible, you can even use as many Arduino's as you want and send the information to one 'master' Arduino to process the data.

What you need is a way to communicate between them. Depending on distance, speed and reliability, you can chose for Serial, I2C, SPI or more 'exotic' solutions like CAN(bus), RS485 or even wireless methods (with nRF modules).

Some have a simple protocol, for others you might have to make it yourself.

Also think of the processing, you want to do the processing on the main device, or to process as much as possible on the 'slave' Arduinos and send it to the main device.

(Btw, I talk about Master/Slaves), these are not official terms, but meant as example. For example, with CAN, you can send message from any Arduino to any other. With Serial, you can send from 1 Arduino to 1 other.

If you have 2 Arduino's, probably Serial is the easiest.

---
Tags: analogread
---


# Question
Title: How do I connect an 8x8 LED RGB matrix to an Uno?
I have this 8x8 LED RGB matrix. How do I get it connected to an Arduino Uno?

It came with no other wires/modules/connectors and has a veritable crap-ton of pins to connect.

# Answer
Because you have, unfortunately, decided to buy a product without a datasheet (and the product description can't even decide if it's common anode or common cathode!), you'll have to find a product which is similar that *has* a datasheet, and determine by experimentation if the pinout matches.

For instance, this Sparkfun LED matrix looks similar. Take a look at the datasheet for an internal schematic and manually verify the pinout.

Once you know the pinout, you can begin to figure out how to drive it. There are many ways to drive large numbers of LEDs, one of the simplest of which is a bunch of shift registers.

Getting yourself a couple of 595 SRs and playing with the matrix (hint: try and get a single colour working first, then add the others) would be a good place to start.

Alternatively, the display description says that it is compatible with "Arduino RGB LED Matrix Driver Shield". That may or may not be true, but looking at a schematic of that board would give you insight into how to drive the matrix. I believe that board uses a DM163 8x3 CC LED driver chip, which seems to be perfectly suited to drive the matrix, but buying and wiring that chip up may be non-trivial.
> 1 votes

# Answer
The idea is to use a shift register PMIC (power management ic), such as the MAX6971; you'll need a pair of them; each has 16 bits of output; if you want to really shave off a dollar, get four TPIC6C596.
> 0 votes

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


title: Arduino security

text:
# Question
Title: Arduino security
My question is how secure can I make an Arduino? The project I am working on would put the Arduino out in the public (school campus inside a trash can to sense how much trash is in it) and I want to make sure random people can't access it and mess/change the code. Any suggestions would be helpful.

It will also be connected to the network and be sending data to a database.

# Answer
> 1 votes
If I understand your question, then you want ensure, that nobody is able read and change your code to see, what are you doing and to send you fake data from that Arduino.

What are problems here:

* It can be stolen (eventually with the entire trash bin) - means no fake data and no data
* It can be vandalised/destroyed in matter of minutes (max) - again no (real/fake) data
* The arduino can be reprogrammed by normal way (via bootloader) and send fake data - you can prevent that by changing the bootloader
* Arduino can be read and reprogrammed by ISP and send fake data - you can lock it (by setting SPIEN) to prevent both reading its memory and to reprogramming it this way
* the lock can be cleaned and chip erased and reprogrammed (but not read) by Chip Erase command from High Voltage programming. You can make it more difficult, if needed pins are attached to some devices or ground/power.
* the chip can be desoldered, reprogrammed and soldered back to avoid problems with connected devices.
* also the whole Arduino can be swapped with already tampered Arduino
* another Arduino can be atached to the net to inject fake data (and maybe prevent the original from normal transfers by interference) (so it have problems with physical security)

To mess with your data (send fake) such program need to be able send data in (somehow) correct format over the net. Without source code or at least the code in Arduino the format of the data could still be sniffed from transmissions and deciphered (but it is difficult task to do) and you can employ some crytography to make it even harder (but it would eat a lot of memory and computing power from your code).

---

Well, in practical life your problem is stolen/vandalised arduino and simple attacks, which can be blocked by locking the Arduino fuses and bootloader (but you would have hard time put update there after locking it) and using some cryptography.

# Answer
> 0 votes
Software security features are not available in Arduino. However if you want to prevent people from flashing a new code to some extent, you can desolder the USB pins or use a version of Arduino like ProMini, that requires external USB connector for coding.

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


# Question
Title: Not able to convert String to Integer when receiving data from pubnub?
I did managed to upload mpu9250 sensor data on PubNub and nodeMcu but not able to use the received data to control servo

Look at the Port reading and see that servo angle is still showing '0'

Code:-

```
IMU.readSensor();
char buf[500] = {};
int imu = IMU.getAccelX_mss() * 10;

sprintf(buf, "\"%d\"", imu);

Serial.print(buf);

PubNonSubClient *pclient = PubNub.publish(pubchannel, buf);
if (!pclient) return;
PublishCracker cheez;
cheez.read_and_parse(pclient);

/** You're mostly interested in `outcome()`, and,
    if it's "failed", then `description()`.
*/

Serial.print("Outcome: "); Serial.print(cheez.outcome());
Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
Serial.print("description: "); Serial.println(cheez.description());
Serial.print("timestamp: "); Serial.println(cheez.timestamp());
Serial.print("state: "); Serial.print(cheez.state());
Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
Serial.print("IMU Reading: "); Serial.println(IMU.getAccelX_mss());

pclient->stop();

/* Wait for news. */
PubSubClient *sclient = PubNub.subscribe(subchannel);
if (!sclient) return; // error
String msg;
SubscribeCracker ritz(sclient);
while (!ritz.finished()) {
    ritz.get(msg);
    if (msg.length() > 0) {
        Serial.print("Received: "); Serial.println(msg);
        pos = msg.toInt();
        Serial.print("value of servo angle: "); Serial.println(pos);
        myservo.write(pos);
    }

}
sclient->stop();

delay(1000);

```

How do I convert a string to integer so that it can be used in servo?

# Answer
> 1 votes
This is the code which worked for me:-

```
        msg.remove(0,1); msg.remove(msg.length());
        pos = msg.toInt();
        Serial.print("value of servo angle: "); Serial.println(pos);
        myservo.write(pos);

```

I had to remove this character (" ") by using msg.remove(0,1) & msg.remove(msg.length()) that removes starting and ending string.

---
Tags: wifi, nodemcu, mpu6050, iot, imu
---


# Question
Title: Arduino should check the same way like a USB keyboard or a USB mouse, if turned on notebook is connected
I have a USB HUB and have connected to it a USB keyboard and a USB mouse. As long I have not connected a Notebook to it those devices don't turn on. 5V is always turned on! So I could charge my phone. How do they know there is no notebook connected? My Arduino is always on. I want to emulate this with an Arduino. Without the need of extra software on a notebook, the Arduino should be able to tell if a notebook is connected to the USB Hub or not. Please help.

# Answer
With Arduino Nano, you don't have control over the USB, because it is handled by the USB-to-TTL-Serial chip on the board. The MCU is to this adapter connected only with RX and TX of the Serial interface.

With Arduino Micro you could retrieve the state of the USB connection, because he MCU ATmega32u4 has a build in USB support an handles the USB connection from application (sketch).
> 1 votes

---
Tags: arduino-nano
---


# Question
Title: analogWrite is not working - while trying to control DC motor speed
I'm trying to control the speed of DC Motor using

1. Arduino R3
2. NPN Transistor (2N2222A331)
3. 10k potentiometer
4. 2M ohm resistor
5. Diode

I'm not using L298N and I'm also not using L293D.

DC motor is running, but the speed of DC motor doesn't seem to change with changes in potentiometer. Circuit seems to be alright as DC motor is running.

The code is as follows

```
int potPin = A0;
int motorPin = 9;
int potValue = 0;
int motorValue = 0;

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

void loop()
{
 potValue = analogRead(potPin);
 motorValue = map(potValue, 0, 1023, 0, 255);
 analogWrite(motorPin, motorValue);
 delay(2);
 Serial.print("potentiometer = " );
 Serial.print(potValue);
 Serial.print("t motor = ");
 Serial.println(motorValue);
}

```

Whenever I tweak the Potentiometer, I can see the relative changes from Arduino "Serial Monitor" (both Potentiometer values and Motor values), but the speed doesnt seem to change physically.

Things that I tried

1. tried different combinations of resistors(100,1k,10k,1M,2M ohm) so as to vary voltage that goes to DC Motor
2. tried to check with different Output pins like 3,5,9

Nothing works, DC motor speed isn't changing.

**this leads me - to believe that, my analogwrite isn't working. please help me understand as to what i'm i doing wrong?**

The Circuit is as follows

# Answer
Two things to test:

1. Have you tried to put an LED (and resistor to protect it) in the motor's place? If the brightness changes, your setup (Arduino+transistor) is working. If not, maybe you've killed your 2N2222 by giving it a wrong diode or something else is wrong.
2. Have you tried reducing the PWM frequency? An LED can follow a fast change, but a motor can't. Also, by turning on-off the motor less frequently you dissipate less power on your transistor and diode. A quick search gave me this: this.
> 1 votes

# Answer
Referring to this datasheet you have connected the transistor the wrong way around. Also, 1M resistor at the base is way too high. Bipolar transistors are **current amplifiers** (amplification at about 50-100 in your case) and with 1MOhm at the base there will be no current through the base at all. I would try with 2k for a beginning. I hope you have another transistor because this one seems to be broken and I'm pretty sure that it's not a fault in the analog output. If the output stage of the uC was broke there would be no reaction (at least in a correct circuit)
> 1 votes

# Answer
Well, 2M resistor to the base? If the motor is running with that, the transistor must be broken (shorted). Just try to check if the motor is running with disconnected base.

You can also check PWM output by connecting LED with resistor (no, not 2M ohms, just about 330 ohms). For the transistor 1k should be sufficient maybe little less (depends on motor current and h21e amplification coeficient).

Also there are some versions 2N2222 with emitter and collector swapped. And reversed transistor has much lower current amplification coeficient.

And I hope you are using external power supply, USB is not a good idea. Starting power is usually way too much for the overcurrent protections.

Anyways, this works for me:

```
void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  analogWrite(9, map(analogRead(A0), 0, 1023, 0, 255));
  delay(100);
}

```

2N2222A + 1k + PC FAN + 12V Fan Power supply.

Connections:
E -\> Gnd,
C -\> FAN-,
FAN+ -\> 12V,
12V GND -\> Arduino GND,
Pin 9 -\> 1k -\> B

On the Arduino side 47k trimmer and the USB
> 0 votes

---
Tags: arduino-uno, motor, potentiometer, speed
---


# Question
Title: Arduino program to scan two different rfid cards in same program ? Im using nodemcu- esp8266 , rc522 reader and Firebase
/\*My project is a Library management system using rfid cards. Im trying to generate a code wherein User first scan a book and then the record will be pushed in Issued\_Books table in Firebase . Then the user scans his id to ensure that the book will be issued on his/her id. But in my program is scanning only books id. It fails to scan users Id after that. Im a beginner so can anyone guide me? \*/

//My loop code is as following:

```
void loop() {

  if ( !mfrc522.PICC_IsNewCardPresent() ) {
    delay(50);
    return;
  }

  if ( !mfrc522.PICC_ReadCardSerial() ) {
    delay(50);
    return;
  }
String book;

  for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    book.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    book.concat(String(mfrc522.uid.uidByte[i], HEX));}
    book.toUpperCase();

    Firebase.pushString("Issued_Books/Book_rfid",book);

      Serial.println();

  if ( !mfrc522.PICC_IsNewCardPresent() ) {
    delay(50);
    return;
  }

  if ( !mfrc522.PICC_ReadCardSerial() ) {
    delay(50);
    return;
  }
  String user;

  //Serial.print("Scan your id: ");
    for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    user.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    user.concat(String(mfrc522.uid.uidByte[i], HEX));}
    user.toUpperCase();
    //Serial.print(F("Card UID: "));
    Firebase.setString("Issued_Books/Book_rfid/user_rfid",user);

    delay(3000);
}

```

# Answer
also look into sprintf to get hex formatting (I dont have these libraries so I cannot test, this is all written in stackexchange editor, so I might have a typo somewhere)

```
unsigned long startScanTime;
bool GotBookId = false, GotUserId = false;
void loop() {
GotBookId = false;
GotUserId = false;

  if ( !mfrc522.PICC_IsNewCardPresent() ) {
    delay(50);
    return;
  }

  if ( !mfrc522.PICC_ReadCardSerial() ) {
    delay(50);
    return;
  }
String book;

  for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    book.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    book.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
    book.toUpperCase();
    if(book != "")
       GotBookId = true;

    Serial.println("Got Book");

startScanTime = millis(); //timeout look to get user card
  while( !mfrc522.PICC_IsNewCardPresent() && (millis() - startScanTime < SCAN_TIMEOUT) ) {
   //do nothing but wait
  }

  if(!mfrc522.PICC_IsNewCardPresent())
  { //did not get the user id, return from loop
      return;
  }
  if ( !mfrc522.PICC_ReadCardSerial() ) {
    return; //should never hit this if library works correctly
  }
  String user;

  Serial.print("Scan your id: ");
    for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    user.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    user.concat(String(mfrc522.uid.uidByte[i], HEX));}
    user.toUpperCase();
    //Serial.print(F("Card UID: "));
    GotUserId = true;

   if(GotBookId && GotUserId){
       Firebase.pushString("Issued_Books/Book_rfid",book);
       Firebase.setString("Issued_Books/Book_rfid/user_rfid",user);
   }
}

```
> 1 votes

---
Tags: nodemcu, rfid
---


# Question
Title: Door control with Arduino and limit switches
I want to make a door with two limit switches and three buttons: one for stop and the other two for open and close. I run into a problem with the code with the start buttons and the limit switches. I can't make the code because I'm a beginner. Please can somebody help me with some code or something like that?

I'll appreciate it if you help me, because it's for my school project:)

# Answer
> 2 votes
You will need to write code to

1. Control a motor. Likely a DC motor with two way control. This can be done with four MOSFETs and several diodes or much better, one H bridge IC. Your code will need to determine which one of two lines going to the dc motor is getting connected to the positive rail, and which one to the negative/ground, or both disconnected, using the three buttons you described.
2. You will need to write code that monitors the limit switches. I would suggest you use interrupts for these. One pin goes to ground, the other goes to the Arduino interrupt pin. You can use attachInterrupt() function to write functions that execute right away. Make sure you read up on which pins on your Arduino will support interrupts.
3. You will need to stop the motor movement either directly or by throwing a switch using the interrupt (or whatever detection method you use for the limit switch).

\*one special consideration is that any variables that you use inside of interrupt functions should be marked as volatile, so `int myVar;` becomes `volatile int myVar;` \*also don't use Serial.print or millis() inside of your interrupt functions if can avoid it.

---

From here Google 'Arduino switch' and work on an implementation of limit switches separately. If you want to, Google 'Arduino Interrupts' and improve your implementation to use interrupts. Next, Google 'DC motor bidirectional control Arduino'. Work on it standalone. Once both work separately, combine into a single project.

Let me know as you go through these if you have specific questions, and I would be happy to help you learn how to build it using the components you have.

---
Tags: arduino-uno
---