title: MOSFET dimmer IR controlled

text:
# Question
Title: MOSFET dimmer IR controlled
I am trying to make a group of LED dim with PWM to a MOSFET. The code seems to work for this, but the trouble is that the IR receiver will only receive the signal to turn on the lights and then IR receivers onboard LED goes to a permanent dim state (which is suppose to be off completely). It then refuses to take input until a Arduino reset is preformed. I purchased another IR receiver and placed it in the same configuration and it work exactly as intended I could brighten the LEDS and I saw the PWM stretch on my oscilloscope with every click of my remote. The trouble is that the receiver quickly quit working at this point I think there is a problem with my circuit. I am attaching the circuit diagram in hopes that someone can help.

Thanks, Billa

```
#include <IRremote.h>

int led = 9;
int led2 = 10;
int brightness = 0;    // how bright the LED is
const int RECV_PIN = 7; //IR Receiver Pin
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
  Serial.begin(9600);
  irrecv.enableIRIn();

}

void loop() {

  analogWrite(led, brightness);
  analogWrite(led2, brightness);

  if(irrecv.decode(&results)) //this checks to see if a code has been received
{
    if(results.value == 0xFF906F) //if the button press equals the hex value 0xC284
    {
        Serial.println("Triggered U");
        brightness = brightness + 5;
    }

    if(results.value == 0xFFE01F) //if the button press equals the hex value 0xC284
    {
        Serial.println("Triggered D");
        brightness = brightness + 5;
    }

    irrecv.resume(); //receive the next value
}

  delay(100);
}

```

# Answer
The first error I see with the sketch is right under this line of code `Serial.println("Triggered D");`. You are incrementing the variable `brightness` when you probably meant to decrement it.

The second error is with your call to `analogWrite()`. This function accepts an `integer` between 0 and 255. You do not constrain the value to that range, and can see what I mean by adding this line of code `Serial.println(brightness);` right above this one `irrecv.resume();` in your sketch. Going from 0 to -5 turns the LED from off to maximum brightness. Is this what you want it to do?

The errors with your MOSFET circuit is a "General Electronics" question, and should be asked on electronics.stackexchange.com. As I mentioned in one of my comments to your question, there is a recommended format for drawing schematics.

My other comment was regarding this Q+A at EE. You won't find a consensus on exactly how to use a MOSFET there either, but the image in this answer may be helpful to you.
> 0 votes

---
Tags: led, hardware, ir, remote-control, mosfet
---


# Question
Title: How do I join two RGB ledPanel 32x64 in order to get one 64x64?
I'm making a project to make a pixelArt of 64x64 using two 64x32 RGB ledMatrix and Arduino MEGA.

This is the RGB Panel I am using.

I use ADAFruit and RGBMatrixPanel libraries in my Arduino Code and if I connect the Arduino pins to the RGB panel it works, but the problem is when I try to connect the output of the first panel to the input of the second, I saw the "same image duplicated" but with different brightness, and if I change the length of the panel seems to print random LEDs.

I know that Adafruit is thought to get a screen with max of height of 32, but I don't care, because for my purpose you can assign each pixel programmatically in order to print the proper image.

I followed this guide in order to make the connection with a panel of 64x32.

I think that I have to change my code and also my physical connections, but I don't know how, can anyone help me?

Other option that I thought was create another matrix2 instance at the same code using different PINS, but this is very weird.

This is the current connections: (I have a power supply of 5v - 10A)

This is the result that I have: (duplicated in both screens with a brighness/weird shadow in the second)

And this is the final result that I'm looking for: (this is made with two Arduino Megas)

Thanks in advance!

# Answer
First off, connecting the 2nd panel to the same output pins as the first one, you are simply sending same data to the 2nd panel, which is why you get the duplicate visuals. I'm guessing you are sending power that same way, which is why you are seeing the brightness dim.

Secondly, it's hard to read on the pics in the AliExpress listing, but the Sparkfun site had a better image, which shows an "Output" connection on the back of the panels. You need to daisy chain the 2nd panel to the first panel through this "Output" connection. This should prevent you from having to create a 2nd matrix2 and use a 2nd set of pins.

Third, having a 2nd set of pins and controlling the 2nd LED matrix can make updating the image faster. It depends on your library as well as how the LED matrix is made, so it really depends on those factors, but some LED systems are designed so there is a maximum amount of pixels that can be displayed before there's a noticeable delay in LED updated. With this amount of LED pixels, you're probably fine, but if you want fast updates and expect to expand your matrix in the future, you might want to consider driving the panels separately. I'm not saying you have to now, but if you're seeing lag, this might be a good option.
> 2 votes

---
Tags: arduino-mega, rgb-led
---


# Question
Title: Serial communication PC to Arduino using C and send via NRF
I'm trying to communicate my PC with an Arduino Mega via serial and after send the message via NRF to another Arduino.

But I don't know if the message is send correctly or if it even send the message. Because I can't debug using `Serial Monitor`. If it is opened the serial port appear as busy.

When I execute the code the TX led on the Arduino blinks, but nothing is send via NRF.

I made some tests using only the NRF between the Arduinos and it's working, but when I try using the PC - Arduino serial communication, nothing happens.

**C Code**

```
#include <stdio.h>
#include <string.h>

char arduinoPort[] = "/dev/ttyACM0";

int main() {

  char buffer[] = {'1'};
  int error = 10;
  FILE *usb_port;

  usb_port = fopen(arduinoPort, "rwb");

  if(!usb_port) {
    perror(arduinoPort);
    return 1;
  }

  //memcpy(buffer, &error, sizeof(error));
  fwrite(buffer, sizeof(char), sizeof(buffer), usb_port);

  fclose(usb_port);

  return 0;
}

```

**Arduino Code**

```
#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
#include <RF24_config.h>

RF24 radio(7, 8); // CE, CSN

uint64_t address = 0xF0F0F0F0E1LL;

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

  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
  radio.printDetails();

}

void loop() {

  if(Serial.available() > 0) {

    char byteLido = Serial.read();

    radio.write(&byteLido, sizeof(byteLido));
    delay(1000);
  }
}

```

# Answer
Working with serial in C on Linux is not as simple as opening a file and reading from it (though in *some* circumstances that can work).

You should open the file using `open()` not `fopen()`, then use `tcgetattr()` and `tcsetattr()` etc to configure the port.

For example:

```
#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>

struct termios oldsettings, newsettings;
int fd;

// This signal handler will close the port cleanly leaving
// it in the same state it started in
void sighandler(int sig) {
    if (sig == SIGINT) {
        if (fd >= 0) {
            // Restore the settings to original
            tcsetattr(fd, TCSANOW, &oldsettings);

            // Close the port
            close(fd);

            printf("Program teminated. Thank you for playing.\n");
            // Exit the program
            exit(0);
        }
    }
}

int main(int argc, char *argv) {

    // Trap CTRL-C to close the port properly
    signal(SIGINT, &sighandler);

    fd = open("/dev/ttyACM0", O_RDWR);
    if (fd < 0) {
        fprintf(stderr, "Error opening serial port: %s\n", strerror(errno));
        return 10;
    }

    // Save the settings
    tcgetattr(fd, &oldsettings);
    // Grab the current settings again to modify
    tcgetattr(fd, &newsettings);

    // Set the baud rate
    cfsetispeed(&newsettings, B9600);
    cfsetospeed(&newsettings, B9600);

    // Make it a raw port
    cfmakeraw(&newsettings);

    // Apply the settings
    tcsetattr(fd, TCSANOW, &newsettings);

    char c;
    printf("Press CTRL-C to terminate\n");

    while (read(fd, &c, 1) == 1) {
        printf("Got character 0x%02x\n", c);
    }

    fprintf(stderr, "Reception terminated: %s\n", strerror(errno));

    return 0;
}

```

No one ever said programming C was easy. It makes you appreciate just how much work the Arduino API does behind the scenes for you...

Also you need to be aware that the Arduino resets (if you use an Uno, Mega, or other board with a separate USB interface chip) when you open the serial port. You need to wait about 2 seconds after opening the port before you ever send anything, or whatever you send will be completely ignored. You can do that with:

```
sleep(2);

```

after you have opened and configured the port.
> 1 votes

---
Tags: serial, c, nrf24l01+
---


# Question
Title: Arduino communication protocol with python - beyond pyserial and Arduino example
TL;DR does someone know of a advance and reliable/redudent USB protocol for communicating between a raspberry pi and Arduino due (native port)

I am trying to learn how to build a little robot which I hope could be autonomous at some point. In terms of hardware I am using an Arduino Due and a raspberry pi 3. The former is connected to DC motors, servos, ultrasonic sensors, light sensors, etc... The pi is responsible for running the picam and sending controlles from an Xbox controller to the Arduino as well as running a django web interface. Long story short, I am trying to have python reliably communicating with the Arduino over serialusb (using the native port) but with no luck. The simple communication protocol shown in the Arduino example is too weak. I found a GitHub project named arduino-robust-serial https://github.com/araffin/arduino-robust-serial which worked at first but for reasons which are quite long to discuss here was not enough.

My question is as follows: does someone know of a reliable serial protocol around which could be used to have a raspberry pi communicating with an Arduino over usb?

I hope I'm not too vague. But looking online I'm struggling to find resources regarding Arduino which are not beginner blinking light examples.

Thx

# Answer
> 1 votes
Ok, after quite some time looking for something that would allow me to easily control an arduino with the raspberry pi, I found the FIRMATA protocol which allows one to communicate with the arduino through many languages. (a snippet from the github page for SEO purposes is shown at the end of this message).

From there I looked for through the python frameworks, and had a long chat with MrYsLab who helped me integrate the arduino Due to his pymata and pymataExpress frameworks. They work quite well and enable you to have a script that quickly and efficiently communicates with the arduino. I'm sure proper frameworks from ros.org or gobot are better. But pymata worked for me hence my answer to my own question.

1. processing
2. python
3. perl
4. ruby
5. clojure
6. javascript
7. java
8. .NET
9. Flash/AS3
10. PHP
11. Haskell
12. iOS
13. Dart
14. Max/MSP
15. Elixir
16. Modelica
17. golang
18. Qt/QML
19. Android/Kotlin
20. Smalltalk

---
Tags: serial, arduino-due, communication, python, robotics
---


# Question
Title: Breadboard arduino uno not working properly
Is there any mistake in the circuit of arduino uno on breadboard... I am using arduino uno board to program this 328p mcu and after that i remove 328p from arduino uno board and placing on breadboard as shown in circuit diagram. But mcu is not working(i.e the motors are not and other devices connected to mcu are not working) But when i connect reset,vcc,gnd pins of 328p on breadboard to arduino uno board without 328p on it then its working fine and all devices are working according to my program.. even when i connect those reset,vcc and gnd pins to reset,vcc,gnd of any usb asp programmer then also its working fine(\*even programmer is not plugged in to pc). Its very strange behavior even if i disconnect any of these reset,vcc,gnd cables then also its not working... Is there any errors in circuit...please help me out

# Answer
> 1 votes
Problem solved by adding 100nf capacitor between reset and ground.... Which enables a auto reset function after every time powering on.. from this arduino forum i got this solution

Thank you everyone

---
Tags: arduino-uno, breadboard
---


title: how to set buzzer on and off

text:
# Question
Title: how to set buzzer on and off
I have a project that require me to use magnetic contact sensor. I will put the sensor at the door. So the idea is i want every time someone open the door, the buzzer will make a sound, but it will only stay for 3 seconds. When the door is close, buzzer will do nothing and when someone open the door again, the buzzer will make a sound for 3 seconds again. That is the loop. Here is my code. Sorry it's messy. I changed it few times and it still not working like what I want.

```
const int buzzer = 13;
const int sensor = 4;

int state; // 0 close - 1 open switch

void setup()
{
  pinMode(sensor, INPUT_PULLUP);
}

void loop()
{
  state = digitalRead(sensor);

  if (state == HIGH){
    tone(buzzer,1000);
    delay(3000);
    noTone(buzzer);
  }

  else{
    noTone(buzzer);
  }

}

```

# Answer
When I have a state-machine problem such as this, I diagram it first - here's mine, based on how I understand your requirements:

Most state machines are only activated when an external event happens, so not much happens inside the state-boxes. But since your application only does this one thing, you can actually do your testing inside the states. This is the difference between between blocking- and non-blocking programming - we can afford to block (delay until something happens) because there is nothing else we have to do in the meanwhile.

And my code for the state-machine (which I haven't tested, but it compiles without error):

```
const int buzzer = 13;
const int sensor = 4;

int state; // 0 close - 1 open switch

void setup()
{
   pinMode(sensor, INPUT_PULLUP);
}

void loop()
{
   // Wait for sensor HIGH
   while( digitalRead(sensor) == LOW )
      ;

   // Sensor HIGH - Alarming
   tone(buzzer, 0.52);
   delay(3000);

   // Wait for sensor LOW
   noTone(buzzer);
   while( digitalRead(sensor) == HIGH )
      ;

   // (goes to Wait for sensor HIGH)
}

```
> 2 votes

---
Tags: arduino-nano, timers, piezo, buzzer, breadboard
---


title: NodeMCU what is my esp3286 core version

text:
# Question
Title: NodeMCU what is my esp3286 core version
How do I find out what my esp3286 core version using Arduino IDE?

# Answer
Tools Menu -\> Board -\> Boards Manager - scroll down to the core and see what version it is.
> 1 votes

---
Tags: arduino-ide, nodemcu
---


# Question
Title: one Arduino with RS485 and Ethernet shields: does this work?
I'm planning to wire a few Arduinos together via RS485, and have one of them act as a hub that collects information from the others and presents it via http on an Ethernet connection.

For instance an Aduino MKR with ETH shield and 485 shield. Can I expect these to work together? My worry is having 2 shields that potentially need lots of bandwidth, timing issues etc.

# Answer
> 1 votes
Should be no problem.

The ETH shield uses SPI to communicate with a W5500 chip. That chip does most of the network processing for you.

The 485 shield just connects to the UART TX and RX pins. It's just serial communications with a couple of control pins from there on out.

Neither use any pins that the other one uses.

---
Tags: ethernet, rs485
---


# Question
Title: Arduino IDE display DEBUG PORT Serial1 output
How can I display / capture Arduino IDE's `Serial1` output? Can I display it using `Arduino IDE` or using a script in `Python`?

This python script (courtesy of Chad G) works for the Serial:

```
#!/usr/bin/env python3

import serial
import sys

if len(sys.argv)<2:
    print("Please give serial port number")
    exit()
port=sys.argv[1]
ser= serial.Serial('/dev/ttyUSB'+port,9600,timeout=5)

while True:
    try:
    stringMe = str(ser.readline().strip())
    if len(stringMe)>3:
        print(stringMe)

    except:
    print(sys.exc_info())
    ser.close()
    exit()

```

called as (for USB0):

```
python3 Arduino/tools/multiMonitor/monitorUsb1.py 0

```

or, if I want to save to a log file:

```
python3 Arduino/tools/multiMonitor/monitorUsb1.py 0 >> Arduino/tools/multiMonitor/log/usb00.txt

```

# Answer
> 1 votes
`Serial1` (on most Arduino boards that have `Serial1`) is connected to a pair of pins on the GPIO headers and nowhere else.

To get it to your computer you will have to feed those TX and RX pins through a USB to TTL UART (FT232, CP2102, etc) adaptor.

From there on in it's exactly the same as using `Serial` but of course with a different device name.

---
Tags: arduino-ide, python
---


title: serial port through Rx and Tx want work

text:
# Question
Title: serial port through Rx and Tx want work
my serial connection prints rubbish, but it systematic, so it's not just random as you see on image 1, any help would be appreciated

other info:

the first image of the serial monitor of COM6 is my own serial connection, image nr. 2 is the serial monitor of COM4 which already uses the onboard serial to USB the last image shows how I made my own serial connection

the 2 black cables are providing around 4 volts, I know these are not necessary cause the USB already provides 5 volts and ground

and oh ye, normally the USB on the last image would be connected to my pc ofc

# Answer
You're using a USB to RS-232 adaptor. That is wrong.

RS-232 is not (electrically) the same as UART. Not only is the logic inverted, but it uses ±10V NRZ signalling.

That means that when the UART expects a 3.3V HIGH signal the adapter is sending it a -10V signal. When it's expecting a 0V LOW signal it's being sent a +10V signal.

So yes, it's gibberish - it's getting the opposite of what it expects to see - and the excess and negative voltages risk damaging your ESP. Fortunately the currents involved are usually so low that it doesn't damage it straight away, but with prolonged use you can probably kiss your ESP goodbye.

Disconnect that dongle immediately and get a proper USB to UART adapter.
> 0 votes

# Answer
Just check the code by running on all different Baud-rates (in the serial monitor) ..It should normally work on the rate u have declared in the code.
> 0 votes

---
Tags: serial, arduino-ide, esp32
---


# Question
Title: A proper way to get the roll, pitch and yaw values
TL, DR : What is the method (in terms of sensors and algorithm) to get the roll, pitch angles of an aircraft at any instant?

I am planning to build a hobby aircraft. I am so confused about which kind of sensors should I use and how to use them in order to get the roll, pitch and yaw angles of the aircraft.

I think I also have some problems understanding the concept. I consider these P, R, Y angles similar to the x,y,z coordinates as if they are able to describe the **attitude** of a body. If something in the below list contains "nonsense" arguments, please also enlighten me about them.

What I want is to be able to know at any instant:

1. What is the pitch angle of the aircraft, i.e how much degrees its nose pointing away from the horizontal plane of the earth.
2. What is the yaw angle, i.e to what direction(north, east etc) is the aircraft pointing through.
3. What is the roll angle, i.e what is the angle between aircrafts body surface ( wing to wing **x** tail to head surface ) and the horizontal plane of the earth/sky.

In some sources there is something going on as the importance of order of the application of roll, pitch and yaw. But I cannot understand why this is related.

I have used accelerometer values by inputting them into some formulas on the internet (those arctangent formulas, which everybody uses but nobody explains well) to get the roll and pitch values. However could not understand how to manipulate them in order to meet my requirements (different axis orientations of the sensor).

I also have basic understanding about what a gyroscope is.

I have an MPU6050(Accelerometer+Gyroscope).

P.S : my goal is to build a quadcopter but I guess in order to understand these concepts a fixed wing standard plane model.

# Answer
> In some sources there is something going on as the importance of order of the application of roll,pitch and yaw. But I cannot understand why this is related.

Take your right hand: point your thumb upwards, your index finger away from you, and your middle finger to the left. You now have a righthanded coordinate system: your thumb is the x axis, your index finger the y axis, and your middle finger the z axis.

First rotate +90° around the x axis (thumb). Your index finger now points to the left, and your middle finger towards you. Next, rotate +90° around the y axis (index finger). Your thumb now points away from you, your index finger to the left, and your middle finger upwards.

Now, move back to the initial position, and apply the same two rotations in a different order, first around the y axis and then the x axis: Rotate +90° around the y axis (index finger). Your thumb is now pointing to the right, your index finger away from you, and your middle finger upwards. Next, rotate +90° around the x axis (thumb). Your thumb now points to the right, your index finger upwards, and your middle finger towards you.

This is different from the last result: order of rotation matters.

> I have used accelerometer values by inputting them into some formulas on the internet(those arctangent formulas, which everybody uses but nobody explains well)

When the aircraft is moving at a constant velocity, the accelerometer just measures the acceleration due to gravity, which is a vector pointing exactly downward, (0, 0, -g) in the global coordinate system. This is always true, regardless of the orientation of the sensor.
If the sensor is perfectly level, the sensor's local coordinate system is aligned with the global coordinate system, so the sensor also measures (0, 0, -g).

When the sensor is tilted, the measured vector also has an x and y components.
To keep things simple, imagine the case where the sensor is tilted around the positive y axis.
The sensor now measures an x component as well as a z component: (x, 0, -z).

As you can see from the following image, the angle of rotation `θ = atan2(x, z)`.

The black arrow is the acceleration due to gravity, and the red and blue arrows are the x and z axes of the coordinate system of the (tilted) sensor.

---

However, accelerometer measurements are not useful for determining the orientation when the sensor is accelerating, because then the measured vector no longer points exactly downward (in the global coordinate system).

Gyroscopes measure angular velocity. By integrating the angular velocity, you get the angle.
There's one caveat: it is impossible to integrate exactly, because we only have measurements at discrete points in time. This means we have to use something like Euler's method, which is known to result in drift of the orientation estimate. To make matters worse, the measurement is noisy, and this noise is integrated as well, resulting in an even larger error.

Luckily, you can combine both imperfect measurements into a single, better orientation estimate using a sensor fusion algorithm. I've successfully used Sebastian Madgwick's algorithm for my quadcopter.
It uses the measurements of the accelerometer to minimize gyro drift.

Note that this algorithm uses quaternions instead of Euler angles (roll, pitch, yaw), because the latter suffer from gimbal lock, and because quaternions geneally require less processing power.

Also note that you cannot determine the yaw angle using the accelerometer, so you'll get some drift on that measurement.

It's a good idea to do all of your calculations using quaternions. You probably won't need Euler angles for your quadcopter, except maybe for debugging purposes.

If you want to, you can also get the quaternion from the acceleration vector directly:

```
    Quaternion quaternionFromDirection(Vec3f v) {
        /*
         * Formula:
         * q = cos(ϑ / 2) + sin(ϑ / 2)·(x·i + y·j + z·k)
         * where (x y z) is a unit vector representing the axis about which
         * the body is rotated; ϑ is the angle by which it is rotated.
         *
         * Source:
         * https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Using_quaternion_as_rotations
         *
         * The rotational axis (x y z) can be calcuated by taking the normalized
         * cross product of (0 0 1) and the given vector. The angle of rotation
         * ϑ can be found using |A×B| = |A||B|·sin(ϑ).
         */

        // First check the edge case where v == (0 0 z), i.e. vertical
        if (v.x == 0 && v.y == 0)
            return {1, 0, 0, 0};

        // Calculate the cross product and its norm.
        Vec3f cross     = {v.y, -v.x, 0};
        float crossNorm = cross.norm();
        cross /= crossNorm;

        // Calculate the angle ϑ.
        float angle = std::asin(crossNorm / v.norm());

        // Calculate the resulting quaternion.
        return {
            std::cos(angle / 2),            //
            std::sin(angle / 2) * cross.x,  //
            std::sin(angle / 2) * cross.y,  //
            std::sin(angle / 2) * cross.z,  //
        };
    }

```
> 5 votes

---
Tags: accelerometer, android, gyroscope, imu
---


# Question
Title: Why is Arduino I2C so sensitive to RFI/EMI?
I have a 2-motor robot project that uses a MP6050 for relative heading (yaw) measurements, and I'm having problems with the I2C bus when the motors are running. I have done most of the things suggested here and elsewhere; 2.2K pullups vs default, shortest possible (3cm) I2C wires, MPU6050 as far away from the motor drivers as possible, reduced I2C clock speed to 100KHz, etc, etc (for additional details, see my blog post on the subject).

So, my question is, why is the I2C bus so sensitive to RFI/EMI, especially with 2.2K pullups to +5V? Looking at the levels with my O'scope shows a 0-4.6V swing, so it's hard to believe that EMI-induced currents could be high enough across 2.2K to pull the 'high' level low enough to be considered a '0', so something else must be going on. Maybe the EMI is getting into the MPU6050 output driver circuit, causing it to turn off? If so, maybe capacitive bypasses on the I2C lines would help. Any ideas? Are other IMU modules less susceptible to motor driver EMI?

TIA,

Frank

# Answer
> 1 votes
Put a ground plate between your data lines and the power+signal lines used to drive the motor. A GPS ground plate is fine, see link below. You can just cut a piece of metal sheet to fit, or even use folded metal foil connected to ground. Motors are just noisy, and I2C is sensitive. Even updating a I2C LCD can cause noise. I like to use shielded wire (like for headphone- or HDMI cable) if my data lines are more than an inch long. You can shield lines with metal foil and heatshrink, but that’s a mess.

Use an opto-isolator to turn on your motors if a ground plate is not enough. If they only drive in one direction, add a catch diode and a 330pF cap to trim the noise. But they are probably most noisy when running. Good luck with that.

https://www.imnasa.com/en/ground-plate-200x64x12mm-for-gps-etc.html

---
Tags: motor, mpu6050
---


title: Connect 5v 30a relay with Arduino Uno

text:
# Question
Title: Connect 5v 30a relay with Arduino Uno
I have previously connected 5V 10A relay switches to my Arduino.

But for my new project I need to use a 5V 30A relay switch with my Arduino.

In 10A relay switches, we make connection with Arduino using GND, VCC and IN.

But for 30A switches, there are DC+, DC-, IN.

My question is that, how do I connect my Arduino to the relay using these pins?

# Answer
> 3 votes
From the Amazon page you linked to:

> 1 dc+ : Dc power supply positive pole
> 2 dc- :Dc power supply negative pole (i.e. ground)

Arduino:
VCC: positive DC power supply
GND: ground

technically, VCC = the voltage at the collector of a transistor, these days it's used as shorthand for the positive output pin of an IC.

---
Tags: arduino-uno, relay
---


title: Arduino DUE and 5V logic sensor?

text:
# Question
Title: Arduino DUE and 5V logic sensor?
For an application I use Arduino DUE and VNH2SP30 as the motor driver.I think this motor drive is only compatible with 5V logic but DUE provide 3.3V logic.Will my problem be solved if I use logic level shifter to convert 3.3V logic level to 5V?In the meantime, I control the speed and direction of the motor with the following code:

```
analogWrite(PWM_kare,head_analog);
digitalWrite(INB_kare, HIGH);
digitalWrite(INA_kare, LOW);

```

# Answer
> 2 votes
According to the datasheet (page 5) the "Input High Level Voltage" is 3.25V. That means that any voltage over 3.25V will count as a HIGH.

That is kind of borderline for 3.3V logic which can drop below 3.3V for a HIGH depending on load and other circumstances.

So while it *might* work off 3.3V I would say for reliable operation you should use some form of level shifting in your circuit, yes.

A simple, cheap, MOSFET-based logic level shifter will do the job - there is no need for anything fancy.

---
Tags: arduino-due
---


title: Arduino Pro Mini Serial Monitor garbage

text:
# Question
Title: Arduino Pro Mini Serial Monitor garbage
This is my first post. I hope that I am posting in the right section of the forum. Otherwise, could an admin move this topic to the appropriate section please?

Board : Arduino Pro Mini 3.3V 8MHz

Arduino IDE : 1.6.12 Arduino is powered by a FTDI Board and USB Mini-B cable from the computer USB port in the following order :

Arduino FTDI

BLK GND

GND CTS

VCC VCC

RXi TX

TXo RX

DTR DTR

Also, I have connected a HC-06 bluetooth module in the following order :

Arduino HC-06

GND GND

VCC VCC

D10 TXD

D11 RXD

The Serial Monitor is open on COM4, Newline, 9600 baud.

The code that I'm trying to run is :

```
#include <SoftwareSerial.h>
SoftwareSerial BT(10, 11);
void setup()
{
  pinMode(13, OUTPUT);
  BT.begin(9600);
  // Send test message to other device
  BT.println("Hello from BTSerial");

  Serial.begin(9600);
  Serial.println("Hello from Serial");
}

char a; // stores incoming character from other device
void loop()
{

  if (BT.available())
  // if text arrived in from BT serial...
  {
    a=(BT.read());
    if (a=='1')
    {
      digitalWrite(13, HIGH);
      BT.println("LED on");
    }
    if (a=='2')
    {
      digitalWrite(13, LOW);
      BT.println("LED off");
    }
    if (a=='?')
    {
      BT.println("Send '1' to turn LED on");
      BT.println("Send '2' to turn LED on");
    }
    Serial.println(a);
  }
}

```

I am trying to communicate with the HC-06 from an Android phone. I am posting in this section of the forum because when I send a message from the phone to Arduino the following is printed in the Serial Monitor :

```
à„…€ƒ¦¤„„‡…§¤¦„‡Å„EóAãbBãbHãb

```

When I am trying to send a message from Arduino to the phone, nothing is received on the phone.

Could someone please explain why I get garbage output on the Serial Monitor even though the baud rate is the same in the code as it is in Serial Monitor window? Is there a problem with the Arduino IDE?

**Edit 12.11.2016**

This is what I get when I open the Serial Monitor in the Arduino IDE with this code : Newline, Baud rate 9600

```
‚Æ‡¥Ç$¤†Fó

```

If I change the Serial Monitor properties to Newline, Baud rate 19200 this is what I receive :

```
Hello from Serial

```

On the Android phone application I do not get anything printed.

Also, please note that this question is also addressed on the Arduino forum at the following link : http://forum.arduino.cc/index.php?topic=434623.0 I will try and answer in both places as I am not sure that everybody has an account on the forum

# Answer
I had the same issue. The problem was solved in an other forum: https://forum.arduino.cc/index.php?topic=434623.0 I copy the solution here:

```
It appears that in fact your board is not running at 8MHz, but instead 16MHz.
Please select the correct setting for your board:
Tools > Processor > ATmega328(5V, 16MHz)
Or if it has the ATmega168:
Tools > Processor > ATmega168(5V, 16MHz)

```
> 3 votes

# Answer
Flip the RX and TX wires of the HC06. This is because this statement : `SoftwareSerial BT(10, 11);` actually means `SoftwareSerial BT(RXpin, TXpin);`. Considering this, 10 is your Rx and 11 is your Tx. In this case, you have to connect pin 10 (software Rx) of your Arduino to the Tx pin of your HC06 and pin 11 (software Tx) to the Rx pin.
> 2 votes

# Answer
> BLK GND
>
> GND CTS

That looks backwards to me. Connect GND to GND and CTS to BLK.

The bluetooth module operates at a predefined baud rate. You need to ensure that your Arduino communicates at that baud rate - you don't get to pick any old baud rate.

The baud rate can be changed with the `AT+UART=x` command (where `x` is a single digit representing the baud rate: `1=1200, 2=2400, 3=4800, 4=9600 (default), 5=19200, 6=38400, 7=57600, 8=115200, 9=230400, A=460800, B=921600, C=1382400`). If the HC-06 isn't on the default baud rate of 9600 (which is highly possible) then you will have to guess what the right baud rate is. Work through the possible ones listed there in yopur `BT.begin(...)` function to see if one of them starts working.
> 2 votes

# Answer
> Could someone please explain why I get garbage output on the Serial Monitor even though the baud rate is the same in the code as it is in Serial Monitor window? Is there a problem with the Arduino IDE?

Even if the baud of serial monitor and the code is same, there is a possibility that you have not configured your HC-06 to works on the same baud. There are many ways to check and configure it by using AT-Command. You will easily found them since many tutorial has been written, here is some of the example :
link 1
link 2
> 0 votes

---
Tags: serial, softwareserial, arduino-pro-mini, ftdi, hc-06
---


# Question
Title: Why does my code treat my sound sensor as if it's always HIGH
I have a sound sensor that was working perfectly fine as I was using it as a clap sensor to turn lights on and off. However, I tried to change the code to make it work a little smoother and for whatever reason it stopped working. I then tried to write a very simple script to allow it to turn on and off using just one clap but now it treats the sound sensor as if it's always inputting HIGH. Any ideas why this might be happening?

note: I've turned up the sensitivity and can see that the sound sensor isn't always HIGH. Even when it's too high to hear me clap it still turns the LED on and off as if the if statement below was always true.

```
int SENSOR = 2;
int LED = 13;

void setup() {
  // put your setup code here, to run once:
  pinMode(LED, OUTPUT);
  pinMode(SENSOR, INPUT);
}

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

  if(digitalRead(SENSOR) == HIGH){
    digitalWrite(LED, (digitalRead(LED) == HIGH ? LOW : HIGH));
    delay(100);
  }
}

```

This is the sound sensor module I am using: Robojax Sound Detection Microphone Module

# Answer
The robojax microphone switch I was using outputs LOW when it senses a sound rather than outputting HIGH as I assumed. The solution was just to replace all the if statements testing for a HIGH input with LOW.

note: sorry about not looking into the microphone earlier.
> 2 votes

---
Tags: arduino-uno, power, led, sound
---


# Question
Title: How can I give power to Arduino Uno using a 12V 7.5 Ah Lead-Acid battery?
I am trying to give power to my Arduino Board using a 12V 7.3 Ah Lead-Acid Battery but I am unable to do it.

I connected the battery to Arduino Uno (via DC Pin) and it worked for a couple of minutes but then, it automatically stopped working. I checked the voltage of the battery using a Multimeter from the same DC Pin which was connected with battery and board. The voltage was 12.62 volts. Then I thought my board might have been fried. So, I checked the board by connecting it with a 12V 2 Amp DC adapter and I found that my board was not fried and it was working fine with the Adaptor. The Adaptor was giving 12.48 volts voltage. Then, I again checked the board using battery but still it didn't work. I tried charging the battery via a charger but it still didn't work. I tried these steps multiple times but the results were always same.

I checked with my 12V DC Fan & some other devices also and it works perfectly, but it doesn't work with my Arduino Board. This indicates that my battery is in a good condition but not working with Arduino Board only. While Arduino is also in a good condition, working with 12V DC Adaptors but not with the Battery.

Please Help!

# Answer
The input voltage on the DC pin is specified as 7 to 12V. Your battery may well be supplying more than that, causing the voltage regulator to overheat and shut down.

> The voltage was 12.62 volts.

That is out of spec for the Arduino Uno. When you operate out of specified voltages anything can happen, and that anything may not be very good.

You could get a buck converter to lower the voltage.

Certainly a Uno should be able to run for a long time on a 7 Ah battery (provided you are supplying voltages in range for it, preferably using a buck converter or similar to make sure that a fully-charged battery does not supply too high a voltage).
> 1 votes

---
Tags: arduino-uno, battery
---


# Question
Title: LMT01 temperature sensor code does not run - need help
Apr 06, 2018, 09:52 pm

## I hope this is appropriate. I posted this question on the Arduino/Sensor site, got 42 views, but no reply.

I had no success getting help with any earlier post on this subject, so I am starting over with new code by Kevan Darrah. He is a good programmer, so the code should work, but it doesn't. I did a lot of reading and I understand how it should work, so let me spend few words explaining what I learned and maybe someone can take it from there. The LMT01 output is 0.6V to 1.6V pulses 10 usec wide, I verified this using a scope, the total number of theses pulses is proportional to the temperature. This repeats every 100 msec. This signal is input to pin D2, but that is a digital pin: High=5V, Low= 0V, but Arduino IDE does something sneaky when you use the special function "attachInterrupt(pin,ISR,Falling)" - It redirects the signal internally to pin A0N of the positive side of an Analog Comparator, and attaches to AN1 internally a stable reference voltage of 1.1V. Now the 0.6V to 1.6V pulses are exactly centered on the comparator so it puts out a perfect 1's and 0's for easy counting.

## So to repeat myself only Pin2 is attached with the LMT01 to the Arduino. Why doesn't this &!#^-thing work, it compiled and uploaded correctly. If I had a debugger on this software, moving one line at a time I could fix it myself. Code follows:

```
 //Sample Code for LMT01 Temperature Sensor
//LMT01ELPGQ1
//Kevin Darrah

//TempPins
#define pulsePin 2 //D2 on arduino D5 on esp8266 **This is the output from the LMT01

//globals for the LMT01 temp sensor
volatile unsigned int pulseCount = 0;//pulses out of the sensor
float temperatureC = 0, temperatureF = 0;//converted temperatures
float tempHIGH, tempLOW = 1000;

//functions
void pulseDetect();//interrupt function
float getTemperature();//call this to get temperature from the LMT01 - returns a float for the temperature in (C)

void setup() {
  Serial.begin(115200);
  pinMode(pulsePin, INPUT);//output from LMT01 sensor circuit

}

void loop() {
  temperatureC = getTemperature();// call getTemperature() to return temp in C
  if (temperatureC != 1000) {//returns 1000 if anything went wrong
    temperatureF = temperatureC * 9.000 / 5.000 + 32;
    if (temperatureF > tempHIGH)
      tempHIGH = temperatureF;
    if (temperatureF < tempLOW)
      tempLOW = temperatureF;
    Serial.print(temperatureC);
    Serial.print("C  ");
    Serial.print(temperatureF);
    Serial.print("F  HIGH=");
    Serial.print(tempHIGH);
    Serial.print("F  LOW=");
    Serial.print(tempLOW);
    Serial.print("F  DIFF=");
    Serial.print(tempHIGH - tempLOW);
    Serial.print("F  ");
    Serial.print(pulseCount);
    Serial.println("pulses  ");
    for (int i = 0; i < random(50, 200); i++)
      delay(1);
  }

}

float getTemperature() {// *********  GET TEMPERATURE FUNCTION *** returns the temperature C
  attachInterrupt(digitalPinToInterrupt(pulsePin), pulseDetect, FALLING);//using interrupt pin tp trigger on falling edge

  unsigned long conversionStartTime = millis();//keeps track of timing

  while (millis() - conversionStartTime < 10) { //looking for silence, in case we go to read temperature mid-measurement, ride it out till next one
   // yield();//for the ESP8266 to keep other tasks happy
    if (pulseCount > 0) {
      pulseCount = 0;
      conversionStartTime = millis();
    }
  }

  pulseCount = 0;//reset pulse count
  while (millis() - conversionStartTime < 150) {//wait for first pulse
   // yield();//for the ESP8266 to keep other tasks happy
    if (pulseCount > 0)
      break;
  }
  if (pulseCount == 0)
    return 1000;//FAIL - never got a pulse

  conversionStartTime = millis();//conversion done, so reset time
  unsigned int oldPulseCount = pulseCount;//just to help keep track of timings when pulse pin goes idle
  unsigned long pulseTime = millis();
  while (millis() - conversionStartTime < 60) { //measure pulses
   // yield();//for the ESP8266 to keep other tasks happy

    if (pulseCount != oldPulseCount) {//new pulse, so update timer
      oldPulseCount = pulseCount;
      pulseTime = millis();
    }
    else if (millis() - pulseTime > 5) {//no pulses for a while, must be done.
      break;
    }
  }
  //^^^ Stays stuck here counting pulese for 60ms

  if (pulseCount < 5) { //this is just noise, false trigger... I mean only 5 pulses, that can't be right
    return 1000;//FAIL
  }

  detachInterrupt(digitalPinToInterrupt(pulsePin));//done with the interrupt
  temperatureC = 256.000 * pulseCount / 4096.000 - 50;//conversion
  //see 7.3.2 Output Transfer Function in Datasheet

  return temperatureC;//throw the temp back
}

//change this function to look like this if using the ESP8266
//void ICACHE_RAM_ATTR pulseDetect()

void pulseDetect() {// *********  PULSE COUNTER INTERRUPT FUNCTION
  pulseCount++;
}

```

# Answer
> 2 votes
This is added 15 months after the OP but there is very little information on this sensor.

You have not included your schematics which would be useful. For this setup TI gives you four options: transistor level shifting, isolation, multiple devices to one MCU pin, and common ground with high-side signal. Kevin Darrah uses the transistor level shifting method in his videos. Please refer to the TI datasheet for connections, pages 3 and 21 are relevant in setting that up. There is also this sample code supplied with a video that shows setup using the comparator.

NOTE: Ensure you do not have your sensor reverse biased or it will not work and may wreck it. Diodes are a good idea here.

Try commenting this out:

```
if (pulseCount < 5) { //this is just noise, false trigger... I mean only 5 pulses, that can't be right
return 1000;//FAIL

```

}

I found this sensor gives very low pulse readings if you have something setup incorrectly which will come out around -50C and this line may be causing it to read a fail. If that is the case you will need to rewrite the getTemperature() function, possibly using the comparator method supplied by TI which will require you to rewire, see their training code which includes a video. TI notes the first couple of readings may be incorrect. In my code I have my function perform several throwaway tests before spitting out a reading.

TL;DR If you use the TI comparator method, you can use the digital pins for power instead of the +5VDC like they do but use a diode (needed also for multiple sensors) to isolate the sensor to prevent reverse bias. If you do this you can shut the sensor off by switching it to INPUT but be aware, OUTPUT mode goes to ground by default which can cause reverse bias and fry your sensor. Use digitalWrite(pin,HIGH) prior to switching to OUTPUT to change default behaviour to +5V rather than GND (true, the diode should protect you here but adding this line is necessary anyway so do it in this order, safety first). I needed multiple sensors in my build so this is what I found, I used the Arduino-based comparator method quite successfully.

I don't have the necessary components to connect with transistor level shifting and actually test this at the moment but you could try this code if you want. I trimmed it down, eliminated most of the ESP8266 stuff you weren't using anyway and modified the getTemperature function to resemble what I have working right now.

```
//Sample Code for LMT01 Temperature Sensor
//LMT01ELPGQ1
//Kevin Darrah
// Ben Nesbitt, 2019

// For LMT01 if using transistor method of connection

//TempPins
#define pulsePin 2 //D2 on arduino  **This is the output from the LMT01

//globals for the LMT01 temp sensor
volatile unsigned int pulseCount = 0;//pulses out of the sensor
float tempC = 0;//converted temperatures
float tempHigh = 151;
float tempLow = 151;
unsigned long timeMillis = millis();

//functions
void pulseDetect();//interrupt function

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

  pinMode(pulsePin, INPUT);//output from LMT01 sensor circuit

}

void loop() {
  timeMillis = millis();
  tempC = getTemp(pulsePin);// return temp in C

  Serial.print(tempC); Serial.print("C  ");
  Serial.print(pulseCount); Serial.println("pulses  ");

  while (millis() - timeMillis < 5000) {} // Change this for how often you want to sample the temperature.

}

float getTemp(int pin)
{
  attachInterrupt(digitalPinToInterrupt(pin), pulseDetect, FALLING);//using interrupt pin tp trigger on falling edge
  float temperature = 0;
  unsigned long timeMillis = millis();//keeps track of timing
  int counterRef = 0; // Pulse count reference

  while (millis() - timeMillis < 10) { //looking for silence, in case we go to read temperature mid-measurement, ride it out till next one
    if (pulseCount > 0) {
      pulseCount = 0;
      timeMillis = millis();
    }
  }

  pulseCount = 0;//reset pulse count
  for (int i = 0; i < 3; i++)
  {
    while(pulseCount < 1) {}  //* TI recommends aborting the first one or two tests as inaccurate

    if(pulseCount != 0){
      //Wait for counting to be complete
      counterRef = 0;
      while(pulseCount != counterRef)
      {
        counterRef = pulseCount;
        timeMillis = millis();
        while (timeMillis == millis()){}
      }
      if (i < 2)
      {
        pulseCount = 0;
      }
      else
      {
         temperature = 0.0625 * pulseCount -50; // Pulses to temperature conversion
      }
    }
  }

  detachInterrupt(digitalPinToInterrupt(pin));//done with the interrupt

  //see 7.3.2 Output Transfer Function in Datasheet

  return temperature;
}

void pulseDetect() {// *********  PULSE COUNTER INTERRUPT FUNCTION
  pulseCount++;
}

```

---
Tags: arduino-uno
---


# Question
Title: DC motor does not work using PWN or Digital pins
1. I have connected `pin 3` to a DC motor and using `analogWrite` and `DigitalWrite` to try making it start. However, nothing happens.
2. If I try to move the pin from `pin 3` to `5V` or `3.3V` the motor starts.

**Q:** What could be the problem since it does not start using pin 3 (or others). I am using `HIGH` on `digitalWrite` and `255` on `analogWrite`.

Thanks for any help!

# Answer
The Tutorial.pdf document that describes the components in the kit does not tell you what the current draw of the motor is. Chapter 10 has 2 tutorials on how to use the motor with a relay or L293D IC. This suggests to me that the motor draws a lot more current than a digital output can provide.

The tutorial using the L293D gives you the ability to vary the speed of the motor using PWM, so it would be a good place to start.

Hopefully pin 3 was not damaged by the excess current flow when the motor was attempted to be powered from it.
> 2 votes

# Answer
The digital/analog pins cannot directly source enough current to run a motor. Use the pin to control a switching device like a mosfet which then controls current flow to the motor.
> 1 votes

# Answer
You should read up on controlling motors from digital circuits and follow a tutorial until you understand the "gotchas".

You have to be careful with the pins on an Arduino and not trying to draw too much current from them. A motor very likely needs several times more current than an Arduino digital pin can provide (you should keep the current draw on an Arduino pin ≤20 mA. Your motor might well draw 10 times that much. You might have damaged or destroyed the pin you used.

Secondly, motors use inductive coils (electromagnets). Inductors have an effect called "back EMF" that causes a reverse surge of current when you remove power from them. That will also fry whatever solid state component is driving the inductor. (The Arduino pin if you're trying to drive the inductor directly, or a transistor if you're switching the current to the inductor using a transistor.) You need a "flyback diode" on the inductor to protect the circuit that drives it.
> 0 votes

---
Tags: arduino-uno, programming
---


title: arduino boolean function

text:
# Question
Title: arduino boolean function
In the following code :- The aim of code is " when push button is pressed , led is on and when push button is is pressed again led is of"

```
#define led 12
#define button 7
boolean trigger = false;
boolean previous = false;
void setup()
{
  pinMode(led , OUTPUT);
  pinMode(button , INPUT);
}
void loop()
{
  int current = digitalRead(button) ;
  if (current && !previous)
  {
    trigger = !trigger;
  }
  previous = current;
  digitalWrite(led , trigger);
}

```

My Questions are as follows:-

1. When i used digitalread(button) instead of introducing variable i.e current. LED shows abnormal behavior. Why ?
2. What is the purpose of current = previous expression. Whats its significance?
3. Also please explain the working of a code in a brief manner in a loop.
4. Why I should use Boolean instead of int?

# Answer
> 1 votes
> When i used digitalread(button) instead of introducing variable i.e current. LED shows abnormal behavior. Why ?

Likely this is because of switch bounce. The processor is very fast compared to the bounces a mechanical switch makes when operated. So the results can be unexpected. You can get around this problem in software by using a state machine. Or in hardware by using capacitors to filter out bouncing.

> What is the purpose of current = previous expression. Whats its significance?

The program is tracking the state of the switch. So you need to know the previous state of the switch to know if the state of the switch has changed.

> Also please explain the working of a code in a brief manner in a loop.

The two fixed or reserved function names in an Arduino sketch are "setup" and "loop". "setup" is called only once on boot up. And "loop" is called over and over again after "setup"is called. In "loop" the code reads that state of the button, then tests to see if the state of the button is true and the previous state is false. If it is, then toggle the variable which tracks the state of the LED. Then the code will always save the current state as the past state and turns on / off the LED according to the value tracking the state of the LED.

Now comes the tricky part. Assume the switch is perfect and does not bounce. The toggling only occurs when the switch is 1st pressed. That is because the next time through "loop" both trigger & previous are true and the test will then be false and the LED will not be toggled. Not until after the switch is released does the code reset previous to false. Now if the switch is pressed again, for only 1 iteration through "loop", the test will be true and the LED will be toggled.

This approach depends on the switch not to bounce. And is difficult to understand. Consider using a 4 state machine (button up / LED off, button down / LED on, button up / LED on, button down/ LED off) rather than this 2 state machine (button down / LED toggle, button up / LED steady).

> Why I should use Boolean instead of int?

Bools only have two states. Integers can have many states. It is less confusing and less error prone to use a variable that only has two states if that is the intent of the program.

---
Tags: arduino-uno
---


title: Can arduino-cli verify sketches?

text:
# Question
Title: Can arduino-cli verify sketches?
I'm trying to do some simple unit testing with arduino-cli in a .gitlab-ci file like so

```
variables:
  DOCKER_HOST: tcp://docker:2375

image: "docker:latest"

services:
  - docker:dind

before_script:
  - docker pull "arduino/arduino-cli:latest"
  - arduinocli(){ docker run arduino/arduino-cli:latest "$@";}

search:
  script:
    - arduinocli lib search hi

```

but instead of `arduinocli lib search hi` at the end, I want to verify my sketch. Is there a way to do this with arduino-cli?

# Answer
> 2 votes
In Arduino parlance the word "Verify" is used (erroneously) to mean "Compile the code into a binary or HEX file, but don't upload it to the board".

To compile (and thus "verify") the code just pass the `compile` command to `arduino-cli` with the board you want to compile for and the sketch you want to compile.

# Answer
> 1 votes
@Majenko's is 100 % correct. Here's my updated `.gitlab-ci.yml` for my arduino library.

```
image: ubuntu:latest

before_script:
  - apt-get update -yq
  - apt-get install -yq ca-certificates
  - apt-get update && apt-get install -y --no-install-recommends bzip2 curl unzip
  - apt-get upgrade -yq
  - curl -L -o arduino-cli.tar.bz2 https://github.com/arduino/arduino-cli/releases/download/0.3.3-alpha.preview/arduino-cli-0.3.3-alpha.preview-linux64.tar.bz2
  - tar xjf arduino-cli.tar.bz2
  - mv arduino-cli-0.3.3-alpha.preview-linux64 /usr/bin/ino
  - export APPDIR=$(ino config dump | grep --only-matching --regexp=/.*/Arduino)"/libraries/DC_motors"
  - mkdir --parents $APPDIR
  - mv ./* $APPDIR

test:
  script:
    - echo 'run a script'

compile:
  script:
    - ino core update-index
    - ino core install arduino:avr
    - ino core list
    - ino lib install "Adafruit Motor Shield V2 Library"
    - ino lib search Regexp
    - ino lib install Regexp
    - ino lib install AccelStepper
    - ino compile --fqbn arduino:avr:uno $APPDIR/examples/API

```

In case that library moves, here's the tree output of `DC_motors`

```
├── examples
│   └── API
│       └── API.ino
├── extras
│   ├── test
│   │   └── Makefile
│   └── testPython.py
├── .gitignore
├── .gitlab-ci.yml
├── keywords.txt
├── library.properties
├── README.md
└── src
    ├── MSv2.cpp
    ├── MSv2.h
    ├── MSv2Motors.cpp
    ├── MSv2Motors.h
    ├── MSv2Steppers.cpp
    ├── MSv2Steppers.h
    └── utility
        ├── MSv2Common.cpp
        └── MSv2Common.h

```

---
Tags: testing
---


# Question
Title: Sampling stereo audio at greater than 40 Hertz using arduino
I am working on a project to make a speaker with reactive lighting. I need to be able to sample stereo audio at a decent rate for songs. The `audioRead ()` function can do about `8 kHz` and I have heard you can push it up till `35 kHz` but than you can only use it for mono and you cannot use the arduino for anything else.

* Someone recommended that I use an ADC. What can it do for me?
* Is the arduino's operating speed a limitation?
* If not the arduino which other micro-controller is suitable for this purpose.

# Answer
> 3 votes
If you are only interested in getting a reading of the sound intensity, then 8 kHz may be enough. You can also convert the signal to mono using a pair of resistors. If you want the Arduino to do other stuff while taking the analog readings, then you should forego `analogRead()` and access the ADC directly. This is more involved that typical Arduino programming, as it involves configuring the ADC at low-level, in “free running mode”. In this mode the ADC operates in an autonomous way, and send you an interrupt every time a sample is ready.

I have written a program that does something similar: it samples an analog input at 9.6 kHz (104 µs per sample) an periodically sends the reading through the serial port: sound-meter.ino. You can probably adapt it for driving LEDs instead of the serial port.

# Answer
> 1 votes
The first part of the speed limitation on the Arduino is that the ADC is painfully slow. If you had a faster ADC chip then you could take analog readings faster so you can take more per second. Once you're over that threshold then the next limitation you run into is the speed with which Arduino can communicate with that ADC. So make sure you get something fast (like SPI).

---
Tags: arduino-uno, audio, adc
---


# Question
Title: L298N beeps and malfunctions when receiving certain analogWrite values
1. I created a simple circuit with an `UNO`, `L298N` and `a single motor`.
2. Wrote the following code to test controlling the speed of the motor.
3. Tested motor with `digitalWrite()` function and it works fine.
4. Tested motor with `analogWrite()` function and from `255` down to around `70` motor works at various speeds.

**Q:** But from around 70 and below, the L298N starts to beep and the motor stop spinning. Any thoughts?

```
int enr = 9;
int inr1 = 8;
int inr2 = 7;

void setup() {
 pinMode(enr, OUTPUT);
 pinMode(inr1, OUTPUT);
 pinMode(inr2, OUTPUT);
}

void loop() {
  analogWrite(enr, 71);
  digitalWrite(inr1, HIGH);
  digitalWrite(inr2, LOW);
}

```

# Answer
Ok, here is my theory what's happening:

Every motor has an amount of friction at his rotor. You need to pass enough energy to overcome this friction, or the motor will not move. When you use `analogWrite(enr, 71)` or lower, you pass only a small amount of energy to the motor, so that it cannot overcome the friction.

Now you have to understand, what `analogWrite()` really does. It does **not** output an analog voltage. Instead it generates a PWM signal. The voltage changes between HIGH and LOW level (5V and 0V in case of the Uno) at a specific frequency. The relation between HIGH time and LOW time is called duty cycle. That is, what's controlling the motor speed. So instead of supplying different voltages, we turn the motor on and off very fast. Since the rotor has a relatively big inertia (because of it's mass), it cannot react fast enough to follow these pulses. We only give it small pushes very fast. Instead it integrates over all the pulses. If the duty cycle is low (more LOW than HIGH time) only a small amount of energy is passed to the motor.

So, what is the motor doing, when it's got not enough energy to overcome the friction? It will still get little pushes very fast, but cannot actually spin. Instead the passed energy will induce vibrations in the motor, which have the frequency of the PWM signal. These vibrations can then be heard as a continuous beep.

If enough energy is passed to overcome the friction, the rotor spins correctly and does not vibrate, thus you cannot hear a beep.

**What to do now:**

The described principle applies to every motor, so cannot do much about that. You can simply go the easy way and not drive the motor with such low duty cycles. Another cause might be, that your motor likes to get a higher current to give it's full power. The L298N is quite inefficient, so you could change that to a H-bridge driver, that uses MOSFETs instead of bipolar transistors. Also maybe you can increase the voltage, that you use to drive the motor (depending on the not specified motor).

You didn't describe, how you have connected everything, so 2 other points: You cannot drive a motor from a digital pins power (since a digital output pin can only provide 40mA at max, 20mA recommended) and you should also not power a motor through the Arduino, since you might fry the voltage regulator or the protection diode. You can get away with that, when using small motors without any load, but that doesn't scale well. You should always connect the motor circuit directly with the power supply, so that the motors current does not have to flow through the Arduino.
> 2 votes

---
Tags: arduino-uno, motor, pwm, analogwrite, l298n
---


title: Faster Arduino Mega

text:
# Question
Title: Faster Arduino Mega
I am using Arduino Mega 2560 for interfacing devices such as the Maxim MAX22500E and TI ADS1241.

Now I am requiring more speed for hopefully the same coding, and I am thinking in the Arduino Due (84 MHz Clock) which is enough faster than the Arduino Mega (16MHz Clock) but imposes working with 3.3V, hence using some 3.3V 5V level conversion for every input and output.

If I want to keep the same "arduino" coding environment, is there another faster 5V processor? Or should I focus in the strategy of interfacing the 5V devices from a 3.3V processor?

# Answer
You should begin working with 3.3V. 5V is getting rarer and rarer as far as "real world" applications go.

Many devices that you have been using at 5V will also work at 3.3V (such as the MAX22500E). Running those at 3.3V will mean you don't need logic level translation.

Others, like the ADS1241, have "split power" where you can have different logic voltage (DVDD) and analog voltage (AVDD), so you just run the logic at 3.3V and the analog at 5V so you don't need a logic level translator.

For those few rare devices that have to run at 5V and don't have a 3.3V equivalent, yes you will need to use some logic level shifting.
> 8 votes

---
Tags: arduino-mega, arduino-due
---


title: Convert to and from Unix Timestamp

text:
# Question
Title: Convert to and from Unix Timestamp
What is the best way to convert between date, hours, min, seconds to Unix timestamp in milliseconds in Arduino? I need to have this conversion, since I'm using RTC (date, hours, min, secs etc) and communicating Unix timestamp over BLE

I found some snippet of codes online, but have not tested it extensively yet.

```
  byte second = epoch%60; epoch /= 60;
  byte minute = epoch%60; epoch /= 60;
  byte hour   = epoch%24; epoch /= 24;

  unsigned int years = epoch/(365*4+1)*4; epoch %= 365*4+1;
  unsigned int year;
  for (year=3; year>0; year--)
  {
      if (epoch >= days[year][0])
          break;
  }

  unsigned int month;
  for (month=11; month>0; month--)
  {
      if (epoch >= days[year][month])
          break;
  }

  year  = years+year;
  month = month+1;
  unsigned int day   = epoch - days[year][month]+1;

  unsigned int weekday  = (dayOfMonth += month < 3 ? year-- : year - 2, 23*month/9 + dayOfMonth + 4 + year/4- year/100 + year/400)%7;

```

And to convert to Unix timestamp:

```
unsigned long epoch = (((year/4*(365*4+1)+days[year%4][month]+dayOfMonth)*24+hour)*60+minute)*60+second;

```

Are there any library in Arduino that implement this? I would trade off reliability over size of the program.

# Answer
I think that the two most used libraries are the Adafruit RTClib and the pjrc.com TimeLib. They both have functions to convert the epoch, and they both are reliable. But both lack the timezone and the DaylightSavingTime. I think you find the pjrc.com TimeLib just slightly more suitable to handle the epoch time (which is a 32-bit unsigned long defined as 'time\_t').
> 7 votes

# Answer
There is a standard way of doing those conversions in C, which is through the functions defined in `<time.h>`. This API being standard, you can test it in your computer. Recent versions of the avr-libc support this: see time.h in avr-libc. These functions can handle local time if you provide a function implementing the DST rules: see `set_dst()`. Examples are provided for US and EU rules.
> 2 votes

# Answer
Here's an example to convert seconds (Unix time) to Date & Time using TimeLib.h:

```
#include <TimeLib.h>

unsigned long offset_days = 3;    // 3 days
unsigned long t_unix_date1, t_unix_date2;

void setup() {
  Serial.begin(115200);
  t_unix_date1 = 1564398600;
  Serial.print("t_unix_date1: ");
  Serial.println(t_unix_date1);
  offset_days = offset_days * 86400;    // convert number of days to seconds
  t_unix_date2 = 1564398600 + offset_days;
  Serial.print("t_unix_date2: ");
  Serial.println(t_unix_date2);
  printf("Date1: %4d-%02d-%02d %02d:%02d:%02d\n", year(t_unix_date1), month(t_unix_date1), day(t_unix_date1), hour(t_unix_date1), minute(t_unix_date1), second(t_unix_date1));
  printf("Date2: %4d-%02d-%02d %02d:%02d:%02d\n", year(t_unix_date2), month(t_unix_date2), day(t_unix_date2), hour(t_unix_date2), minute(t_unix_date2), second(t_unix_date2));
}

void loop() {

}

```
> 1 votes

---
Tags: time, rtc, data-type
---


title: Reading from EEPROM and combining

text:
# Question
Title: Reading from EEPROM and combining
I'm trying to read from the EEPROM and combine the information and send it out over SoftwareSerial using write() function but i'm getting the following error

```
error: invalid operands of types 'const char [3]' and 'const char*' to binary 'operator+'

```

---

```
void loop()
{
  const char* eTest1 = EEPROM.read(1);
  const char* eTest2 = EEPROM.read(2);
  const char* eTest3 = EEPROM.read(3);

  char combinedVal[] = eTest1+":"+eTest2+":"+eTest3;
  bluetooth.write(combinedVal);
}

```

# Answer
You cannot use the + operator for that.

However, since EEPROM.read only returns one byte and not a string, you can do a much easier implementation:

```
void loop()
{
  char result[] = "1:2:3";
  for (int item = 0; item < 3; item++)
  {
    result[item * 2] = EEPROM.read(1 + item);
  }
}

```

This first create a string "1:2:3", where the digits are overwritten in the for loop by that item. Note that the digits in the string do not matter, it's just some free 'comment', it also should work when using "x:x:x".
> 3 votes

---
Tags: serial, softwareserial, eeprom
---


# Question
Title: Burn bootloader into Arduino UNO from Arduino Duemilanove
I have been working with my **Arduino UNO** for 2-3 hours and after that it was not possible to load sketchs into the board since it returns a

> "avrdude: stk500\_recv(): programmer is not responding" error.

* The internal led "L" of the board is permanently on.

After a little research I guess that the bootloader was corrupted at some point (I still don't understand when and how).

**Q:** Apart from this board I have an **Arduino Duemilanove** board and I would like to know if it is possible to use this Duemilanove board to burn the bootloader in the broken board, is this possible? in afirmative case, how?

Since all the examples over there shows how to do it with the same board and not with a different one.

# Answer
Yes, Nick Gammon has a page on doing that here https://www.gammon.com.au/bootloader
> -1 votes

---
Tags: arduino-uno, arduino-duemilanove
---


title: SPI Wiring Confusion

text:
# Question
Title: SPI Wiring Confusion
I am currently trying to learn about SPI and how it works on the Arduino. I want to wire a MAX7219 chip to it to drive an 8x8 LED matrix with. Normally, I would assume the wiring from Arduino to MAX7219 goes:

* PIN 10 SS -\> CS
* PIN 11 MOSI -\> DIN
* PIN 13 SCK -\> CLK

And indeed, this answer confirms my assumption. However, after going through some other resources and guides I found some confusing and conflicting information about how the pins on the two devices should be connected.

For instance, the documentation that came with my Arduino kit has this schematic.

This tutorial I found has the same wiring.

Most surprisingly, this tutorial doesn't even use the SPI pins at all.

What perplexes me the most is the sentence

> The VCC and GND of the module go to the 5V and GND pins of the Arduino and the three other pins, DIN, CLK and CS go to any digital pin of the Arduino board.

Is this true? If yes, then what is the point of the SPI pins at all? Why are the pins wired in so many different configurations? I am really confused by this.

# Answer
SPI is a communication protocol, you can take advantage of some hardware optimizations by using the pins where that hardware is available or you can do everything *by hand* using any pin you like, with the disadvantage of a bigger and slower firmware. In certain situations, like in the presence of a shield or a library already using those pins, the SPI pins might be unavailable and you have to resort to a software solution (aka *bitbang*, as you manipulate bits to generate the proper signals), otherwise use of the hardware SPI pins is strongly advised.
> 2 votes

# Answer
> For instance, the documentation that came with my Arduino kit has this schematic.

Pins 10 through to 13 are standard SPI pins on the Uno.

* 10 (SS)
* 11 (MOSI)
* 12 (MISO)
* 13 (SCK)

I have a tutorial here. I also have a Stack Exchange reference question and answer about SPI.

---

> Most surprisingly, this tutorial doesn't even use the SPI pins at all.

It is certainly possible to "bit bang" SPI and in some cases this is desirable, for example if you have something like an SD card interface, and also want to use SPI for a display. On the page I linked, specifically at this post I describe how to bit-bang SPI.

---

> What perplexes me the most is the sentence
>
> The VCC and GND of the module go to the 5V and GND pins of the Arduino and the three other pins, DIN, CLK and CS go to any digital pin of the Arduino board.

For bit-banged SPI, yes you can use any pins.

---

> Is this true? If yes, then what is the point of the SPI pins at all?

The hardware SPI is faster and easier, and you can do other things while SPI is sending/receiving but with bit-banging it is much more timing-dependent.
> 0 votes

# Answer
This video shows a project I did with a Duemilanove, 4 MAX7219s driving 4 8x8 LED matrices, and powered via 7.5V power supply. https://www.youtube.com/watch?v=hwYqgyMc5S4

With a 9V supply, the 5V regulator overheated and shut down after some number of minutes. With 7.5V, there was no problem.

The SPI and power pins, 5V, Gnd, SCK, MOSI, go to all devices, and each chip has its own SS pin (I didn't want to deal with sending out a bunch of NOP commands to feed data thru daisy-chained chips). Data to all 4 devices is refreshed as fast as 50mS, any faster and the display got too hard to read. I think I only used SPI at 4 MHz too, I have done other projects with SCK at 8 MHz, that can send out data really fast.
> 0 votes

---
Tags: spi, max7219
---


# Question
Title: Fade In/Fade Out with multiple LED strips
I want to make a strip led application(Fade In/Fade Out).Each strip has 48 pixels.One of the strips should be red and the other should be blue.Using the for loop, I managed to fade in-fade out a small number of strips (eg 10).But when I fade in / fade out all of the 48 leds, the code behaves as if there is a "delay".I guess that's because there's a lot of data in the for loop.Is there a way to do fade in / fade out without using a for loop?

```
#include "FastLED.h"
#define NUM_LEDS_PER_STRIP 48
CRGB redLeds[NUM_LEDS_PER_STRIP];
CRGB blueLeds[NUM_LEDS_PER_STRIP];
void setup() {
FastLED.addLeds<NEOPIXEL, 6>(redLeds, NUM_LEDS_PER_STRIP);
FastLED.addLeds<NEOPIXEL, 7>(blueLeds, NUM_LEDS_PER_STRIP);
FastLED.setBrightness(0);
}

void loop() {
//fade in
for(int i=0;i<256;i=i+5) {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(i);
redLeds[j] = CRGB(255,0,0);
blueLeds[j] = CRGB(0,0,255);
FastLED.show();
}}
//fade out
for(int i=255;i>=0;i=i-5) {
for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
FastLED.setBrightness(i);
redLeds[j] = CRGB(255,0,0);
blueLeds[j] = CRGB(0,0,255);
FastLED.show();
}}
}

```

# Answer
Each change of brightness requires sending out 48 LEDs x 3 bytes/strip, = 144 bytes = 1152 bits of data. Each bit needs 2.5uS of data, so 2.88mS minimum at 400 KHz data rate. I don't know what rate FastLED.h uses, might be as fast as 800 KHz. How many strips? 2? So double that.

Each string needs all of its data sent out if any one LED changes, so you might change 1 LED, and leave 143 alone, all the data still gets sent out. That's just the way the addressable strips work.
> 1 votes

# Answer
CrossRoads already gave a likely reason for the delay (so upvoted).

One way to solve it is using one microcontroller (slave) per LED string and split the load, and using one microcontroller as master:

* Use a fast communication protocol between your current MCU (master) and the slaves (preferably small/cheap ones like Arduino Mini/Micro's), e.g. SPI which is easy to use for communication.
* To make sure they all start at the same time, you can first send all data (SPI), and at the end after all data is sent to all slaves, set on the master a GPIO high where all slaves listen to, knowing they have to start sending.
* SPI is very fast, but if you want to save communication time, you can make some smart commands (e.g. like sending a command to reset a group of bytes, or change a group of bytes by a certain value etc). Depending on what commands you want, it might be needed to store the data of all led strips on your Arduino, which can cost quite some money (see CrossRoads answer).
> 0 votes

---
Tags: arduino-mega
---


# Question
Title: Arduino powered from motor shield and USB issue
I am using an Arduino (Elegoo) Mega with Motor shield to drive a digital train set. The Motor shield is powered from a 12v 1.1 amp dc power supply and I have the Arduino plugged into my laptop via USB. I have an app which sends commands via serial to the mega which are then turned into commands for the train set and sent down the line.

When using this all of a sudden the main chip on my Arduino blew up and my Laptop seemed to blow a re-settable fuse shutting off instantly (It was dead for about 10-20 minutes then worked again).

**Would this be because something caused power to get back through the Arduino to my laptop?**

The railway will short from time to time if a locomotive derails for example.

I know there is a trace on the Motor Shield which prevents the shield powering the Arduino. I have now cut this although it says you only need to cut it if using over 12v.

# Answer
Looking at pictures of the Elegoo Mega 2560 they use a "hash fill" for the pour on the tab of the regulator, not a solid fill, and zero vias to another dissipation layer on the reverse. While this may look more funky it provides only a fraction of the heat dissipation of a solid double-layer fill, meaning the regulator is more likely to overheat. Also because this is a Chinese clone the component quality will be lower (cheaper) meaning the regulator probably doesn't have proper thermal overload protection.

So it gets too hot too easily, and **pop** your Arduino is dead as the regulator fails "short" and 12V gets pumped directly into the rest of your Arduino.

Byebye Arduino, and byebye computer (fortunately temporarily in the case of your computer).
> 1 votes

# Answer
Be careful dissing Chinese components as 'poor quality' Your TV, Phone, computer and practically any other electronic item you own has chines built components in it. Most of these items are assembled in China anyway. I agree the board design may be poor but component quality from China is fast becoming a thing of the past.
> 0 votes

---
Tags: arduino-mega, usb, arduino-motor-shield, clones
---


title: Reset NodeMCU master from Arduino slave

text:
# Question
Title: Reset NodeMCU master from Arduino slave
I designed a PWS (personal weather station) which will be placed in a difficult to access location. In case of the master crashing and not requesting from the slave for a certain amount of time (stay alive protocol), is it possible to reset the master from the slave by powering a digital pin?

Note, I improvised a pull down circuit so that the Arduino Nano's D7 (or any other digital pin) 5V output could be pulled down to 3.3V.

# Answer
There is no need for a voltage divider or a level conversion on the reset pin of the esp8266. The esp8266 has internal pull-up on reset pin. To reset the esp8266 the reset pin must be connected to ground for a very short moment.

To pull the reset pin LOW with pin of the other MCU we do:

```
void resetEsp() {
  pinMode(ESP_RESET_PIN, OUTPUT);
  delay(1);
  pinMode(ESP_RESET_PIN, INPUT);
}

```

ESP\_RESET\_PIN is the pin wired to reset pin of the esp8266. It is not configured in `setup()` and it is never set `HIGH` (we don't want to send 5 V to esp8266). Setting the ESP\_RESET\_PIN to `OUTPUT` connects it to ground, setting it back to `INPUT` hands the control of the line back to esp8266 reset pin's internal pull-up.
> 2 votes

# Answer
As per verification from Juraj, this would be correct wiring for his answer:
> 0 votes

---
Tags: nodemcu
---


# Question
Title: Arduino slave with 2 masters sharing the same I2C Bus?
Consider a scenario where two (or more) `master` devices (the NodeMCU's, in this case) share an `I2C bus` with one (or more) `slave` device(s), like thus:

Would this be a feasible setup? In other words, could both `masters` request (not simultaneously) from the `slave`?

# Answer
The situation you describe is called MultiMaster. It is normally done in hardware using the I2C peripheral in the MCU. However the ESP8266 doesn't have one (or if it does, it's not used), and uses bit-banging to implement I2C in software. If you can add MultiMaster functionality to the ESP8266's Wire library then possibly yes, you could do it.

Another option is to have some other communication channel between the two masters (it could be as simple as a wire with a pullup resistor - see below) so that only one master communicates at a time.

Electrically there is no problem with your setup - I2C is a fully open-drain system (or should be implemented as such - hence the pullup resistors needed on the SCL and SDA pins), so multiple devices can drive the lines at the same time. It's just that if they do you will get data corruption and communication won't happen.

---

Example: Semaphore Wire Implementation

1. Connect any two GPIO pins together with a wire. Add a pullup resistor to the wire (10kΩ should suffice).
2. Both GPIO pins are set to INPUT.

When a master wants to send it first reads the GPIO pin:

* If it is HIGH then it is "clear to send". So it sets the GPIO to OUTPUT and pulls the line LOW.
* If it is LOW then it waits for a random amount of time and tries again.

Once communication is finished the master sets the GPIO pin to INPUT again.
> 6 votes

# Answer
Changed diagram after comments and accepted answer:
> 1 votes

---
Tags: arduino-uno, arduino-nano, i2c, nodemcu
---


# Question
Title: Is there a way to play sounds from an Arduino without using a sound shield?
I would like to play a wav file (spoken words) from my Arduino. I do not want to add a sound shield. Is there a way to play a sound through an output pin? The quality does not have to be great.

# Answer
I helped someone with a similar question. The results are in my github repo at https://github.com/linhartr22/count. This example uses the PWM library and includes a reference to the article I used to learn how to convert audio files to MP3 with proper settings for the PWM libary. It plays audio through an 8 ohm speaker or a piezo buzzer connected directly to the Arduino.
> 8 votes

# Answer
The PCMAudio example shows how to play audio data via PWM. Note that you will need to access the MCU at a low level in order to do this; the Arduino libraries don't provide enough control over the hardware.
> 4 votes

# Answer
Yes, you can - see http://www.instructables.com/id/Simple-Wav-Player-Using-Arduino/

Space is quite limited, unless you use an SD card.
> 3 votes

# Answer
Yes, I did a project yesterday to play recorded voice. You don't need a speaker module.

Just connect the speaker via a resistor to one of Arduino PWM output. Then Connect a micro-sd card module. Format your micro-sd card with FAT32 Option.

Use Sample wave converter to convert your sound files and select the options as 16,000Hz Mono 8Bit. You are all done. Use tmrpcm library. It's all easy.
> 1 votes

# Answer
old post but still a good question...

Here is a tutorial for playing 8 bit 33khz audio using the Adafruit M0 Express. You can play ~60 seconds of audio from the 2MB onboard flash through the 10bit Analog out pin. https://github.com/hydronics2/SamdAudio

two other audio board solutions that offer near 16bit quality...

* Adafruit's circuit python boards itsbyitsyM0, M4, feather M0. Same as above but using the circuit python interface instead of Arduino.
* teensy3.2, teensy3.5, teensy3.6 (you can play out using the Analog pin without the audio shield but the audio shield has a nice 1/8" jack

Teensy Tutorial

Adafruit tutorial
> 0 votes

# Answer
@Hoytman i think this arduino library can help you a lot https://sensorium.github.io/Mozzi/
> 0 votes

---
Tags: analogwrite, digital, sound, digital-analog-conversion
---


# Question
Title: NodeMCU Exception 28 - intermitent problem
I am SOMETIMES getting `exception 28` when running a web upload (over a very unstable rural internet CPE link - wifi is fine, but feed goes on and off):

```
Decoding stack results
0x40213b8c: dns_gethostbyname at core/dns.c line 1472
0x40204d95: ESP8266WiFiGenericClass::hostByName(char const*, IPAddress&, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp line 468
0x40208d7c: HardwareSerial::write(unsigned char const*, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/HardwareSerial.h line 159
0x4020519c: WiFiClient::connect(char const*, unsigned short) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/WiFiClient.cpp line 98
0x40208fe0: Print::println(char const*) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 190
0x402040c4: uploadAgrigis(char const*) at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 360
0x40208f41: Print::write(char const*) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.h line 60
0x40208f6c: Print::println() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 178
0x40204a2b: loop() at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 258
0x402074f0: TwoWire::endTransmission() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/Wire/Wire.cpp line 151
0x40203a04: BH1750_Init(int) at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 1121
0x40209d3c: loop_wrapper() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/core_esp8266_main.cpp line 125

```

My code at line 360 is

```
if (client.connect(serverName,80)) {

```

My current strategy is to keep the wifi connection open all the time. Should I test for connection before attempting to connect to the server?

# Answer
> 1 votes
Exception 28 is, according to the exception list document:

> Access to invalid address

The most common cause is trying to read or write from/to a NULL pointer.

It *could* be because you have debugging turned on, and that debugging is trying to print something that didn't get returned properly from another function call (the call failed) - most likely looking up a host name (`hostByName()`) due to your intermittent internet connection.

This may sound counter intuitive, but try turning off debugging to see if that helps reduce the number of crashes.

---
Tags: nodemcu
---


title: Is My Motor Shield Broken?

text:
# Question
Title: Is My Motor Shield Broken?
So I am trying to work on a mini battle bot project. However, it has been a while since I have worked with my Arduino electronics. So I am going through and learning how to do each thing before putting it all together. So far I have learned how to use the IR remote and got that working. I got my brushless motor with esc working with the Arduino. Now I am trying to get my dc motors working for the wheel component. I am just trying to get one motor running from the motor shield as proof of concept essentially. So here is the run down.

I have 8xAA batteries in series with each AA running at 1.5 volts for a total of 12 volts. I have verified this with my multimeter. The dc motors need 9-18 volts to run, so 12 should have it running. However, I will probably step that up to 18 volts for maximum power and run 4 dc motors since I am guessing my project will be a little heavy, so I need as much power as possible. I have the 8xAA batteries connected correctly with positive to the positive and negative to negative on the motor shield. I have checked my soldering connection and the pins are not bent and it looks straight and good. I made sure I firmly pressed down to get it onto the Arduino. Motor is connected to m2 as per the code. I don't understand why this isn't working as it should work. I have tried using this form: Why is my Adafruit motor shield not spinning my motors?

And that did not solve it. I originally was using a 9 volt battery but that form told me to use more than 9 volts and to use AA batteries, so I did that. I also checked my connections and made sure soldering is good. Here is my code:

```
#include <AFMotor.h>

// DC motor on M2
AF_DCMotor motor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor party!");

  // turn on motor #2
  motor.setSpeed(200);
  motor.run(RELEASE);
}

int i;

// Test the DC motor
void loop() {
  motor.run(FORWARD);
}

```

I have connected my motor to the battery directly and motor runs just fine. I have checked the voltage of my battery and it is great, not below the 12 volts and not above 13 volts. I have opened up serial monitor and I do see 'motor party' so I know the code is running. I looked for errors down below and saw none. The port I have checked and it is correct. Motor shield is made by Adafruit. I do have the correct library installed, in fact I just installed it today so I have up to date library. The lights on the Arduino light up and the light indicating power on the motor shield also light up when my AA batteries are plugged in. When I plug it in, lights light up but motor doesn't run. Here are a few pictures.

https://i.stack.imgur.com/cSo3x.jpg

I am have a hard time figuring this out, so if anyone can help me, thanks in advance.

# Answer
The commands you are using don't match the ones listed for this board. Here is the AF Documentation for the Motor Shield Board V2.

Try

```
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *motor = AFMS.getMotor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor party!");

  // turn on motor #2
  AFMS.begin();
}

int i;

// Test the DC motor
void loop() {
  motor->run(FORWARD);
}

```

Note: In this library, getMotor() returns creates a pointer; so, you have to use "-\>" rather and "." to access the motor run() method.
> 2 votes

# Answer
As noted by markshancock, you are using an older version of the Adrafruit Motor Shield library meant for the version 1 of the board (you have the version 2.3), and according to their forum they are not compatible (they use different communication protocols) use the newer version of the library https://forums.adafruit.com/viewtopic.php?f=31&p=276888
> 3 votes

---
Tags: arduino-uno, programming, motor, adafruit, arduino-motor-shield
---