# Question
Title: Can I run more than 2 servo motors smoothly, connecting their power to regulated limit voltage and signal wires to the digital pins of the arduino?
Now my next project is going to be about Servo Motors and for that, I don't want to buy any shield or motor driver for Servos. So I have designed a circuit, to drive 12 servos at a time without any interruptions. I haven't got any Servos yet, well my order is shipped already...Keeping that aside lets head down to the connection..

The Screenshot was taken from a circuit designed by me at tinkercad.com.

Parts:

1. HiWatt Battery (Standard 9 volts battery blue and white coloured)
2. SG90 Servo Motor
(6v 400mah max) (Resistance of each of them is 1.4kohm, when connected power and ground of multimeter)
3. Arduino (Required amp is 40\*12)

The circuit Explanation:

1. The Orange wires of servos are signal wires connected to the pins of Arduino.
2. A 750 ohm resistor is connected to the positive terminals of each motor, from which, voltage is regulated for the motor.
3. The motor grounds have been connected to the ground of the battery.
4. Ground of Arduino has been connected to the ground terminal of the battery. So now, ground of the battery and the Arduino is same.
5. All the motors are connected in parallel connections with 750 ohm resistors at the positive terminal of each motors

So now my question is, How many servos will I be able to run when I power them parallel-ly using a standard 9 volts battery (HI-WATT, Blue and white one), if no, Which will be the best battery for doing it?

I need to run 12 Servos uninteruptedly.

Thanks for your precious time....

# Answer
> 3 votes
> So now my question is, How many servos will I be able to run when I power them parallel-ly using a standard 9 volts battery (HI-WATT, Blue and white one), if no, Which will be the best battery for doing it?

Unfortunately: Zero motors with your current circuit. Maybe one motor with a better circuit and the same battery. Here is the explanation.

* You should ditch the standard 9V block battery. These batteries are made for low power applications (like IR remotes or smoke sensors) and cannot provide enough current for driving all those motors. They might be able to drive one servo, but still will be drained very fast. You should use a battery, that can provide much more current. Which battery you choose also depends on your other requirements. A series of AA alkaline batteries can give you enough current. Or you can directly buy a LiIon or LiPo rechargeable battery (including a fitting charger board). They can provide way enough current.
* You cannot just use simple resistors as voltage regulators. That just doesn't work for loads, that can draw a changing amount of current (like a motor).

+ The voltage, that the motor gets, depends on the current, that the motor draws. When the motors stands still, it will draw very little current. Thus the motor is getting the full 9V in that case. As the drawn current rises, the voltage will go down, until the motor gets not enough voltage to operate correctly.
    + The resistor of 750 Ohm restricts the current draw of the motor. Even when we (for the sake of calculation) treat the motor as a short circuit, the maximum current through the resistor with 9V will be only 12mA, so way way lower than the 400mA, that you stated in your question. You won't be able to move the motor much with that little current.
    + Even if you used a smaller value, you need to be careful with the current. I guess you are using standard resistors there, which typically have a power limit of about 0.25W. These are meant for rather low current circuits. With the 400mA @ 6V, that your motors need, you are in the region of 2.4W (that is not necessary the power for the resistor, just a value for you to see the relation). You can easily burn away a little resistor that way. When you need a resistor with a higher power limit, you need to buy one, which can handle it (and these are typically multiple times the size of a standard "signal" resistor and still can get very hot, when used in the realm of their power limit).

Instead you should buy a proper voltage regulator. At that current, buy a switching buck regulator, as they are way more efficient than linear regulators. Which regulator you need to buy also depends on the voltage of the battery, that you choose. Be sure to buy a regulator, that can provide significantly more current, than we need in total for your circuit. This is important, because regulators are typically described with a maximum current, at which they already need extra measures for cooling. When you stay well below that, you can avoid thinking about fitting cooling for it.

---

> So , will it control the motors as good as 16 channel servo drivers?

Yes, it can. Though you need to think about how you are controlling the servos on the Arduino. The standard `Servo` library supports up to 12 servos with one timer. When you can change the library to use 2 Timers for supporting more servos, then you have it. You could also try to search for other libraries, which support more servos, or write your own library. I would say, using the driver would be simpler. The driver does not switch the power for the servos. It has a chip, which can output 16 servo control signals and is controllable over an interface like I2C or SPI.

If you want to use such a driver is up to you. You might find it more important to have as few electronic parts as possible.

---
Tags: arduino-uno
---


# Question
Title: Is it possible to send 2 or more o/p signal at the same time?
I wanted run two motors using Cytron MDD10A Dual Channel motor driver. So my concern is based on execution of code that is done line by line, in that case when I'm driving two motors will this delay in output signal at the PWM pins make a difference in nature of performance i.e. for example a car wheel, in case there is such delay it'll cause one wheel to rotate prior to another which is not desired. If yes, how do I rectify the same. I also wanted to know when I use the delay function does it cause the delay in execution of the previous line or reads the upcoming line upon some 'x' seconds of delay?

Thank you for your help.

edit: code sample:

```
void FWD() {       // to move forward
    digitalWrite(m1, HIGH);  // motor 1 ON
    digitalWrite(m2, HIGH);  // motor 2 ON
    analogWrite(tm1, 225);   // tm1 assigned to a PWM pin
    analogWrite(tm2, 225);   // tm2 assigned to another PWM pin
}

```

in the above function I wish to run both analogWrite at the same time as I'm not sure how will it affect the output? I wish for the motors to start at the same time.

# Answer
> 2 votes
Technically, it is possible to start two PWM outputs at the exact same time on an Uno or Nano. If they are both controlled by the same timer, you just have to update the corresponding control register *once* with the relevant bits set to enable both channels. For example, you could start outputs 5 and 6 simultaneously, as both are on Timer 0:

```
OCR0A   = value;  // set the duty cycle on OC0A = digital 6
OCR0B   = value;  // set the duty cycle on OC0B = digital 5
TCCR0A |= _BV(COM0A1) | _BV(COM0B1);  // enable both outputs

```

If the outputs are on different timers, it is a bit more tricky. Timers 0 and 1 can be synchronized by clearing their shared prescaler with the Timer/Counter Synchronization mode active. I do not think there is a simple way to synchronize Timer 2 with any of the others.

All this is highly hardware-dependent, and not supported at all by the Arduino core library. Thus, if you want to apply any of this, you will have to study the datasheet, and poke directly into the I/O registers of the microcontroller.

But then, as Delta\_G clearly points out in his answer, all this is irrelevant to motor control. Motors are mechanical devices that have significant inertia. They take time to speed up and slow down. Just to give you a sense of scale, PWM outputs 3, 9, 10 and 11 deliver a square wave with a period of 2.04 ms. Yes, those are *milliseconds*, and this is too short for the motors to significantly change their speed within one period. Contrast this with the handful of *microseconds*, that the call to `analogWrite()` will take.

# Answer
> 1 votes
I don’t think your fear is founded. Yes technically one motor starts after the other but the amount of time would be a few microseconds at most. For perspective it takes you about 200,000 microseconds to blink your eye. You will not be able to tell. They will appear to start at exactly the same time. You would need some very sophisticated high speed cameras to see the difference in timing. It wouldn’t affect how your car moves.

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


# Question
Title: Why we are using client.flush() in the program code ,when we connect Esp8266 with internet or web server?
I am using Esp8266 Wifi modular (12-E) for controlling a led through the access of wifi/webserver. I have written code in Arduino ide taking various references from the google.In the code, I didn't understand the client.flush(), why we are using this method? In google, I have searched about many explanations, I got common to explain which I don't understand till yet. **"Waits for the transmission of outgoing serial data to complete."** I didn't get till yet. can anyone explain to me in simple terms?

/

```
/ Wait until the client sends some data

  Serial.println("new client");

  while(!client.available()){

    delay(1);

  }

  // Read the first line of the request

  String request = client.readStringUntil('\r');

  Serial.println(request);

  client.flush();

```

# Answer
This is most likely related to the *old* usage of `.flush()` from pre IDE version 1.0.0.

In those old versions `.flush()` would erase any pending data in the reception buffer. It was the equivalent of:

```
while (client.available()) {
    client.read();
}

```

Now though it's used to ensure that all data has been sent before doing anything else. In this situation it's completely meaningless.
> 0 votes

---
Tags: serial, esp8266, wifi, web-server
---


title: Analog Read dummy file

text:
# Question
Title: Analog Read dummy file
Can we use just a analog Read without storing it

i hear it it a good practice to take two reads

for better accuracy

example:

```
// Read extra analog inputs
    for (int i = 0; i < 8; i++)
{
    // Read analog pin to nothing.
        analogRead(i]); // analog-read is not writing to anything
}

// Read the analog inputs
for (int i = 0; i < length; i++)
{
    // Write the state of the analog pin to the response buffer.
    slave.writeRegisterToBuffer(i, analogRead(analog_pins[address + i]));
}

```

# Answer
how about this ?

```
// Read the analog inputs
for (int i = 0; i < length; i++)
{
    analogRead(analog_pins[address + i]); // for pre read

    // Write the state of the analog pin to the response buffer.
    slave.writeRegisterToBuffer(i, analogRead(analog_pins[address + i]));
}

```
> 1 votes

---
Tags: analogread
---


# Question
Title: Arduino Nano and 0.96 i2c oled screen not working
When I try to scan the i2c address it stays stuck on "i2c Address Scanner" which is the first line of the code. My screen is connected with VCC-5V, GND-GND, SCL- 4.7K resistor-\>A5, SDA- 4.7K resistor-\>A4. Nothing displays on screen, and I even tried without the resistors. I also tried with some 10K resistors and same result.

> Here in the picture you can see how I connected the screen to the nano. SDA-A4, SCL-A5, VCC-5V, GND-GND.

# Answer
> 1 votes
From what I am reading it is not properly connected. You are getting what I would expect. ACL of the device goes directly to A5 and a pull up resistor to +5. Same thing with SCL, connected directly, both need pull ups. You did not state what it is connected to. If there is nothing connected you will get nothing. Also the old wire library did not support timeout so you could hang indefinitely.

---
Tags: arduino-nano, i2c, display
---


# Question
Title: Connecting an Arduino Nano, Mega and LCD via I2C works but fails when shutting down Mega
I have connected an Arduino Nano, Mega and a LCD via I2C/TWI (SDA/SCL).

The Nano is playing the master while Arduino Mega and LCD are slaves. This works well till I power off the Arduino Mega. Of cause I don't expect the Mega to answer.

In particular the SCL line seems to pull-down the connection. Disconnecting SCL from the Mega will reestablish the connection to the LCD. I added two pull-up resistors 4.7k to both SDA SCL but no improvement from that.

Is there no way than physically disconnecting the lines?

# Answer
> 1 votes
See How to setup an I2C bus which stays valid if a slave is powered down or fails?

Basically I2C uses pull-ups to have all lines HIGH until any device bring it LOW. Arduino uses INPUT\_PULLUP / OUTPUT+LOW states for this. But if you switch Arduino off (turn off Vcc), internal diodes cut the power on pins to Vcc (which is zero) +diode voltage (which is small), effectively to logical LOW. And I2C see that as the device is activelly sending LOW all the time - so communication is blocked.

If you just add pullup resistors, you either have them high enought so it not prevent this state or you have them low enought to draw the lines HIGH even when there is LOW on device, which prevents other devices to draw them LOW for communication. You need "cut off" such incactive lines - either physically disconnect (pull wires from connector - such as if you just get the Mega out of socket, or use some relays powered from Mega Vcc, which disconnet them when the power goes out) or electrically disconnect - using some circuits designed for it. There are some already sold or you can create your own to the same efect (if you are skilled in this area - otherwise it is much easier and faster to pay for some already made solution)

# Answer
> 0 votes
There are I2C Multiplexers/Switches that you can use to disconnect automatically such as the PCA9540. I do not know if they are available on breakout boards.

---
Tags: i2c
---


# Question
Title: How to capture the compilaton output to a text file in Windows?
I am trying to capture the verbose output of the compilation to get it into a text file. I am using the IDE 1.8.12 running on Windows 10. I have tried looking for a right mouse button context menu, CTRL-C doesn't work, and finally in desperation, the CMD.exe trick of hitting the Enter key after selecting text.

I also went to the build folder in appdata/local/temp/arduino\_build\_nnnnn but there's nothing like that there.

There is a topic already about this but it refers to the Linux IDE which can be launched from the command line. It turns out that it's somewhat the same on Windows.

# Answer
The post Capturing avrdude command in IDE gave me the clue. Under Windows the file

`C:\Program Files (x86)\Arduino\arduino_debug.exe`

can have its output redirected to files same as a shell command.

In the CMD.exe DOS box, I executed:

`C:\Program Files (x86)\Arduino>arduino_debug.exe >\temp\logfile.txt 2>\temp\errfile.txt`

and the regular log stuff went to logfile and the errors and warnings went to errfile.

There's enough material in those two files to hurt yourself.
> 0 votes

---
Tags: arduino-ide, compilation-errors, windows
---


# Question
Title: Why I could not read the other sms's except the first SMS?
I have to read the incoming SMS on my GSM module SIM900, and I want to print the sender number and message to the serial monitor.

I first configure the GSM module with AT commands and Response() function will give me the response to AT commands.

as any SMS will be in the following pattern

+CMT: "\[Mobile number\]", "\[Date and Time\]\>" \[message body\]

So, I first extract +CMT and after that I will take mobile number and at last we have message body. The code I have used is

```
char RcvdMsg[200] = "";
int RcvdCheck = 0;
int RcvdConf = 0;
int index = 0;
int RcvdEnd = 0;
char MsgMob[15];
char MsgTxt[50];
int MsgLength = 0;

void Config() // This function is configuring our SIM900 module i.e. sending the initial AT commands
{
    delay(1000);
    Serial.print("ATE0\r");
    Response();
    Serial.print("AT\r");
    Response();
    Serial.print("AT+CMGF=1\r");
    Response();
    Serial.print("AT+CNMI=1,2,0,0,0\r");
    Response();
}

void setup()
{
    Serial.begin(9600);
    Config();
}

void loop()
{
  RecSMS();
}

void Response() // Get the Response of each AT Command
{
    int count = 0;
    Serial.println();
    while(1)
    {
        if(Serial.available())
        {
            char data =Serial.read();
            if(data == 'K')
            {
                Serial.println("OK");
                break;
            }
            if(data == 'R')
            {
                Serial.println("GSM Not Working");
                break;
            }
        }
        count++;
        delay(10);
        if(count == 1000)
        {
            Serial.println("GSM not Found");
            break;
        }
    }
}

void RecSMS() // Receiving the SMS and extracting the Sender Mobile number & Message Text
{
    if(Serial.available())
    {
        char data = Serial.read();
        if(data == '+'){RcvdCheck = 1;}
        if((data == 'C') && (RcvdCheck == 1)) {RcvdCheck = 2;}
        if((data == 'M') && (RcvdCheck == 2)) {RcvdCheck = 3;}
        if((data == 'T') && (RcvdCheck == 3)) {RcvdCheck = 4;}
        if(RcvdCheck == 4)
        {
            RcvdConf = 1;
            RcvdCheck = 0;
        }

        if(RcvdConf == 1)
        {
            if(data == '\n'){RcvdEnd++;}
            if(RcvdEnd == 3){RcvdEnd = 0;}
            RcvdMsg[index] = data;

            index++;
            if(RcvdEnd == 2){RcvdConf = 0;MsgLength = index-2;index = 0;}
            if(RcvdConf == 0)
            {
                Serial.print("Mobile Number is: ");
                for(int x = 4;x < 17;x++)
                {
                    MsgMob[x-4] = RcvdMsg[x];
                    Serial.print(MsgMob[x-4]);
                }
                Serial.println();
                Serial.print("Message Text: ");
                for(int x = 46; x < MsgLength; x++)
                {
                    MsgTxt[x-46] = RcvdMsg[x];
                    Serial.print(MsgTxt[x-46]);
                }

                Serial.println();
                Serial.flush();
            }
        }
    }
}

```

The problem of the code is

After receiving first SMS I am getting my mobile number and message body. After that I am only getting the sender number printed to my serial monitor but not the message body.

Where has it gone wrong. I could not understood.

Please help me.......Thanks in advance.

# Answer
> 1 votes
It looks like `RcvdEnd` never gets reset back to zero because `RcvdConf` is set to zero when `RcvdEnd` is 2, which means it will never get to 3 and reset it (at least not when you are expecting it to). I'm not sure how many new lines you are supposed to be checking for but the way it is set up now or is looking for two on the first message, and three for every message thereafter. You might want to rework the logic and maybe move where that value gets reset.

# Answer
> 0 votes
```
             {
                MsgTxt[x-46] = RcvdMsg[x];
                Serial.print(MsgTxt[x-46]);
            }
             RcvdEnd =0;
            Serial.println();
            Serial.flush();

```

---
Tags: arduino-uno, programming, gsm, debugging
---


# Question
Title: Determining direction from IMU accelerometer data
I am learning how to integrate sensors on arduinos and read their data.

My ultimate purpose is to place the IMU on a robot and use it in determining the robots location in an environment.

Using the following code, I am able to get accelerometer and temperature data:

```
// (c) Michael Schoeffler 2017, http://www.mschoeffler.de

#include "Wire.h" // This library allows you to communicate with I2C devices.

const int MPU_ADDR = 0x68; // I2C address of the MPU-6050. If AD0 pin is set to HIGH, the I2C address will be 0x69.

int16_t accelerometer_x, accelerometer_y, accelerometer_z; // variables for accelerometer raw data
int16_t gyro_x, gyro_y, gyro_z; // variables for gyro raw data
int16_t temperature; // variables for temperature data

char tmp_str[7]; // temporary variable used in convert function

char* convert_int16_to_str(int16_t i) { // converts int16 to string. Moreover, resulting strings will have the same length in the debug monitor.
  sprintf(tmp_str, "%6d", i);
  return tmp_str;
}

void setup() {
  Serial.begin(9600);
  Wire.begin();
  Wire.beginTransmission(MPU_ADDR); // Begins a transmission to the I2C slave (GY-521 board)
  Wire.write(0x6B); // PWR_MGMT_1 register
  Wire.write(0); // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
}
void loop() {
  Wire.beginTransmission(MPU_ADDR);
  Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) [MPU-6000 and MPU-6050 Register Map and Descriptions Revision 4.2, p.40]
  Wire.endTransmission(false); // the parameter indicates that the Arduino will send a restart. As a result, the connection is kept active.
  Wire.requestFrom(MPU_ADDR, 7*2, true); // request a total of 7*2=14 registers

  // "Wire.read()<<8 | Wire.read();" means two registers are read and stored in the same variable
  accelerometer_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x3B (ACCEL_XOUT_H) and 0x3C (ACCEL_XOUT_L)
  accelerometer_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x3D (ACCEL_YOUT_H) and 0x3E (ACCEL_YOUT_L)
  accelerometer_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x3F (ACCEL_ZOUT_H) and 0x40 (ACCEL_ZOUT_L)
  temperature = Wire.read()<<8 | Wire.read(); // reading registers: 0x41 (TEMP_OUT_H) and 0x42 (TEMP_OUT_L)
//  gyro_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x43 (GYRO_XOUT_H) and 0x44 (GYRO_XOUT_L)
//  gyro_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x45 (GYRO_YOUT_H) and 0x46 (GYRO_YOUT_L)
//  gyro_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x47 (GYRO_ZOUT_H) and 0x48 (GYRO_ZOUT_L)

//  // print out data
  Serial.print("aX = "); Serial.print(convert_int16_to_str(accelerometer_x));
  Serial.print(" | aY = "); Serial.print(convert_int16_to_str(accelerometer_y));
  Serial.print(" | aZ = "); Serial.print(convert_int16_to_str(accelerometer_z));
//  // the following equation was taken from the documentation [MPU-6000/MPU-6050 Register Map and Description, p.30]
  Serial.print(" | tmp = "); Serial.print(temperature/340.00+36.53);
//  Serial.print(" | gX = "); Serial.print(convert_int16_to_str(gyro_x));
//  Serial.print(" | gY = "); Serial.print(convert_int16_to_str(gyro_y));
//  Serial.print(" | gZ = "); Serial.print(convert_int16_to_str(gyro_z));
  Serial.println();

  // delay
  delay(1000);
}

```

Giving me output like the following:

```
aX =   3526 | aY =   -968 | aZ = -11988 | tmp = 25.89
aX =   3478 | aY =   -936 | aZ = -12020 | tmp = 25.91
aX =   3530 | aY =   -922 | aZ = -12002 | tmp = 25.91
aX =   3490 | aY =   -896 | aZ = -12006 | tmp = 25.94
aX =   3498 | aY =   -898 | aZ = -12036 | tmp = 25.91
aX =   3520 | aY =   -916 | aZ = -12050 | tmp = 25.91
aX =   3466 | aY =   -924 | aZ = -11960 | tmp = 25.91
aX =   3492 | aY =   -944 | aZ = -12026 | tmp = 25.92
aX =   3510 | aY =   -924 | aZ = -12048 | tmp = 25.91
aX =   3440 | aY =   -942 | aZ = -11980 | tmp = 25.91
aX =   3514 | aY =   -924 | aZ = -12066 | tmp = 25.91
aX =   3484 | aY =   -944 | aZ = -11968 | tmp = 25.92
aX =   3490 | aY =   -944 | aZ = -12012 | tmp = 25.92
aX =   3458 | aY =   -952 | aZ = -11944 | tmp = 25.92

```

**What I need to know is how do I determine what direction my robot is moving in based on the accelerometer output?**

# Answer
> 1 votes
You can't with any great accuracy.

The acceleration vector from the accelerometer is a combination of two things:

* Gravitational acceleration
* Acceleration due to change in the robot's velocity.

If the robot is travelling at a constant speed, there is no acceleration due to change in velocity, so the accelerometer will only be measuring gravity. No idea then how far the robot has gone.

If the robot is turning on the spot, again there is not acceleration change. So you don't know which direction the robot is facing!

You can get a rough idea of speed by integrating the acceleration, and distance by integrating speed. However any errors quickly accumulate, and thus the absolute distance may be very poor.

To get velocity (speed with a direction) or absolute position, you will need a magnetometer or gyroscope to estimate rotation.

# Answer
> 1 votes
You haven't described your robot but if it is a typical wheeled vehicle that can drive forward and backward, the accelerometer can give you one of those two directions (which is already known because you or your sketch commanded it). If in addition your robot can steer, the the accelerometer will give show a side force (aka centripetal acceleration or centrifugal force) in the direction of the turn.

Figuring out how much the robot turned (in order to get its current direction) is mathematically straight-forward but practically, it is noisy and subject to accumulating errors, as already pointed out.

If knowing orientation, thus direction of travel, is your goal, wouldn't a electronic compass (magnetometer) be of more help?

# Answer
> 0 votes
First you have to test, in which orientation the sensor on the IMU board is mounted. You can use your test sketch for this. If you don't move the sensor it will show you the gravitational force, which always points down. Orientate the IMU in such a way, that aX and aY are near zero. Now you know where up and down are. Move the IMU to the sides, until you found the direction, where only aX changes considerably, while aY is staying near zero. Then you have found the next direction.

Finally mount the IMU in your robot in the found orientation. Since you know, which of aX, aY and aZ change with which direction, you know the direction of the robots movement.

---
Tags: arduino-nano, robotics, imu
---


# Question
Title: Creating WebServer ip:port on esp8266 module
I creating Clever House with wifi. For this I'm using ESP8266 as module connected to Arduino. They communicate with SoftwareSerial. And there's a problem with global webserver on ESP8266. That I think to do it I must do this:

1.Create Webserver on another port(Neither 80 nor 443) Or Host will be in this model: https://ip:port/

2.Open port forwarding for port.

3.Almost done.

So how can I do it with AT commands?

# Answer
> 2 votes
As @Juraj mentioned, martyncurrey.com/arduino-esp8266-web-server , I need to start server with command: `AT+CIPSERVER=1,5000`, IP is IP of the esp8266 and reserve it on router or use the AT command to set static IP.

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


# Question
Title: Sim800L does not send SMS messages in a row
I created a project with sim800l that comes and stores 5 phone numbers in eeprom memory and then when a sensor is triggered, it sms all the numbers and then calls the first one. But the module does not send an SMS to everyone and only sends an SMS to the first number and then nothing else and then calls. The problem is not that the numbers are not read correctly, because when sending the text message, I said, show the number in the monitor series and it will show correctly. It is not a problem not to send a text message request because I also connected a usb to ttl module to the tx rx module and saw that it comes for all numbers and at sends the at command correctly.

```

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

#define SIM800RX 7 //D7 - SIM800L RX PIN
#define SIM800TX 8 //D8 - SIM800L TX PIN

#define SENSOR1SMSTEXT "Fire error" //Sensor 1 SMS Text
#define SENSOR2SMSTEXT "Theft error" //Sensor 2 SMS Text

SoftwareSerial SIM800(SIM800RX, SIM800TX);

String readSerial(String txt) {
  SIM800.flush();
  if (SIM800.readString() != "") {
    while (SIM800.readString() != "") {}
  }
  String text = "";
  if (txt != "") {
    SIM800.println(txt);
    int timeout = 0;
    while  (!SIM800.available() && timeout < 12000) {
      delay(1);
      timeout++;
    }
    if (SIM800.available()) {
      text = SIM800.readString();
    }
  }
  return text;
}

void readSerialOK(String txt) {
  while (readSerial(txt).indexOf("OK") == -1) {
    delay(700);
  }
}

void configSim800L() {
  readSerialOK("AT");
  delay(200);
  readSerialOK("AT+CMGF=1");
  delay(200);
  readSerialOK("AT+CNMI=1,2,0,0,0");
  delay(200);
  readSerialOK("AT+CMGDA=\"DEL ALL\"");
  delay(200);
  readSerialOK("AT+CSMP=17,167,0,0");
  delay(200);
}

void SendTextSMS(String num, String sms) {
  SIM800.print("AT+CMGS=\"");
  SIM800.print(num);
  SIM800.println("\"");
  delay(150);
  SIM800.print(sms);
  SIM800.write(26);
  delay(700);
  Serial.println("");
  Serial.print("Send SMS to:");
  Serial.print(num);
  Serial.print(":");
  Serial.println(sms);
}

bool checkPhone(String phone) {
  if (phone.substring(0, 2) == "09" && phone.length() == 11) {
    return true;
  } else {
    return false;
  }
}

void WriteEEPROM(byte part, String val) {
  int start_addw = part * 16;
  int w_len = val.length();
  EEPROM.write(start_addw, w_len + 1);
  int end_w = start_addw + w_len;
  byte len = 0;
  for (int i = start_addw + 1; i < end_w + 1; i++) {
    EEPROM.write(i, int(val[len]));
    len++;
  }
  len = 0;
  EEPROM.commit();
}

String ReadEEPROM(byte part) {
  int start_addr = part * 16;
  String str;
  int ch;
  int r_len = EEPROM.read(start_addr);
  int end_r = start_addr + r_len;
  for (int i = start_addr + 1; i < end_r; i++) {
    ch = EEPROM.read(i);
    str += char(ch);
  }
  if (checkPhone(str) == false) {
    str = "";
  }
  return str;
}

void ClearEEPROM(byte part) {
  int start_addw = part * 16;
  int w_len = 11;
  EEPROM.write(start_addw, 0);
  int end_w = start_addw + w_len;
  byte len = 0;
  for (int i = start_addw + 1; i < end_w + 1; i++) {
    EEPROM.write(i, 0);
    len++;
  }
  len = 0;
  EEPROM.commit();
}

void SendSMS(String sms) {
  String num1 = ReadEEPROM(1);
  String num2 = ReadEEPROM(2);
  String num3 = ReadEEPROM(3);
  String num4 = ReadEEPROM(4);
  String num5 = ReadEEPROM(5);
  if (num1 != "") {
    SendTextSMS(num1, sms);
  }
  if (num2 != "") {
    SendTextSMS(num2, sms);
  }
  if (num3 != "") {
    SendTextSMS(num3, sms);
  }
  if (num4 != "") {
    SendTextSMS(num4, sms);
  }
  if (num5 != "") {
    SendTextSMS(num5, sms);
  }
}

void Call() {
  String call = "";
  String num1 = ReadEEPROM(1);
  String num2 = ReadEEPROM(2);
  String num3 = ReadEEPROM(3);
  String num4 = ReadEEPROM(4);
  String num5 = ReadEEPROM(5);
  if (num1 != "") {
    call = num1;
  } else if (num2 != "") {
    call = num2;
  } else if (num3 != "") {
    call = num3;
  } else if (num4 != "") {
    call = num4;
  } else if (num5 != "") {
    call = num5;
  }
  Serial.println("");
  Serial.print("Call to:");
  Serial.print(call);
  if (call != "") {
    readSerialOK("ATD"+call+";");
    delay(300);
  }
}

void trigSensor1() {
  SendSMS(SENSOR1SMSTEXT);
  Call();
}

void trigSensor2() {
  SendSMS(SENSOR2SMSTEXT);
  Call();
}

void setup() {
  SIM800.begin(9600);
  Serial.begin(9600);
  EEPROM.begin(512);
  pinMode(IN1, INPUT_PULLUP);
  pinMode(IN2, INPUT);
  pinMode(SSS, OUTPUT);
  digitalWrite(SSS, LOW);
  while (readSerial("AT+COPS?").indexOf("+COPS: 0,0,\"") == -1) {
    delay(700);
  }
  configSim800L();
  digitalWrite(SSS, HIGH);
}

void loop() {
  if (digitalRead(IN1) == LOW) {
      trigSensor1();
  }
  if (digitalRead(IN2) == HIGH) {
      trigSensor2();
  }
}

```

Thanks if friends have experience in this area tell me.

Thanks in advance.

# Answer
> 2 votes
I find error:

```
void SendTextSMS(String num, String sms) {
  SIM800.print("AT+CMGS=\"");
  SIM800.print(num);
  SIM800.println("\"");
  delay(150);
  SIM800.print(sms);
  SIM800.write(26);
  delay(3000);
  Serial.println("");
  Serial.print("Send SMS to:");
  Serial.print(num);
  Serial.print(":");
  Serial.println(sms);
}

```

i replaced delay with 3000ms the error solved.

---
Tags: sms
---


title: Arduino timer interrupts for PID

text:
# Question
Title: Arduino timer interrupts for PID
I'm working on a robotics project where an arduino nano is acting as the motion controller. I'm trying to use a trapezoidal motion profile generator and PID loop to follow that profile, but I found out the motion was quite jerky and I assumed it's because both the motion profile and the PID run at the same speed (10ms loop using timer interrupt library)

```
#include <TimerOne.h>
void setup() {
  Timer1.initialize(10000);
  Timer1.attachInterrupt(Compute);
}

```

now I want to use two seperate loops, one running at the same 10ms interval for the profile generation and one running at 1ms for the PID (I'm not sure if the motors can actually act that quickly, but I can adjust the timings a bit), this way the PID has about 10 loops to get to the desired position accurately, reducing the jerky motion.

I'm not sure how I can set up two different interrupts using that library or by setting the flags like TCCR0A to generate the desired interrupt timers.

Here's the actual "Compute" function in case it's relevant (there are some bugs regarding the direction and it's using two different methods for generating the profile, also I'm changing it so don't think it matters, but just in case it does, I posted it)

```
void Compute(){
  int dir;
  if (setPoint > target){
    dir = 1;
  } else if (setPoint < target){
    dir = -1;
  }
  if (mode == 1) {
    target += v*dir;
    if (abs(setPoint - target) <= turningPoint){
      v -= acceleration;
    } else {
      if (v < maxV){
        v += acceleration;
      }
    }
    if (abs(target) >= abs(setPoint)){
      target = setPoint;
      mode = 0;
      v = 0;
      Serial.println("Finished!");
    }
    #ifdef DEBUG
      printDebug();
    #endif
  } else if (mode ==2){
    target += v*dir;
    if (phase == 1 and v < reachableV){
      v += acceleration;
      if (v >= reachableV){
        phase = 3;
        v = reachableV;
      }
    } else if (phase == 3){
      v -= acceleration;
      if (v <= 0){
        target = setPoint;
        mode = 0;
        v = 0;
        phase = 0;
        Serial.println("Finished!");
      }
    }
    #ifdef DEBUG
      printDebug();
    #endif
  }
  error = target- pos;
/////////////////////////////////////////////////
  PID_P = kp * error;
  if (PID_P > outMax) PID_P = outMax;
  if (PID_P < outMin) PID_P = outMin;
/////////////////////////////////////////////////
  if (abs(error) < 50){
    PID_I += ki * error * sampleTime;
  } else {
    PID_I *= 0.8;
  }
/////////////////////////////////////////////////
  PID_D = kd * (pos - lastPos) / sampleTime;
  if (PID_D > outMax) PID_D = outMax;
  if (PID_D < outMin) PID_D = outMin;
/////////////////////////////////////////////////
  output = PID_P - PID_D + PID_I;
  if (output > outMax) output = outMax;
  if (output < outMin) output = outMin;
/////////////////////////////////////////////////
  lastPos = pos;
  if (output < 0){
    digitalWrite(DIR,1);
  } else {
    digitalWrite(DIR,0);
  }
  analogWrite(PWM,abs(output));
/////////////////////////////////////////////////
}

```

p.s: I'm most likly going to use the PID library instead of trying to write my own like I currently have the code.

# Answer
Just use a single 1ms timer interrupt and count them. Every 10 interrupts do both things.

```
void interruptHandler() {
   counter++;

   // do things that happen every 1ms

   if(counter == 10) {
      // do things that happen every 10ms
      counter = 0;
   }
}

```
> 4 votes

---
Tags: arduino-nano, interrupt, timers, pid
---


# Question
Title: How to calculating requirements of power supply for a project
I am starting with electronics and been working with Arduino for some time now. I did some basic LED and servo motor project and was hoping to jump into making an obstacle-avoidance car. I used **4** AA batteries to make it, but the voltage was too low, as the motors were not moving. Then I knew about the volt requirements and all that. I also tried with a 9v alkaline battery, but it didn't help much.

Here are the electrical parts I used:

1. Arduino
2. Ultrasonic sensor
3. 4 toy motor
4. 1 hobby servo motor
5. Motor driver shield L293D
6. Battery

These are the operating voltages that I know of:

1. Arduino = 7 to 12 v
2. Hobby servo motor = 3.0V~ 7.2V
3. Toy motor = 3v ~ 12v dc; has a No load current 40 - 80 mA

Because AA batteries are of 1.5v and are in series, it has 6v, and I am assuming that was the reason it was not working as expected. What I am confused about is, how do I choose a battery or power supply to be specific.

Please forgive me for asking such a noob question. Since 1 Arduino + 4 toy motor + 1 hobby servo motor = 7v + 4 x 12v + 7v = 62 v, but I checked and I couldn't find battery that is above 15v. I surely don't understand how to pick a power supply. Could you please help me out on how to calculate and choose the right battery/power supply? Also, what to look for if for example, I want to run it for a minimum of 10 minutes?

# Answer
> 0 votes
A power supply a 9V battery is not. Since you are using batteries the L293D is a very poor choice for a driver, it uses silicon transistors which I believe are in a darlington configuration which will cause a voltage drop of from 1.4 to 2.8 volt on the motor. The 4 (or more) AA batteries will work but use a MOSFET bridge. You can always use a small SEPIC (Buck/Boost) converter to power it, that will keep the voltage constant until the batteries are exhausted. Set it to about 9V and power the arduino via the VIN input for more filtering. You will need a way of measuring voltage. You will lose less power with the converter then you are losing in your current driver.

---
Tags: arduino-uno, power, motor, battery, arduino-motor-shield
---


title: How to use PWM with DRV8870?

text:
# Question
Title: How to use PWM with DRV8870?
I'm using Arduino nano and I'm struggling working with the DRV8870 IC on PWM mode. When I use `analogWrite(_pin, duty_cycle);` the motor makes weird noises. I thought it's because of the PWM frequency so I tried to change it using `TCCR1B = TCCR1B & B11111000 | B00000011;` but it didn't work out.

Texas Instruments wrote this in their pdf: "When using PWM, switching between driving and braking typically works best. For example, to drive a motor forward with 50% of the maximum RPM, IN1 = 1 and IN2 = 0 during the driving period, and IN1 = 1 and IN2 = 1 during the other period."

drv8870\_pdf

# Answer
> 1 votes
analogWrite(\_pin, duty\_cycle) will work properly only on pins that support PWM. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11. The Arduino Due supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs. Check the following link to find yours: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

---
Tags: arduino-uno, motor, pwm, cpp
---


# Question
Title: Controlling Dynamixel MX24T, MX64T servo wirelessly using Arduino Mega?
I am planning to control multiple Dynamixel servos (MX28T or MX-64T) wirelessly using an Arduino Mega. Since this servo uses serial communication, I need an additional serial port to interface with XBee module. Although it seems to be very common application controlling these servos wirelessly based on Arduino, I could't find any of them in web. I found the two very well constructed libraries.

1. https://code.google.com/p/slide-33/downloads/list. This library is for MX28T servo, which is the same servo I am trying to use, but it uses UNO;therefore, I cannot interface with XBee.
2. The Arduino/Dynamixel Resource Page... This library uses UART1 (serial1) to interface with servo (AX-12) motors. Therefore, I can connect XBee module to UART0. But, the problem is that this library is outdated and not compatible with MX64-T servo anymore.

So my questions are:

1. Is there any one who has experience in controlling Dynamixel MX24T, MX64T servo series using XBee module simultaneously? If you have experience, please share with me.
2. Is it possible for Arduino Mega can interface with Xbee module using Serial1 (i.e., RX18 TX19)? If it can, I might be able to use the library1 without any modification.

# Answer
I know, Although it is not ZigBee, ROBOTIS Arduino Shield(https://emanual.robotis.com/docs/en/parts/interface/dynamixel\_shield/) can use BLE module (BT-410). My recommendation is Arduino compatible OpenCM 9.04(https://emanual.robotis.com/docs/en/parts/controller/opencm904/).

Arobotix-M(https://www.trossenrobotics.com/p/arbotix-robot-controller.aspx), you can use ZigBee.
> 1 votes

---
Tags: serial, servo
---


title: digitalwrite() HIGH for arduino

text:
# Question
Title: digitalwrite() HIGH for arduino
How too know whether digitalwrite(HIGH, pin\_number) sets the voltage to 5 volts or 3.3 volts. I am yet to purchase arduino uno. I want digital pin voltage to be 5 volts. I am aware that thereis a pin already have 5 volts but I want to know only about the voltage output at digital pins.

Sorry if question is too silly. I am not very knowledgable in Electronics.

# Answer
Different boards operate internally at different voltages. This is dictated by the main chip on the board. That main internal operating voltage is also the voltage at which the IO pins operate.

Most "old" Arduino boards operate at 5V. This includes, but is not limited to:

* Arduino UNO
* Arduino Mini
* Arduino Leonardo

Newer more powerful boards, many made by other companies, operate at 3.3V. Again, this includes such boards as:

* Arduino DUE
* Arduino MKR1000
* Teensy boards (v3.0+)
* chipKIT boards
* ESP8266 & ESP32 boards

Some boards come in variants that give either voltage - the most notable being the Pro Mini boards from Sparkfun. These come in both 5V and 3.3V variants and it is important to pick the right board for your needs.

In general, though:

* If it's 8-bit and runs on an ATMega chip it's likely 5V unless otherwise stated
* All 32-bit boards will be 3.3V unless otherwise stated.
> 2 votes

# Answer
When you use `digitalWrite(pin_Number,HIGH);` this sets the output pin to 5 V but still if you want to check the voltage you can you a digital multi meter set its knob to DC voltage and connect its positive to the pin and the ground pin to ground and the voltage will be displayed on the multi meter
> 0 votes

---
Tags: arduino-uno, digitalwrite
---


# Question
Title: Bluetooth module vs wireless module Arduino
My main question is, what is the main difference between HC-05 Bluetooth module and NRF24L0 wireless module?

Which should I buy?

Which makes these 2 modules different than each other?

Which one should I use in remote control arduino projects?

Which one is made for what purpose?

# Answer
> what is the main difference between HC-05 Bluetooth module and NRF24L0 wireless module?

The main difference is the protocol they use. While some attempts have been made with varying success to get the nRF24L01+ to emulate Bluetooth it is not designed for that. You can only really get rudimentary beacon mode working and that only partially.

nRF24L01+ modules can only communicate with other nRF24L01+ modules. They use their own proprietary protocol that is incompatible with any other system. That's not to say they're bad - they're great modules, and the same RF core and protocol is used in many many other devices by Nordic that are used all over the place - the most notable of which is wireless keyboards and mice.

The HC-05 though is a Bluetooth module which is designed to talk to anything else that also talks Bluetooth - such as your phone or computer. It presents an "SSP" profile and gives "master" mode operation to emulate a serial port connection between your Arduino and any other device that knows about Bluetooth and SSP.

The biggest difference in how they work though is when it comes to connecting devices together. Bluetooth devices have to be "paired" before they will communicate. nRF24L01+ devices don't. This means that getting Bluetooth devices to talk to each other takes a certain amount of time and effort, but nRF24L01+ devices are ready to go the moment they are powered on. It's then just down to your software to set up addresses and such to target the communication.

For Arduino-to-Arduino communication the nRF24L01+ is far less trouble as you set everything simply in your code. There are "LNA+PA" variant boards available that include an amplifier and antenna for longer range communication (I have had 300m+ out of those quite happily).

If you want to communicate with anything else, like your phone or computer, then you will want Bluetooth. Otherwise you will have to add an nRF24L01+ to your computer or phone through USB and (probably) another Arduino, which just gets messy.
> 3 votes

# Answer
NRF24L01+ module is a RF module and HC-05 is an Bluetooth module

It depends on the application you want to perform and what suits best for your application

nrf24l01+ is a great module but it can have issues if you want long distance communication also if you want to increase the distance then there is a module which comes with an antenna

On the other hand It seems that Hc-05 offers 10m range theoretically but according to one the arduino forum link its 15m when in line of sight but if there is some obstacle than it falls drastically

What is the distance you want to cover from the remote control it will specify which best suits you
> 0 votes

---
Tags: arduino-uno, nrf24l01+, hc-05
---


# Question
Title: How to determine what resistor value to use for LED strip
I'm trying to use an ESP8266 powered by my computer through USB cable to control a WS2812B LED strip. I've read online that you're supposed to put a resistor before the data channel to help prevent noise but I'm struggling to figure out what the resistor value should be.

I've figured out so far that the LED strip will use a MAXIMUM of 25.8W and that the Vin pin that is powering the LED strip is outputting 5V. I also plan on putting a 470uF capacitor across power and ground.

# Answer
It seems like people generally just use a resistor around 300 - 500 ohms so I'll just use a 500 ohm resistor. Answer found on another thread. And here as well.
> 2 votes

# Answer
The majority of the time adding a resistor to the data line is completely pointless. It only has an effect if the Arduino and the first WS2812B chip are connected over a long cable. By "long" I'm talking meters, not centimeters. The length of the strip of LEDs is irrelevant as each LED generates a fresh signal to send to the next LED. It's only the length of cable *between the Arduino and the LED strip that matters*.

If that is long you can get "ringing" and reflections of the signal through poorly matched impedances. The resistor is there to absorb some of those reflections and reduce the ringing by increasing the impedance of the Arduino's output.

What is a good value? Well, that's hard to say, since it's dependent on the length and type of cable in use. Too low a value and it will do nothing. Too high a value and it will "round off" your signal too much and you'll lose data. A typically chosen value that fits many situations is 220Ω.

But of course for short connections it's irrelevant and you shouldn't add a resistor.
> 2 votes

# Answer
Strips of LEDs like WS2812Bs need a high current 5V supply, with **NO** current limiting resistor.

You'll need a very high current regulated 5V supply, and would probably be better off using a separate 5V supply for the Arduino and the LED strip so you don't get large voltage fluctuations in the power to the Arduino as the LEDs turn on and off. If you do you a single power supply for both, you should use a power supply with extra capacity. I'd suggest at least a 30W supply. And yeah, you should probably have a filter capacitor on the 5V rail right at the Arduino.

## Edit:

Were you asking about a resistor on the power line, or one on the data pin?
> -1 votes

---
Tags: esp8266, resistor, ws2812
---


# Question
Title: RGB LED using potentiometer and push button
I'm currently working on an assignment which has to turn on an RGB LED using a potentiometer and button.

The problem I currently have is that the button is supposed to change the color I want the LED to display (press one time: red (pin9), press again: green (pin10), press again: blue (pin11)).

As I'm changing through the ports with the potentiometer, the potentiometer will read it with as analogWrite. For example, when I move the potentiometer all the way to the left and press the button the LED will display red, and when I move it back all the way to 0 and press the button twice the LED will stay red (do nothing). If I press it one more time it will turn off.

Another example, I turn on red again, then use green and turn off blue using the potentiometer and button giving me orange. How do I make it so to accomplish all of this while using both and combining colors?

This is a HW question. I am not asking for a whole solution but rather where to start because I already got stuck and I want to restart.

# Answer
You method sound a bit more complicated that it needs to. What I would do is have the button switch between three colors, and have the potentiometer change the brightness of the currently selected color.

For example, when first starting up, the red led is selected. Turning the potentiometer changes the brightness of the red led (in real time). Let's say you turn it 50%, so the red led is at 50% brightness. When you're happy with that, you press the button, and now green is selected. (Since the potentiometer is still at 50% from the red, the green led will immediately turn on at 50% brightness.) You can then turn the pot to change the brightness of the green led. Let's say you turn it all the way of to 0%. Then press the button to select the blue led. Turn it to 100% and the combined color would be a dark purple. Press the button again to select red again.

Here is some proof of concept code:

```

byte selectedColor = 0; // 0:red, 1:green, 2:blue
byte oldButtonState = HIGH;

void loop() {
  byte buttonState = digitalRead(buttonPin); // read the button
  if( buttonState==LOW && oldButtonState==HIGH ) // see if the button is pressed, but wasn't pressed the last time
  {
    selectedColor++; // to to next color
    if( selectedColor==3 )
      selectedColor = 0;// after blue, go back to red
  }
  oldButtonState = buttonState; // remember the buttons state for the next loop

  int brightness = map(analogRead(potPin), 0, 1023, 0, 255);

  if( selectedColor==0 )
    analogWrite(redPin, brightness);
  else if( selectedColor==0 )
    analogWrite(greenPin, brightness);
  else
    analogWrite(bluePin, brightness);
}

```

PS I left out the pinMode stuff in the `setup`.

PPS make sure the led leads are connected to PWM pin on the Arduino (they have a `~` next to them on the PCB).
> 0 votes

---
Tags: led, button, rgb-led, potentiometer
---


# Question
Title: ATMega328 functions, but will not output to any pins
## Problem:

ATMega328 Refuses to digitalWrite() to any pins, I can upload and run sketches using the board UNO from the ide on the 328 and can confirm it is working using the serial monitor (see code).

I am using this FTDI module.

## Board Manager -- UNO works, but ATMega328 Doesn't

**By using the UNO board under board manager, I am capable of writing sketches and communicating with the 328 just fine. But when I use the ATMega328 at 5.5V,16Mhz I receive the following error.**

```
         Using Port                    : COM3

         Using Programmer              : arduino

         Overriding Baud Rate          : 57600

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe0

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

```

## Code & Serial Monitor "Proving" it works

I have tried every usable PWM and other pins to attempt to output using LED's, buzzers and even other Arduino's to read inputs but none of the pins will output high when requested.

I believe that Arduino IDE is attempting to compile my code for the UNO and those pins do not work on the ATMega328 but this could be completely incorrect and someone please correct me if this is a wrong assumption.

Lastly, I have been able to use the SCL and SCA pins to communicate with an I2C LED shield.

Does anyone know why I cannot write sketch to the ATMega328 using the FTDI and my configuration. Posted Below are images and very rough Fritzing schematics of how I am setup.

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

void loop() {
  Serial.println("TICK");
  digitalWrite(5,HIGH);
  delay(1000);
  digitalWrite(5,LOW);
  }

```

## My Breadboard

## Fritzing Schematic

# Answer
> 0 votes
In combination with Nick Gammon's answer above, I was not aware that the physical pin numbers are different from the digital pin numbers used in the sketch. I resolved my issue by referring to this digital pin map.

# Answer
> 1 votes
This may not be your only problem, but you need a second delay.

```
void loop() {
  Serial.println("TICK");
  digitalWrite(5,HIGH);
  delay(1000);
  digitalWrite(5,LOW);
  delay(1000);    // LOW for a second as well
  }

```

Otherwise you will not be able to see the LOW part, because it will be really quick.

---

> I believe that Arduino IDE is attempting to compile my code for the UNO and those pins do not work on the ATMega328

The Uno has an Atmega328 on it, and I usually compile for the Uno when uploading to a custom board, so this is not the issue.

# Answer
> 0 votes
How old is your chip, or the bootloader on it? Most chips sold (with bootloaders preloaded) - and bootloaders available to upload - for the last several years at least, have uploaded at 115200 baud.

---
Tags: arduino-ide, pins, atmega328, port-mapping
---


# Question
Title: Continuous push button detection in for Stepper control
Currently, I've worked on code for controlling stepper motor with pushbuttons. So, basically, I have to press two push button to run forward and backwards. but the problem is when I press the 1st pushbutton it detects that pushbutton and run motor CW or CCW, That means it cannot detect the press of another pushbutton to make it counterclockwise.

I realize that the program isn't detecting the second push button after pressing 1st one. Tried different options to make it work. but failed.

any suggestions?

Here's my code for reference:-

```

#include <AccelStepper.h>

const int button1Pin = A2 ;
const int button2Pin = A1;

int button1State = 0;
int button2State = 0;

boolean flag1 = 0;
boolean flag2 = 0;

AccelStepper stepper = AccelStepper(1, 8, 9);
void setup()
{
   pinMode(button1Pin, INPUT);
   pinMode(button2Pin, INPUT);

   Serial.begin(9600);
}

void loop()
{

      int sensorReading = analogRead(A0);
      int motorSpeed = map(sensorReading, 0, 1023, 500, 1000);
      button1State = digitalRead(button1Pin);
      button2State = digitalRead(button2Pin);

     stepper.setMaxSpeed(2000);
     stepper.setSpeed(motorSpeed);

     if (button1State == HIGH)
       {

        stepper.setSpeed(motorSpeed);
        Serial.print("ok");
        stepper.runSpeed();

       }

  if (button2State == HIGH)
       {

        Serial.print("ok2");
        stepper.setSpeed(-motorSpeed);
        stepper.runSpeed();

      }
}

```

Another problem is in this current code, it cannot detect the potentiometer input inside the if ( button state ) {} loop.

it would be a great help pointing out my mistakes.

# Answer
> 1 votes
I implemented your code here on a UNO using 2 pushbuttons (with the stepper motor functions commented out) and it seems to work fine. When I press button1 I get a lot of "ok" printouts for as long as the button is held down. When I press button2, the same thing happens except with "ok2" instead of "ok".

Here's the code I used:

```
/*
    Name:       TwoPushButtonTest.ino
    Created:    9/28/2020 2:36:07 PM
    Author:     FRANKNEWXPS15\Frank
*/

//#include <AccelStepper.h>

const int button1Pin = A2;
const int button2Pin = A1;

int button1State = 0;
int button2State = 0;

boolean flag1 = 0;
boolean flag2 = 0;

//AccelStepper stepper = AccelStepper(1, 8, 9);
void setup()
{
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);

  Serial.begin(115200);
}

void loop()
{

  //int sensorReading = analogRead(A0);
  //int motorSpeed = map(sensorReading, 0, 1023, 500, 1000);
  button1State = digitalRead(button1Pin);
  button2State = digitalRead(button2Pin);

  //stepper.setMaxSpeed(2000);
  //stepper.setSpeed(motorSpeed);

  if (button1State == HIGH)
  {

    Serial.print("ok");
    //stepper.setSpeed(motorSpeed);
    //stepper.runSpeed();

  }

  if (button2State == HIGH)
  {

    Serial.print("ok2");
    //stepper.setSpeed(-motorSpeed);
    //stepper.runSpeed();

  }
}

```

and here's the wiring diagram:

Note the two 10K pull-down resistors. If these are not present, then the A2/A3 inputs are indeterminate whenever the buttons are in the 'disconnected' state, and anything can happen.

---
Tags: arduino-uno, button, stepper-motor
---


title: L298N motor driver and battery issues

text:
# Question
Title: L298N motor driver and battery issues
I'm trying to build an Arduino 4WD smart car. so i connected my l298N motor driver module with my v4 shield and used a 4 x 1.5v AA batteries to try and power my 4 motors up. i connected 2 of the motors in parallel so i can use 1 L298N to power it on. initially it worked but then a few minutes later it stopped moving. i thought my connections were bad so i redid all the connections but it didn't work so i changed the battery to 9v. with this the motors worked for a few seconds then stopped but was making noise so i tried powering the motor driver with my Arduino but it didn't come on. I tried powering the motor driver module with my Arduino but the driver module didn't come on.i decided to use my bread board and l293D IC to control my motors it didn't work but the motors were making noise. I changed my motor to one that i removed from a PlayStation controller but nothing still.i did research on the internet and was advised on this tutorial (https://create.arduino.cc/projecthub/maxxlife/arduino-4wd-car-cf5fd0) to not use AA batteries but no explanation why. so i checked other tutorials and saw people using AA to control 1 or 2 motors. Why shouldn't i use AA batteries? does anyone please think they know the solution to my problem? thank you

This is how my kit looks https://www.ebay.com/itm/NEW-4WD-Robot-Smart-Car-Chassis-Kits-car-with-Speed-Encoder-for-Arduino-M26/201561877173?\_trksid=p2047675.c100009.m1982&\_trkparms=aid%3D777000%26algo%3DABA.MBE%26ao%3D1%26asc%3D36860%26meid%3Dc76077722d4348e88152fa6c7f32c005%26pid%3D100009%26rk%3D1%26rkt%3D1%26sd%3D181329341315

Also should i change my use Li-ion battery 18650 x2 instead of the 6LR61 9v battery i used

# Answer
> 1 votes
Rule #1 9V batteries a power supply they are NOT. In your case you are looking at small voltages for the motor power. Your choice of a driver is not the best as you will have from 1.2 to 2.4 volts across the L298 depending on the loading. This is directly from the ST data sheet. Try the TB6612FNG instead, taking advantage of the device’s use of MOSFETs. The TB6612 may be a little more expensive, but it will be clearly worth it.

# Answer
> 1 votes
I give you credit for trying. In your spare time read some materials on basic electronics. I will see if I can help but no guarantee. he motor driver you are using has transistors as the driving element. That indicates the motor power is going through them. Since they are transistors they have a PN junction. When voltage goes through a silicone junction it will drop 0.7volts for each junction. If lightly loaded sometimes less. Note: this loss is expelled as heat. You have two configured as a darlington configuration on each output. This places two junctions in series with each motor lead. That is a total of 4 junctions yielding a drop of 4 * 0.7 = 2.8 Volts. Subtract that from your supply before you start, that is a big hit in low voltage systems. The MOSFET will have a drop of about 0.05Volts on each side leaving you 2.7 more volts to work with. Batteries have power ratings, these are conservative:

Type Cap (mAh)) Drain(mA) - D 13000 200 - C 6000 100 - AA 2400 50 - AAA 1000 10 - N 650 10 - 9 500 15 -

The battery capacity will be better with lower drain currents and shorter with higher drain current. To determine your battery life, divide the capacity by the actual load current to get the hours of life. For example: A circuit that draws 10 ma powered by a 9 volt rectangular battery will operate about 50 hours: 500 mAh /10 mA = 50 hours The cell voltage of alkaline cells steadily drops with usage from 1.54 volts to about 1 volt when discharged. The voltage is near 1.25 volts at the 50% discharge point. Alkaline cells exhibit a slightly increased capacity when warmed and the capacity drops significantly at temperatures below freezing. Mercury and silver oxide batteries have nearly twice the capacity as alkaline batteries of the same size but the current ratings are significantly lower. Alkaline batteries also have good shelf life making them ideal for home-made electronic projects. Rechargeable batteries have less capacity than primary cells Look at it like the batteries are your piggy bank. The more your take out the less you will have. The faster you take it out the quicker you are out of money.

---
Tags: battery, l298n, l293d
---


# Question
Title: problems with Blue Pill (stm32f103c8t6) direct register manipulation
I'm trying to access registers but I keep getting the "was not declared in this scope" error message. I'm currently using the STM32F1xx boards from http://dan.drown.org/stm32duino/package\_STM32duino\_index.json

The board package does not seam to recognize any of the registers from the reference manual, mostly trying to access the ADC registers such as 'ADC\_CR2'. Does anyone know where I can find the register names which works in the Arduino IDE?

# Answer
> 0 votes
you need to use something like this:

```
ADC1->CR2 = ... ;

```

note 2 things:

* you need to use `ADC1`, `ADC2` ... to access the registers. not just `ADC`.
* you need to use arrow (-\>) operator to access the registers

and you may need to include the header file, something like this :

```
#include <stm32f030x6.h>

```

find the proper header file for your MCU. (it's not the same as stm32f1xx, but if proper definitions are made somewhere, it may also work)

---
Tags: ide, port-mapping, stm32, board
---


# Question
Title: External RAM (23LC1024) and external Flash (W25Q64JVSSIQ) with Sparkfun SAMD21
i'm trying to extend the capabilities of the Sparkfun SAMD21. My question is, which pins do I have to share? I mean, I understand that MISO, MOSI and SCK are shared, but CS connects each to a different pin, am I correct?

My schematics:

I connect my CS\_RAM to the D10(PA18 on SAMD21). and i connect my CS\_FLASH to the D6(PA20 on SAMD21)

# Answer
You are correct, MISO, MOSI and SCK are common to all the SPI devices. Be sure they are all set up for clock polarity etc. The CS\ line is the select line. If the device is not selected it does not matter what goes on with MISO, MOSI and SCK. There are chips such as the 74HC138 that will give you chip selects with just a few additional pins. 1 pin gives you 2 selects 2=4 and 3 gives you 8 selects.
> 1 votes

---
Tags: spi, flash, memory, sram, samd21g
---


# Question
Title: Servo motor analog vs digital and AC vs DC
I am little confused with servo motor terminology.

Q1. AC servo motor requires AC power source ? Q2. DC servo motor requires DC power source ?

If answer to above 2 questions are YES then what does analog servo motor means.

Q3. Can I use arduino uno to control analog RC servo motor ?

# Answer
> Q1. AC servo motor requires AC power source ? Q2. DC servo motor requires DC power source ?

Yes. It's all down to the kind of motor that is used in the servo - an AC synchronous motor (often with VFD), a small DC brushed motor (the most common RC type) or a brushless DC motor.

> Q3. Can I use arduino uno to control analog RC servo motor ?

Yes. That's precisely what the bundled `Servo.h` library is for. All the Arduino servo examples you will find online use analog RC servo motors.

The name "analog" though for those motors is not really 100% correct. They are driven by a PWM signal where the duty cycle is used to control the angle. The signal itself is 100% digital. The "analog" component comes in the form of the duty cycle of the signal.
> 0 votes

---
Tags: servo
---


# Question
Title: Counter on my coin acceptor goes up without a coin input, any advice?
I'm working on a project that makes use of a CH926 coin acceptor. The problem we're having is that when I read the serial monitor, the coin value is continuously going up and adding credits when it's supposed to remain at 0 until a coin Is fed into the acceptor.

We've tried a different coin acceptor, different codes, arduinos, wiring, resistors, breadboards, the lot. nothing seems to be solving this problem and we can't determine why, it had been working fine until we tried to tidy up our wiring and untangle it.

we're using a basic code that had worked fine up until we had the issue of the counter value no longer remaining at 0:

```
const int coinpin = 2;
const int ledpin = 3;
const int targetcents = 100;

// Variables
volatile int cents = 0;
int credits = 0;

// Setup
void setup() {

  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(coinpin), coinInterrupt, RISING);
  pinMode(ledpin, OUTPUT);

}

// Main loop
void loop() {

  // If we've hit our target amount of coins, increment our credits and reset the cents counter
  if (cents >= targetcents) {
    credits = credits + 1;
    cents = cents - targetcents;
  }

  // If we haven't reached our target, keep waiting...
  else {
  }

  // Debugging zone
  Serial.print(cents);
  Serial.print(" cents toward current credit and ");
  Serial.print(credits);
  Serial.println(" credit(s) earned so far.");
  delay(1000);

  // Turn off LED
  digitalWrite(ledpin, LOW);

  // Now, write your own cool code here that triggers an event when the player has credits!
  if (credits > 0) {
    // Play music?
    // Spin up a motor?
    // Start a game?
    // It's up to you!
  }

}

// Interrupt
void coinInterrupt(){

  // Each time a pulse is sent from the coin acceptor, interrupt main loop to add 1 cent and flip on the LED
  cents = cents + 1;
  digitalWrite(ledpin, HIGH);

}

```

any advice on what may be causing this problem?

cheers

# Answer
> 2 votes
I'm also complicated by that. The advice I saw here was to connect a COIN wire also against an electric "R" 10K and connect to the second hole on the left in the Arduino "IOREF" now it works.

---
Tags: serial
---


title: Using ESP32 Cam internal RAM

text:
# Question
Title: Using ESP32 Cam internal RAM
I am new to the ESP32 series of boards.I powered up my ESP32 Cam board using the Vcc pin supplying about 7.4V using two 18650 batteries only to find out later that was a completely incorrect way to power up the board.

Now I cannot get my board to flash. I am guessing that the SPI SRAM on my board is burnt because when I measure the Vcc at the SPI SRAM chip it doesn't read 3.3V as its supposed to.

Also there is continuity between the ground and Vcc of the SPI SRAM chip. And it heats up excessively when powered up using 5V.

However I read in the documents that the ESP32 has a few bytes of internal RAM in it.

I was planning to use the ESP32 Cam as an IP Camera for one of my projects. I want to know if its possible to desolder the SPI SRAM chip (IPS1704) and somehow use the internal ram to get my job done or else if I have to buy a new board.

Thanks in advance

# Answer
> 2 votes
If there is continuity between 3.3V and GND your board is dead. Most likely (from my experience) the ESD protection diode on the ESP module is fried which leaves you no chance to repair it. Even if you could remove the shielding to change the diode, you have no chance to find out which components are damaged. Considering the cost of the whole device, repairing it doesn't seem to be worth the effort.

For your understanding:

* reading less than 3.3V on the external RAM means you would also read the same voltage at the ESP's Vcc. It's not an indicator for the RAM being dead
* the ESP32 has plenty of internal ram (some hundreds of kB remain for use of your sketch after subtracting what the RTOS uses)
* the ESP32 (**chip**) has no internal flash, so there is always an external flash on the ESP **module**
* the ESPcam has an additional SPI RAM assembled **externaly to the module**. The internal RAM is by far too small to do any useful image processing at any desired resolution, so using only the internal RAM does not work

# Answer
> -1 votes
It appears you have some paper weights. I would suggest before you make more read the instructions and be sure you understand them. It is much less costly that way. There may be some light at the end of the tunnel, if the ESP32 and it is mounted on another board, and it possibly has a voltage regulator, you might be OK, but I have two neighbors chances, Slim and None. Read the data or as they say RTFM.

---
Tags: spi, esp32, iot, sram, espressif
---


# Question
Title: Passing non-static member function using bind
I'm using the GxEPD2 library to communicate with an E-Paper display. I now wanted to use the `drawPaged` method of this library with an object `display`.

I also have written my own class from which I want to print stuff on the display.

Here's the relevant code for the MyClass.h:

```
class MyClass{
    //some variables and methods
    void drawClass(); //this is public
    void drawClassCallback(const void* v1); //this is private
    //    this is actually a uint8_t --^
}

```

And here's the MyClass.cpp:

```
void MyClass::drawClass(){
    //some display preparation
    uint8_t var; //A variable to pass information from the callback to this method since it is needed later
    display.drawPaged(std::bind(&MyClass::drawClassCallback, this, &var));
    //some code where I need var with info from the callback
}

```

I'm getting the following error:

> no matching function for call to 'GxEPD2\_BW::drawPaged(std::\_Bind\_helper::type)'
>
> note: candidate: void GxEPD2\_BW::drawPaged(void (*)(const void*), const void\*) \[with GxEPD2\_Type = GxEPD2\_290; short unsigned int page\_height = 296u\] void drawPaged(void (*drawCallback)(const void*), const void\* pv)

I've also tried `display.drawPaged(std::bind(&MyClass::drawClassCallback, this, std::placeholders::_1), &var)` without success.

I've stumbled upon this post already, however the solution presented there (and the one used above) does not work in this case.

Why is that?

# Answer
> 1 votes
In your `MyClass` example, the `drawPaged()` call is given only a single argument, while according to the library, it needs two:

```
void drawPaged(void (*drawCallback)(const void*), const void* pv)

```

The first argument is the function pointer (or the one wrapped by `std::bind`!). The second argument seems to be some data that will be passed on to that function. (according to the \[linked API)

The error actually explains it, it suspects that you are trying to call `void GxEPD2_BW::drawPaged(void ()(const void), const void*)`. Hence it mentions this as a candidate.

What you need to do is something like this:

```
display.drawPaged(std::bind(&MyClass::drawClassCallback, this, std::placeholders::_1), &var);

```

`std::placeholders::_1` is the placeholder that represents the `var` argument that will be passed on when it is called.

---
Tags: c++, esp32, callbacks
---


title: How to control baby swing?

text:
# Question
Title: How to control baby swing?
I am starting an intresting DIY project of baby swing. My son is 3 month old and we have swing made with ropes in our house where he sleeps. I am looking for any electronic component controlled with arduino to swing it in controlled manner. I thought of servo motor but not sure how will it work. Any suggestions please ?

swing is similer to below

# Answer
A simple DC motor would work. you have to pulse it in the right moment. for finding out the *right moment* and the pulse length (you don't want to push it so hard !) you need a simple accelerometer sensor to measure acceleration in specific axis.
> 0 votes

---
Tags: arduino-uno, wifi, speed
---


# Question
Title: Flow control between ESP32 and RS323 device
I'm trying to communicate an RS232 device with an ESP32 (Heltec Wifi/LoRa 32 v2) my problem is that I don't receive any response from the device, doing some research, I'm thinking that the trouble can be the flow control because I don't use these pins and the modules I've used neither have these pins. Do you know a way to, at least, solder the DB9 pins to have a sort of flow control to communicate the devices?

# Answer
You could use ESP-IDF calls to setup your UART correctly for hardware serial communication on pin 4 and 5 (and perhaps also other pins).

In the sample below, you just have to:

* assign `UART_CLIENT_RTS` and `UART_CLIENT_CTS` to the pins of your need
* change `uart_config_t` to whichever parameters are relevant for your RS232 device
* set `flow_ctrl` to `UART_HW_FLOWCTRL_RTS`, `UART_HW_FLOWCTRL_CTS`, `UART_HW_FLOWCTRL_CTS_RTS` or `UART_HW_FLOWCTRL_MAX`

```
    #define BUFFER_SIZE 1024

    #define UART_CLIENT_TXD  (GPIO_NUM_4)
    #define UART_CLIENT_RXD  (GPIO_NUM_5)
    #define UART_CLIENT_RTS  (GPIO_NUM_?) // Set this
    #define UART_CLIENT_CTS  (GPIO_NUM_?) // Set this

    uart_port_t uartNum = UART_NUM_1;

    uart_config_t uart_config = { // Set this
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity    = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS
    };

    uart_param_config(uartNum, &uart_config);
    uart_set_pin(uartNum, UART_CLIENT_TXD, UART_CLIENT_RXD, UART_CLIENT_RTS, UART_CLIENT_CTS);
    uart_driver_install(uartNum, BUFFER_SIZE * 2, 0, 0, NULL, 0);

```

Communication can be done with the various `uart_write_*` and `uart_read_*` methods as defined in the documentation.
> 1 votes

---
Tags: serial, communication, esp32, rs232
---


# Question
Title: Task watchdog gets triggered during Bluetooth initialization
The board ESP32-Dev-WROOM-32D cannot establish a bluetooth connection due to the task watchdog. Here's my code:

```
#include "BluetoothSerial.h"
//check if Bluetooth is enabled
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32test");
  Serial.println("The device started!");
}

```

The program runs fine until `SerialBT.begin("ESP32test");` where it freezes, and does not continue to run. The message `The device started!` is not printed. Instead, the task watchdog gets triggered after some time: `E (24791) task_wdt: Task watchdog got triggered.`

Is there any way to turn off the task watchdog? Or is there any other issue?

# Answer
> 1 votes
`SerialBT.begin("ESP32test")` is hanging, and because ESP32 doesn't deal well with code that hangs, so it complains about it.

ESP32 runs a Real-Time OS (FreeRTOS). The fact that it is a real-time OS means that execution of code needs to be guaranteed to finish within a certain time-frame. You'll often see RTOS functions containing the time limit in which that a blocking function should finish executing, such as:

```
    uart_wait_tx_done(uart_num, 100); // wait timeout is 100 RTOS ticks (TickType_t)

```

(from ESP-IDF docs)

FreeRTOS comes with a task API. Each task can execute code, but they need to give other tasks the chance to execute code too. I think that when a task blocks, it doesn't allow other tasks to do work on the same CPU. (but I can't find sources to back this up)

`setup()` runs in one of the RTOS tasks, and when `SerialBT.begin()` blocks the task for too long, the task watch dog complains that the task is hanging. If the task is blocked by some kind of looping code, then it generally helps to run `vTaskDelay()` to yield the task to the task watchdog for a bit.

Because your task is blocked by a single call, there isn't much to do about it, given that `SerialBT.begin()` doesn't seem allow you to specify when it should time out.

---
Tags: arduino-ide, bluetooth, esp32, watchdog
---


# Question
Title: How to burn the bootloader and upload sketches on ATmega328P U (specifically this model)?
Recently I started to learn embedded electronics and C/C++ and for a couple of days I tried and I am still trying to burn a new ATMega328P U bought from Aliexpress. From what I know new ATMega328P's come with bootloader included, but after I wired everything up and connected the FTDI FT232RL to load the sketch (wiring is completely right after many many hours of checking on the internet for a dozen of pictures), I get errors like "programmer is not responding" in case of sketch upload and "error while burning the bootloader" or "Yikes, signature bla bla". I don't think the FTDI is the problem since the Arduino IDE recognizes it as COM7 on my PC. Now here's my question: is my atmega328p u broken or have I missed something during the process of both (trying to) burn(ing) the bootloader and upload(ing) the blink sketch? (I have also tried uploading the board programmer from Nick Gammon on my arduino Uno and the burning the bootloader AND followed the instructions from arduino.cc "from arduino to microcontroller on a breadboard"). If you need pictures of some sort, I'll provide them

# Answer
IT WORKED, FINALLY. I followed this tutorial: https://www.electronics-lab.com/project/installing-the-arduino-bootloader-on-the-atmega328p-microcontroller/, followed exactly as it is explained, made the connections (nothing more, nothing less; I even removed the LED on pin 19 and its resistor) and to my surprise... the bootloader was actually loaded and the sketches were uploading just by using the FTDI. Thank you a lot for your help and information and I hope someday I'll pass this knowledge to someone who will be in the spot I was until now. Have a great time and love ya all
> 2 votes

---
Tags: arduino-uno, atmega328, electronics, arduinoisp, atmel
---


title: How can I display text on OLED?

text:
# Question
Title: How can I display text on OLED?
I'm trying to print the information, which is received from the other ESP32 by CAN transceiver, on an OLED. The CAN bus is working perfectly, as the 'HELLO WORLD' is already be received. But I can't print the received 'HELLO WORLD' on OLED (also the OLED is work). The code shows below,

```
#include <CAN.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

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

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }
  delay(2000);
  display.clearDisplay();
  display.setTextColor(WHITE);

  Serial.println("CAN Receiver");
  CAN.setPins(16, 17);
  // start the CAN bus at 500 kbps
  if (!CAN.begin(500E3)) {
    Serial.println("Starting CAN failed!");
    while (1);
  }
}

void loop() {
  // try to parse packet
  int packetSize = CAN.parsePacket();

  if (packetSize) {
    // received a packet
    Serial.print("Received ");

    if (CAN.packetExtended()) {
      Serial.print("extended ");
    }

    if (CAN.packetRtr()) {
      // Remote transmission request, packet contains no data
      Serial.print("RTR ");
    }

    Serial.print("packet with id 0x");
    Serial.print(CAN.packetId(), HEX);

    if (CAN.packetRtr()) {
      Serial.print(" and requested length ");
      Serial.println(CAN.packetDlc());
    } else {
      Serial.print(" and length ");
      Serial.println(packetSize);

      // only print packet data for non-RTR packets
      while (CAN.available()) {
        Serial.print((char)CAN.read());
      }
      Serial.println();
    }

    Serial.println();
  }
  delay(5000);

  display.clearDisplay();

  display.print((char)CAN.read());

  display.display();
}

```

# Answer
Just guessing but looks to me like you read the `CAN` message and print it character by character to the Serial console but you don't save those characters in a buffer as you get them from `CAN.read()`.

So when you then try to `display.print((char)CAN.read());` at that point there are no more characters to available for the `CAN.read()` to read so nothing is printed by the `display.print()`.

So what you need to do is to read the characters into a buffer so that you save them after reading them so that you can use the text string for other purposes.
> 3 votes

---
Tags: communication, esp32, display, can-bus, oled
---


title: Are breadboads available in EasyEDA?

text:
# Question
Title: Are breadboads available in EasyEDA?
So far I have been using TinkerCAD which has them but I am unable to find them on EasyEDA Library. Are connectors supposed to do the same thing? I get this empty rectangle in the EasyEDA library which I am unable to make sense of.

# Answer
> 1 votes
EasyEDA is not designed for diy prototypes like TinkerCAD is. EasyEDA's purpose is to simulate electronic circuits and design circuit boards for those circuit designs. Because of this they don't have a breadboard object because there would be no point in having one, since you can just connect virtual wires in the schematic mode and wire traces in the board design mode.

Furthermore, it doesn't support simulating a full Arduino board with code.

---
Tags: simulator
---


# Question
Title: How do I recover a beetle where I loaded a program that was too large and overwrote the bootloader?
I'm doing on-target unit testing for an industrialized application and my test code is too large to fit everything on the board at the same time. I'm using the Sloeber toolset to develop, and I put something on the board that was over 28K, and the programming failed. Now the beetle does not show up as a serial port, and not even when pushing the reset pins, which I've had to do a number of times in the past. If I overwrote the bootloader, which seems likely, is there a way to recover it? Do I need to reprogram the bootloader on a Beetle board? I haven't found any way to do that with a Beetle...

Thanks!

# Answer
I don't know the Sloeber toolset, but it seems very unlikely, that it really has overwritten the bootloader. When programming via USB, it is actually the bootloader, which writes the program into the flash memory. So that would mean, that the bootloader had overwritten itself, only because a too large program. Not sure, if this is even possible.

Anyway, you can utilize an ICSP/ISP programmer (or another Arduino, if you don't have one) to burn the bootloader onto the chip again. Google for Arduino ISP to get instructions for it, there are plenty of tutorials.

You need to connect the correct pins on the Beetle with the ISP programmer. According to this site, you should find the ICSP pads at the back of the board (the group of 6 pins in 2 rows). Through these pins you can burn the bootloader.

If that doesn't work either, the problem lies somewhere else. As I already stated, overwriting the bootloader because a program is too big for the MCU should not happen and it is highly unlikely, that this is really your problem. You might have damaged something on your board, though we cannot tell that from the description. So you could just try to burn the bootloader and see what happens.
> 1 votes

# Answer
Use double reset to activate the bootloader. The LED will pulse while it waits for upload.

The board doesn't show up on USB because USB is handled by the sketch on MCU with native USB. If the sketch doesn't run it doesn't handle the USB.

The bootloader is protected by fuses.

(This happen to me with Sloeber a few days ago.)
> 0 votes

---
Tags: arduino-leonardo, bootloader
---


# Question
Title: Interfacing MPU6050 with Arduino through Simulink S-function
I am interfacing MPU6050 with Arduino using Simulink S-function builder. I'm implementing MPU6050\_DMP6 code in Simulink s-function builder by following this video. By following this tutorial I implemented the S-function as: I set sample time 0.05 in s-function builder block and number of discrete state=1 and sample mode = 1. in the libraries tab I put the following code:

```
#include <math.h>
#ifndef MATLAB_MEX_FILE
int counter=0;
#include <Arduino.h>
#include "I2Cdev.h"
#include "I2Cdev.cpp"

#include "helper_3dmath.h"
#include "MPU6050_6Axis_MotionApps20.h"
#include "MPU6050.h" // not necessary if using MotionApps include file
#include "MPU6050.cpp" // not necessary if using MotionApps include file
// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
    #include "Wire.cpp"
    #include "utility/twi.h"
    #include "utility/twi.c"
#endif
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;

#define OUTPUT_READABLE_YAWPITCHROLL

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
//#define OUTPUT_READABLE_WORLDACCEL

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
//#define OUTPUT_TEAPOT

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}
#endif

```

in the discrete update tab I have implemented following code:

```
if (xD[0]!=1){
#ifndef MATLAB_MEX_FILE
       // join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial2.begin(115200);
//     while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
    // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
    // the baud timing being too misaligned with processor ticks. You must use
    // 38400 or slower in these cases, or use some kind of external separate
    // crystal solution for the UART timer.

    // initialize device
    Serial2.println(F("Initializing I2C devices..."));
    mpu.initialize();
    pinMode(INTERRUPT_PIN, INPUT);
    // verify connection
    Serial2.println(F("Testing device connections..."));
    Serial2.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
   // Serial2.println(F("\nSend any character to begin DMP programming and demo: "));
   // while (Serial2.available() && Serial2.read()); // empty buffer
   // while (!Serial2.available());                 // wait for data
   // while (Serial2.available() && Serial2.read()); // empty buffer again

    // load and configure the DMP
    Serial2.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial2.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);
        // enable Arduino interrupt detection
        Serial2.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial2.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial2.print(F("DMP Initialization failed (code "));
        Serial2.print(devStatus);
        Serial2.println(F(")"));
    }
    #endif

  xD[0]=1;
 }

```

and in output tab I have implemented this code:

```
if (xD[0]==1){
    #ifndef MATLAB_MEX_FILE
// if programming failed, don't try to do anything
    if (!dmpReady) {
        return;
    }

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
        // .
        // .
        // .
        // if you are really paranoid you can frequently test in between other
        // stuff to see if mpuInterrupt is true, and if so, "break;" from the
        // while() loop to immediately process the MPU data
        // .
        // .
        // .
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();
    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

#ifdef OUTPUT_READABLE_QUATERNION
        // display quaternion values in easy matrix form: w x y z
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        // Serial.print("quat\t");
        // Serial.print(q.w);
        // Serial.print("\t");
        // Serial.print(q.x);
        // Serial.print("\t");
        // Serial.print(q.y);
        // Serial.print("\t");
        // Serial.println(q.z);
#endif

#ifdef OUTPUT_READABLE_EULER
        // display Euler angles in degrees
//         mpu.dmpGetQuaternion(&q, fifoBuffer);
//         mpu.dmpGetEuler(euler, &q);
//         Serial.print("euler\t");
//         Serial.print(euler[0] * 180/M_PI);
//         Serial.print("\t");
//         Serial.print(euler[1] * 180/M_PI);
//         Serial.print("\t");
//         Serial.println(euler[2] * 180/M_PI);
#endif

#ifdef OUTPUT_READABLE_YAWPITCHROLL
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        *roll = ypr[0] * 180/M_PI;
        *pitch = ypr[1] * 180/M_PI;
        *yaw = ypr[2] * 180/M_PI;
        Serial2.print("ypr\t");
        Serial2.print(ypr[0] * 180/M_PI);
        Serial2.print("\t");
        Serial2.print(ypr[1] * 180/M_PI);
        Serial2.print("\t");
        Serial2.println(ypr[2] * 180/M_PI);
#endif

#ifdef OUTPUT_READABLE_REALACCEL
        // display real acceleration, adjusted to remove gravity
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetAccel(&aa, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
        // Serial.print("areal\t");
        // Serial.print(aaReal.x);
        // Serial.print("\t");
        // Serial.print(aaReal.y);
        // Serial.print("\t");
        // Serial.println(aaReal.z);
#endif

#ifdef OUTPUT_READABLE_WORLDACCEL
        // display initial world-frame acceleration, adjusted to remove gravity
        // and rotated based on known orientation from quaternion
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetAccel(&aa, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
        mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
        // Serial.print("aworld\t");
        // Serial.print(aaWorld.x);
        // Serial.print("\t");
        // Serial.print(aaWorld.y);
        // Serial.print("\t");
        // Serial.println(aaWorld.z);
#endif

#ifdef OUTPUT_TEAPOT
        // display quaternion values in InvenSense Teapot demo format:
        teapotPacket[2] = fifoBuffer[0];
        teapotPacket[3] = fifoBuffer[1];
        teapotPacket[4] = fifoBuffer[4];
        teapotPacket[5] = fifoBuffer[5];
        teapotPacket[6] = fifoBuffer[8];
        teapotPacket[7] = fifoBuffer[9];
        teapotPacket[8] = fifoBuffer[12];
        teapotPacket[9] = fifoBuffer[13];
        Serial.write(teapotPacket, 14);
        teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
#endif

        // blink LED to indicate activity
        // blinkState = !blinkState;
        // digitalWrite(LED_PIN, blinkState);
    }

#endif
}

```

The solver I'm using is fixed-step discrete solver.

I build the S-function and then the model successfully. When I run the simulation in the external mode using Arduino mega there are **jump and glitches** in the output raw, pitch and roll angles as shown in the  However, when I plotted the same code through Arduino IDE and monitor data on serial plotter there is no glitches and jumps in angles. I have also change the baud rate to 115200, solver to auto and sample time of s-function but the problem remain to persist. Any help would be appreciated! Thanks in advance!

# Answer
Measurement sometime lost due to serial communications between Arduino and Simulink. So raw data have some glitches in output values. In order to solve the issue, we have to use state estimation to solve this problem.
> 1 votes

# Answer
To add to the answer above, you are limited by the serial speed of the USB, i.e. USB 2.0 is around 12 Mbps, as well as what your hardware can manage. Also, Simulink uses about 25% of each time step simply for maintaining communication and it is unclear how bandwidth is used by this. A simple rule of thumb is to work out how much data you are trying to log and at what frequency as this should give you an idea if you are trying to log too much and hence Simulink won't catch all the data and you end up with the blip you have in the scope. For context, I have been making a wheel speed calculation algorithm and was losing data simply because it wasn't possible to log the volume of data I wanted at high frequency (i.e. 5000 Hz). If you think about logging 3 int8 values at 5000 Hz you are talking 120 kkps, this should give some idea as to how this can get out of control with more signals or larger data types like double.
> 2 votes

---
Tags: arduino-mega, mpu6050, matlab
---