# Question
Title: Can a MEMS accelerometer sensor be used as a shock sensor?
I am trying to make an IOT project- SMART DOOR where I have used a serve motor and NodeMcu and for adding further functionality I have been thinking of adding a theft detection feature where whenever a large force is applied on the lock an alarm starts beeping and for that I don't have a shock sensor but I do have MEMS accelerometer sensor(MPU6050 Accelerometer and Gyroscope). So can I use it to add this functionality? If yes, can I get a little guide on what configuration and sensitivity I should use?

THANK YOU!

# Answer
Sure you can. A "shock" is merely a large amount of acceleration over a short period of time.

You would probably want to set the MPU6050 to its least sensitive setting (±16g), and you might even be able to make use of the "tap" function whereby the MPU6050 itself looks for a sudden short sharp shock to trigger an interrupt (though that may be a little too sensitive for your needs, I don't know).
> 0 votes

---
Tags: iot
---


# Question
Title: Can I integrate Arduino in a CI/CD setup?
While it seems less valuable to emulate Arduino in a CI/CD setup, are there any experiences/best practices for collaborative teams to automate their acceptance tests where a real Arduino is integrated into a CI/CD toolchain (or, what are comparable practices)?

Minimal example of acceptance testing:

* compilation is successful for a given compiler version.

# Answer
> 1 votes
There are different approaches around. I can only point you to some of them:

As a valuable commenter mentioned on your previous question - this does not cover the attached hardware testing (sensors/ motors) - this has to be "integrated" via a test lab station, which you have to control manually (or semi-automated via lab equipment) on defined release/version changes

---
Tags: automatization
---


# Question
Title: Can stack size be determined by free heap?
i have NodeMCU with es8266 onboard on it. I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen. So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

one tiny question here: can `Serial.println("asd asd")` cause memory fragmentation?

# Answer
> 3 votes
> I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen.

Indeed they do. And such things can be a pain to track down.

> So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

No, you can't. The "free" amount of heap does not equate to the top address of heap. Heap can (and generally does) have holes in it. The "free" space is the sum of all those holes plus any extra "heap reserved" space above the highest heap entry.

To get the current stack usage you need to know two things:

1. The staring address of the stack, and
2. The current extent of the stack

Item 1 will be a fixed value, though what that value is I have no clue, but some reading will surely give you that value.

Item 2 can be obtained by allocating a local variable in a function and getting the address of that variable.

If all you care about is the change in stack imposed by your code you can record the "starting" stack point and use that in point 1. For example:

```
char *stack_start;

void setup() {
    char stack;
    stack_start = &stack;
}

```

Then you can use that to get the current stack size compared to the start of your program:

```
uint32_t stack_size() {
    char stack;
    return (uint32_t)stack_start - (uint32_t)&stack;
}

```

> one tiny question here: can Serial.println("asd asd") cause memory fragmentation?

No. Use of `String` and other dynamic allocation is what causes memory fragmentation.

---
Tags: esp8266, nodemcu, memory
---


# Question
Title: How to install a dependency library to an Arduino compilation environment?
Following *approach A* from this Arduino SE answer, I managed to kick off an Arduino CLI compilation in a Docker environment.

However, the project I am trying to compile has a dependency on a LCD control library.

Error output:

```
...../OpenSourceVentilator/OpenSourceVentilator.ino:494:116:
fatal error: LiquidCrystal_PCF8574.h:
No such file or directory
compilation terminated.

```

What is the proper way to link dependencies to the compilation environment of an Arduino project?

While the source suggests a direct compiler call, maybe I need a Makefile instead of the following?

```
arduino-cli compile --fqbn esp32:esp32:esp32 -o ignored.bin OpenSourceVentilator.ino

```

# Answer
If the library is installed the Arduino IDE (or CLI I assume too) just finds it and compiles/links it for you.
> 0 votes

---
Tags: library, arduino-makefile
---


# Question
Title: How to control one Mosfet with another mosfet
I've got 4x 12V 6a peltiers and some 3d printer mosfet controllers to drive them using PWM with my arduino. But I've found the mosfets need ~7V to switch on, so I'm now wanting to control them with some logic level ones I had around. I could just use the logic ones directly to the peltiers, but am finding it difficult to make my stripboard capable of handling 24A (this page seems to say I need tracks/wire of 2.3+mm diameter which I don't have). Hence I'm trying to make a circuit for the arduino to use the logic mosfets to control the 3d printer mosfets but can't quite get my head around how to do it. I think I'm missing a power source for the first mosfet - do I need to have a whole separate DC power supply for this to the peltiers? Very grateful for a bit of help please!

# Answer
> 2 votes
There's one thing you missed with your arrangement, and that is getting the 12V to turn the MOSFET on. In your current arrangement it's possible to turn it off, but never on. Adding a pullup resistor can help:

simulate this circuit – Schematic created using CircuitLab

R1 pulls the gate of M1 up above the switching threshold to turn it on. M2, when on, pulls the gate down below the switching threshold, turning it off.

However: you may have noticed that the switching is now backwards: send a HIGH from the Arduino to turn it off. Which of course has the effect that *the output is normally on and you have to actively turn it off*.

Again a pullup resistor can help:

simulate this circuit

Now R2 keeps the gate of M2 pulled up (switched on) which keeps M1 turned of. That is, until you actively pull the gate down to ground by sending a LOW from the Arduino.

To ensure that the peltier never turns on when you don't want it to you should also take steps to ensure that the 12V power is never provided without the 5V also being provided - so you could maybe power the Arduino through the barrel jack from the 12V supply. It doesn't matter if the 5V is provided but not the 12V, but the other way around could mean the peltier comes on with no active control over it.

---
Tags: current, mosfet, peltier
---


title: Regarding Strings and assignments

text:
# Question
Title: Regarding Strings and assignments
I have this code which works :

```
String ErrorMsg;
.......
if(!UploadPacketError)
{
    ErrorMsg="OK";
}
else
{
   ErrorMsg="NOK";
}

```

String creates a dynamically allocated array which I want to avoid. I would prefer something like :

```
unsigned char ErrorMsg[5];
......
if(!UploadPacketError)
    {
        strcpy(ErroMsg,"OK",3); // +1 for the Null Termination ?
    }
    else
    {
       strcpy(ErroMsg,"NOK",4); // +1 for the Null Termination ?
    }

```

i.e. is there a way to dynamically assign a value to a fixed size character array ?

Cheers Thomas

# Answer
Almost.

First it's `char` not `unsigned char`:

```
char ErrorMsg[5];`

```

Second you don't specify a size with `strcpy`:

```
strcpy(ErrorMsg, "OK");

```

There is a variant of `strcpy` called `strncpy` which copies *at most* `n` characters:

```
strncpy(ErrorMsg, "OK", 5);

```

That is used to prevent buffer overruns. But when working with string literals like that it's pretty pointless.
> 1 votes

# Answer
Also recomending the fixed char approach but for completeness there is a possibility to "get away with String class" IF you **ONLY** use fixed AND predefined Strings to build dynamicly variable messages:

```
bool first = true;

String A = F("My first ");
String B = F("My second ");
String C = F("answer");
if (first) serial.println(A+C);
else serial.println(B+C);

```

Read more on the F-macro here.
Conclusion:

* Large blocks of text to a file system (like SPIFFS, LittleFS, SD)
* dynamic texts to large enough fixed char arrays and
* short messages (consisting of fixed parts) can be created with the F-Macro
> 0 votes

---
Tags: string, array
---


title: Runtime compilation

text:
# Question
Title: Runtime compilation
I want to compile a sketch on Arduino Uno, while Arduino is running and not connected to anything else, and then run the compiled sketch automatically.

Is this feasible?

How?

# Answer
No, not feasable, not possible.

The Arduino runs machine code and it does not have enough space or computation power for a compiler (also there is simply no version of the avr C++ compiler for the AVR platform, for obvious reasons). Also it is internally hardwired to run code from the flash memory. You cannot execute code from RAM. The Arduino is a microcontroller, not a computer. (Here I mean computer as something like: Has a microprocessor to execute code from RAM; has an OS; has huge amount of resources in relation to the average microcontroller)

Also: "not connected to anything else" --\> Then how would you interact with the Arduino, writing the code, triggering compilation?

If this is about the cable connection, you can implement programming over bluetooth through the HC-05 module (google for it, there should be plenty of tutorials out there). Or go away from the Arduino and change to an ESP, so that you can do Over The Air (OTA) updates over wifi.

Or you could change to a minicomputer like the Raspberry Pi Zero, which is just a little bigger than the Arduino Nano and smaller than the Uno. (Though that hardly depends on the goal, what you are trying to achieve. Microcontrollers are sometimes better used for specific tasks in contrast to minicomputers)
> 1 votes

# Answer
No. It's not feasible.

The Uno cannot compile. The Uno cannot run code from RAM. The Uno is *not* a computer.

You *might* be able to find some small scripting language that could run on an Uno, but TBH the Uno is so underpowered you'd be able to do little more than blink an LED...
> 0 votes

---
Tags: sketch, compile, compiler
---


# Question
Title: Display a Random Number to Display for T Seconds With Millis() for Dice Roller
I'm coding an electronic dice roller for a project. At the press of a push button (A2), the code must display a random number to the two digit seven segment display for 20 seconds, then display blank.

Currently, my code will display a random number every t seconds while the button is continuously held. I would like the user to be able to press the button and release to let the code do it's thing.

What type of examples should I look at to achieve this? I'm quite a beginner at arduino code.

```
    #include "SevSeg.h"
SevSeg sevseg; //Instantiate a seven segment object

int displayPeriod = 1000; //button press delay
unsigned long time_now = 0;

long randNumber;

void setup() {

  pinMode(A2,INPUT);
 randomSeed(analogRead(3));

  byte numDigits = 2;
  byte digitPins[] = {2, 3};
  byte segmentPins[] = {4,5,6,7,8,9,10};
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_CATHODE; // See README.md for options
  bool updateWithDelays = false; // Default 'false' is Recommended
  bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
  bool disableDecPoint = true; // Use 'true' if your decimal point doesn't exist or isn't connected. Then, you only need to specify 7 segmentPins[]

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments,
  updateWithDelays, leadingZeros, disableDecPoint);

}

void loop() {

if(digitalRead(A2) == HIGH){

  rollD20();

}

else{

  sevseg.setChars("");
  sevseg.refreshDisplay();
}

}

void rollD20(){

if(millis() >= time_now + displayPeriod){
        time_now += displayPeriod;
        time_now = millis();
        randNumber = random(21);
        }
        sevseg.setNumber(randNumber);
  sevseg.refreshDisplay();
  }

void testInput(){
sevseg.setNumber(0);
sevseg.refreshDisplay();
}

```

# Answer
> 1 votes
I would recommend to not reinvent the wheel, and proper button management may not be so trivial. I would suggest this library to address your problem.

# Answer
> 0 votes
The problem is that your rollD20 function is only called when the button is pressed. So once you release the button, it never goes back to that routine to finish. You need to separate the calling of the function from the detecting of the button.

```
bool rollingDice = false;

void loop() {

if(digitalRead(A2) == HIGH){
  rollingDice = true;
}
if(rollingDice){
  rollD20();
}
else{
  sevseg.setChars("");
  sevseg.refreshDisplay();
}

```

And then in your rollD20 method you need to set that back to false when it is time to stop:

```
void rollD20(){
  if(millis() >= time_now + displayPeriod){
        time_now += displayPeriod;
        time_now = millis();
        randNumber = random(21);
        rollingDice = false;
        }
  sevseg.setNumber(randNumber);
  sevseg.refreshDisplay();
  }

```

---
Tags: arduino-nano, millis
---


title: Possibly fried a new atmega328p?

text:
# Question
Title: Possibly fried a new atmega328p?
I have a new atmega328p IC that I wanted to program. To do so I placed it into the socket of an arduino uno. I accidentally placed it the wrong way around (180° rotated), and powered it via USB and tried to upload the blink sketch, which obviously did not succeed. After I noticed it I turned it around and placed it into the socket the right way. I tried again uploading the blink sketch again without success.

1. Have I fried the atmega328p by placing it in the socket the wrong way?
2. Is there something else you need to do to new atmeag328p before you can program them the usual way?

---

**Update:** It seems that just rotating the IC did not damage it in the state where there was no bootloader programmed. And and the bootloader needed to be programmed first before the IC could be used.

# Answer
Whether your chip is fried or not, we can't say, but they're reasonably tough and will stand a bit of abuse before they fail. Did anything smoke or get hot?

You can buy atmega328p chips pre-programmed with a bootloader from a few vendors, but they don't come from the factory that way so most are not. Preprogrammed chips typically cost a couple of $ US more than blank chips for the time spent by the vendor to buy blank ones, program, and repackage them for sale in small quantities, and are almost always advertised as such. If you don't know whether yours is programmed with a bootloader, it probably isn't. It's worth trying to do it yourself, on a breadboard, using a known-working Uno as a bootloader- programmer. There are lots of how-to articles on the internet.
> 1 votes

# Answer
After a reset it should blink pin13 led as all Arduinos do. If not, I'd first try uploading a bootloader cause I have gotten ones that don't have bootloaders. The 328p if a pretty resistant chip. One time i put 12v into a digital pin and it got so hot the smd desoldered itself but worked fine apart from that pin being blown.
> 1 votes

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


# Question
Title: No Websockets Server for Arduino mkr1010?
I've seen some interesting explanations on using websocket comms on mkr 1010 but it's always handling the mkr 1010 as the client and the server being always a computer or some other "non-arduino" server . I'm working on a system with several mkr 1010's in a master/slave setup and bidi comms i.e. i want to use one of the mkr's as a server (does the calculations etc.) and the other as clients (get result from calculations ans send back sensor info). I did not found any library or example of websocket server for mkr1010. I found it for ESP systems. Please help as i tried my bidi comms with webclient and webserver using http but not good enough for my applicaton (not realy bidi). thanks a lot !

# Answer
> 1 votes
Most websocket libraries work over a Client. Client is base class for all EthernetClient and WiFiClient classes.

But why do you want to use a Websocket for communication of two MCU in the same LAN? Websockets are intended for communication over HTTP infrastructure (firewalls, proxies) to a web server in Internet or from browser to a web server.

Use a basic TCP socket over Arduino Client.

WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.

If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read only from the WiFiClient object on the other side.

client socket

```
if (client.connect(serverIP, PORT)) {
  client.print("request\n");
  String response = client.readStringUntil('\n');
  Serial.println(response);
  client.stop();
}

```

server side

```
WiFiClient client = server.available();
if (client && client.connected()) {
  String request = client.readStringUntil('\n');
  Serial.println(request);
  client.print("response\n");
  client.stop();
}

```

---
Tags: programming, arduino-ide, library, ide, mkr1010
---


# Question
Title: How do I set up a multi-file project in the Arduino IDE?
Suppose I have a project with several modules and a main program. This works well by adding the modules to main\_program.

```
module1.cpp
module1.h
module2.cpp
module2.h
...
main_program.ino

```

I'm having problems when I have test programs for each of the modules. These allow the various devices to be tested in isolation.

```
module1.cpp
module1.h
module1.ino # test program
module2.cpp
module2.h
module2.ino # test program
...
main_program.ino

```

I'm required to have each ino file in a directory of the same name. I can add the files to main\_program by adding (e.g.) ../module1/module1.{cpp,h}. But, I discover that it has actually copied module1.{cpp,h} to main\_program/.

How do I set this up? Is there any option other than making each module a library? If possible I would like to keep these files more local than the library directory, since they're specific to this project and not general-purpose libraries.

# Answer
You have two options with ArduinoIDE.

**First** Each module in a module directory

So the structure looks like

```
  main_routine
     main_routine.ino
  --module1
      module1.ino  #test routine
      module1.cpp
      module1.h
 --module2
  .....

```

included in `main_routine.ino`

```
   #include "module1/module1.h"
   #include "module2/module2.h"

```

So you have everything in your master dir and in module specific subdirs below - Nothing is or will be copied by the ArduinoIDE (v1.8.12)

The **second** (more hacky way) is to have everything in one dir and for development testing working with include guards in the `main_routine.ino`

```
 // for production comment all MODULEX_TEST and uncomment PRODUCTION
 //#define PRODUCTION
 #define MODULE1_TEST
 //#define MODULE2_TEST
.....
#if defined (PRODUCTION) || defined (MODULE1_TEST )
   #include "module1/module1.h"
#endif

#if defined (PRODUCTION) || defined (MODULE1_TEST )
   uint8_t myModule1Var = 0;
#endif

setup(){
.....
#if defined (PRODUCTION) || defined (MODULE1_TEST )
   myModule1setup someInit(1,2,3);
#endif
.....
 }

loop(){
.....
#if defined (PRODUCTION) || defined (MODULE1_TEST )
   void mymodule1Func(){....};
#endif
#ifdef MODULE1_TEST
   void mymodule1Test(){....};
#endif

```

Pros and cons

* +This approach gives you the possibility to test two modules together.
* -Its harder to read, but
* +easier to document with tools like doxygen
* ~Only the active includes are compiled and so no overhead in the compiled code

Be aware that with some tool chains there are at the moment problems when using special templates (works if everything is in one module file - I use an "extended header" file as momentary work around) or arrays as initializer (open issue in esp8266)
> 5 votes

---
Tags: arduino-ide
---


title: ToF Laser Sensor (VL53L0X) not working

text:
# Question
Title: ToF Laser Sensor (VL53L0X) not working
I have this time of flight laser distance sensor: http://www.dx.com/de/p/cjmcu-vl53l0x-tof-laser-distance-measuring-sensor-module-purple-449081#.WSbn52jyi70

The example code of the VL53L0X-arduino library is not working; I always get the serial message

> 65535 TIMEOUT

However, I guess that the problem is at the sensor. The communication is via I2C, so that the i2c scanner should find it's address, right?

This finder doesnot find any address - am I right, that then the problem is at the sensor?

I connected VCC to (nearly) 5V, GND to GND, SCL to A5 and SDA to A4 (Arduino Uno)

# Answer
> 2 votes
I had the same problem using this sensor. The solution was to connect

* VCC -\> 5V
* GND -\> GND
* SCL -\> A5 (SCL)
* SDA -\> A4 (SDA)
* DNC -x Not connected
* GN2 -\> GND
* XSH -\> 5V
* INT -x Not connected

And then to use the code mentioned here by Ted Meyers. I used Nano with ATmega328P and Arduino IDE 1.8.5.

---

CODE:

```
#include <Wire.h>

#define VL53L0X_REG_IDENTIFICATION_MODEL_ID         0xc0
#define VL53L0X_REG_IDENTIFICATION_REVISION_ID      0xc2
#define VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD   0x50
#define VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD 0x70
#define VL53L0X_REG_SYSRANGE_START                  0x00
#define VL53L0X_REG_RESULT_INTERRUPT_STATUS         0x13
#define VL53L0X_REG_RESULT_RANGE_STATUS             0x14
#define address 0x29

byte gbuf[16];

void setup() {
  // put your setup code here, to run once:
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
  Serial.println("VLX53LOX test started.");
}

void loop() {
  Serial.println("----- START TEST ----");
  test();
  Serial.println("----- END TEST ----");
  Serial.println("");
  delay(4000);
}

void test() {
  byte val1 = read_byte_data_at(VL53L0X_REG_IDENTIFICATION_REVISION_ID);
  Serial.print("Revision ID: "); Serial.println(val1);

  val1 = read_byte_data_at(VL53L0X_REG_IDENTIFICATION_MODEL_ID);
  Serial.print("Device ID: "); Serial.println(val1);

  val1 = read_byte_data_at(VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD);
  Serial.print("PRE_RANGE_CONFIG_VCSEL_PERIOD="); Serial.println(val1);
  Serial.print(" decode: "); Serial.println(VL53L0X_decode_vcsel_period(val1));

  val1 = read_byte_data_at(VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD);
  Serial.print("FINAL_RANGE_CONFIG_VCSEL_PERIOD="); Serial.println(val1);
  Serial.print(" decode: "); Serial.println(VL53L0X_decode_vcsel_period(val1));

  write_byte_data_at(VL53L0X_REG_SYSRANGE_START, 0x01);

  byte val = 0;
  int cnt = 0;
  while (cnt < 100) { // 1 second waiting time max
    delay(10);
    val = read_byte_data_at(VL53L0X_REG_RESULT_RANGE_STATUS);
    if (val & 0x01) break;
    cnt++;
  }
  if (val & 0x01) Serial.println("ready"); else Serial.println("not ready");

  read_block_data_at(0x14, 12);
  uint16_t acnt = makeuint16(gbuf[7], gbuf[6]);
  uint16_t scnt = makeuint16(gbuf[9], gbuf[8]);
  uint16_t dist = makeuint16(gbuf[11], gbuf[10]);
  byte DeviceRangeStatusInternal = ((gbuf[0] & 0x78) >> 3);

  Serial.print("ambient count: "); Serial.println(acnt);
  Serial.print("signal count: ");  Serial.println(scnt);
  Serial.print("distance ");       Serial.println(dist);
  Serial.print("status: ");        Serial.println(DeviceRangeStatusInternal);
}

uint16_t bswap(byte b[]) {
  // Big Endian unsigned short to little endian unsigned short
  uint16_t val = ((b[0] << 8) & b[1]);
  return val;
}

uint16_t makeuint16(int lsb, int msb) {
    return ((msb & 0xFF) << 8) | (lsb & 0xFF);
}

void write_byte_data(byte data) {
  Wire.beginTransmission(address);
  Wire.write(data);
  Wire.endTransmission();
}

void write_byte_data_at(byte reg, byte data) {
  // write data word at address and register
  Wire.beginTransmission(address);
  Wire.write(reg);
  Wire.write(data);
  Wire.endTransmission();
}

void write_word_data_at(byte reg, uint16_t data) {
  // write data word at address and register
  byte b0 = (data &0xFF);
  byte b1 = ((data >> 8) && 0xFF);

  Wire.beginTransmission(address);
  Wire.write(reg);
  Wire.write(b0);
  Wire.write(b1);
  Wire.endTransmission();
}

byte read_byte_data() {
  Wire.requestFrom(address, 1);
  while (Wire.available() < 1) delay(1);
  byte b = Wire.read();
  return b;
}

byte read_byte_data_at(byte reg) {
  //write_byte_data((byte)0x00);
  write_byte_data(reg);
  Wire.requestFrom(address, 1);
  while (Wire.available() < 1) delay(1);
  byte b = Wire.read();
  return b;
}

uint16_t read_word_data_at(byte reg) {
  write_byte_data(reg);
  Wire.requestFrom(address, 2);
  while (Wire.available() < 2) delay(1);
  gbuf[0] = Wire.read();
  gbuf[1] = Wire.read();
  return bswap(gbuf);
}

void read_block_data_at(byte reg, int sz) {
  int i = 0;
  write_byte_data(reg);
  Wire.requestFrom(address, sz);
  for (i=0; i<sz; i++) {
    while (Wire.available() < 1) delay(1);
    gbuf[i] = Wire.read();
  }
}

uint16_t VL53L0X_decode_vcsel_period(short vcsel_period_reg) {
  // Converts the encoded VCSEL period register value into the real
  // period in PLL clocks
  uint16_t vcsel_period_pclks = (vcsel_period_reg + 1) << 1;
  return vcsel_period_pclks;
}

```

# Answer
> 1 votes
You have to pull XSH high (3.3V) in order to turn the device on (either via an I/O port or via a pullup resistor to 3.3V).

Also, the device is rated for a maximum of 3.3V, you might damage it if you connect it to 5V.

Regards

# Answer
> 0 votes
One other thing to check as I had this error myself and it was simply because I hadn't soldered the header pins of the nano or the TOF device which I had just stuck into my breadboard. I am using a iHaospace VL53l0x from Amazon. I only thought of it once I ran the i2C scanner check, which didn't recognise (see) the device, so that go me thinking - (https://gammon.com.au/i2c). The I2C scanner Sketch code to use in Arduino's IDE is two thirds down that page. I also should point out that you need to run the serial monitor at the 115200 baud rate not lower or you might get gobbledygook. Now it all works just as it should with the standard Arduino Adafruit example, no #include wire.h required.

# Answer
> 0 votes
I had this problem. After connecting VL53L0X, the script hung at the start. Scanning of i2c devices also hung up. Washing the soldering points of contacts helped. Apparently the device is very sensitive to dirt on the contacts.

---
Tags: sensors, i2c, communication
---


title: store multiple of float type on EEPROM

text:
# Question
Title: store multiple of float type on EEPROM
I have 7 float variables.

`float temperature, differential, calibration,hta,lta,hha,lha;`

I want to store them all on the EEPROM memory, how do I calculate the addresses given that there type is float.

Thanks!

# Answer
create a struct and store the struct

```
#include <EEPROM.h>

const int DATA_ADDR = 0;

struct MyData {
  float temperature, differential, calibration,hta,lta,hha,lha;
};

MyData data;

void setup() {
  data.temperature = 1.2;

  EEPROM.put(DATA_ADDR, data);

  EEPROM.get(DATA_ADDR, data);
}

void loop() {

}

```
> 2 votes

# Answer
With the `sizeof` function:

```
int nrOfBytesOfTemperature = sizeof(temperature);

```

You can also use directly a type:

```
int nrOfBytesOfFloat = sizeof(float);

```
> 1 votes

---
Tags: arduino-uno, eeprom
---


# Question
Title: read state from button to check if clicked
I"m kinda new here and new to the arduino framework.

I want to build a "menu" using LCD 20\*4, so I want to detect "button clicked" event.

I've connected button to pin 8 and to ground, like this(please ignore the other wiring):

```
int leftButton = 8;

void setup() {
  pinMode(leftButton, INPUT);
  digitalWrite(leftButton, HIGH);
  Serial.begin(9600);

}
bool leftButtonClicked(){
  return digitalRead(leftButton);
}
void loop(){
  delay(20);
  Serial.println(digitalRead(leftButton));
}

```

I am receiveing on the serial `1` while the button is not clicked, and when its clicked I receive `0`.

What is the problem? Thank you guys.

# Answer
As you are a beginner, you seem to have some misconceptions:

* **Reading button state with `digitalRead()`:** You thought something is wrong, because you thought that `digitalRead()` returns, if the button was pressed (thus 1 would mean pressed). But that is not directly the case. `digitalRead()` returns the electrical state of the corresponding pin (if the pin voltage is at ground level (0) or Vcc (supply voltage) level) (1)). This corresponds with the button depending on your wiring. I guess you copied the wiring somewhere in the internet. It shows the most common way of connecting a button. The button consists only of two contacts, which get pressed together, when you press the button. So the button can connect the pin to either ground or Vcc, but not to both. When the button is not pressed, the pin is connected to nothing, thus it is floating and the value changes erratically. This is solved with a pullup or pulldown resistor (a rather big resistor from the pin to either Vcc or ground), which sets the value of the pin, when the button is not pressed. That means, that you need 1 resistor for each button, that you want to use. The good news is: The Arduino already has internal pullup resistors, that you can activate via `pinMode(pin, INPUT_PULLUP)`. That way you can save 1 extra component. Since it is a pullup resistor, which connects the pin with Vcc, you need to connect the button with ground.

That also gives you the inverted logic. In the end it is determined by you, what the `digitalRead()` value means. Think electrically about it.
* **Events:** In Arduino programming there are not events. You are programming very much directly the hardware. There is no OS or GUI system, that would handle events for you. The program, that you write, runs command after command with a specific speed (determined by the Arduinos clock frequency; 16MHz for the Uno), pretty much linearly. Though there is one exception for that: interrupts. Microcontrollers have some peripherals build into them (ADC, communication interfaces, Timers, ...) and many of them work parallel to the main program (since their function does not need code, but is implemented in hardware). These peripherals can generate interrupts (for example to service the peripheral), which pauses the normal run of the program, runs an ISR (Interrupt Service Routine) and then returns to the main program. That is somewhat like an event, but very hardware specific and not nearly as generically usable as events on a PC.
* **Reading a button click:** In your code you don't read the "button click", but only the state of the button. Thus you get multiple times 0 for one long enough button press. For the real click action you need to look for the transition from 1 to 0, which ideally only happens one time per button press. I write "ideally", because real life buttons bounce. In the moment of contact the value changes rapidly multiple times, until the button contacts have settled. So you need to debounce the button. You have already done basic debouncing by using `delay(20)` (because the button may need about that time to stabilize). You can see more sophisticated debouncing in the Bounce2 library, which is also easy to use for reading button clicks and presses.
> 1 votes

---
Tags: arduino-uno, button
---


title: Making a Bluetooth Mouse with Arduino

text:
# Question
Title: Making a Bluetooth Mouse with Arduino
I'm trying to make a bluetooth mouse using Arduino. I will be using an analog 2 axis thumbstick as the sensor. I understand that it's possible to do this with the Arduino connected directly to the computer (https://www.arduino.cc/reference/en/language/functions/usb/mouse/). Would it be possible for the arduino to instead communicate wirelessly using bluetooth? The controller I'm interested in is here: https://www.dfrobot.com/product-1259.html

Thank you!

# Answer
> 1 votes
With that specific board, yes you can. According to this review:

> Bluno also supports the HID (Human Interface Device) mode. When running in this mode, Bluno simulates an input peripheral (keyboard, mouse…) connected via BLE.

---
Tags: arduino-uno, bluetooth, mouse
---


title: Creating a file in an SD card

text:
# Question
Title: Creating a file in an SD card
I have an Arduino Mega connected to an SD card reader (Catalex branded), that at least detects the card as it displays the info of the card. But when I try to create a file, it does not create it. I am using the following code:

```
if (SD.exists("data.txt")) {
  Serial.println("data.txt exists.");
} else {
  Serial.println("data.txt doesn't exist.");
}
File root=SD.open("data.txt", FILE_WRITE); //open of the File for writting
if (SD.exists("data.txt")) {
  Serial.println("data.txt exists.");
} else {
  Serial.println("data.txt doesn't exist.");
}

```

I also tried with this code:

```
File root2 = SD.open("file.txt", O_RDWR | O_APPEND);
    if (!root2) {
       // It failed, so try and make a new file.
        root2 = SD.open("file.txt", O_RDWR | O_CREAT);
        if (!root2) {
          // It failed too, so give up.
        Serial.println("Failed to open file.txt");
         }
    }

```

\[Update\]

I also tried with this easier code and it does not work either:

```
#include <SD.h>

const int chipSelect = 10;
Sd2Card card;

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");
}

void loop() {
  File myFile = SD.open("Data.txt", FILE_WRITE);
  if (myFile) {
    for (int i = 0; i < 101; i++) {
      myFile.print(i);
      myFile.print(" multiplied by two is ");
      myFile.println(i * 2, DEC);
    }
    Serial.println("Finished");
    myFile.close();
  } else {
    Serial.println("Error opening Data.txt");
  }
  //do nothing else
  do { } while(1);
}

```

# Answer
> 2 votes
```
// open a new file and immediately close it:

Serial.println("Creating example.txt...");
myFile = SD.open("example.txt", FILE_WRITE);
myFile.close();

```

This is what you missed (I guess..). Please see the link and check the steps followed:
https://www.arduino.cc/en/Tutorial/Files

# Answer
> 0 votes
If you want to make it sure it will not have problem with SD card format then format it to FAT it's most compatible format type.

---
Tags: arduino-mega, sd-card
---


title: Controllino Mega and Fatek HMI

text:
# Question
Title: Controllino Mega and Fatek HMI
I have a setup that controls the rotation of two stepper motor using Arduino UNO, HBS860H stepper drivers, 4X4 keypad and LCD screen. I have replaced the Arduino Uno by a Controllino Mega and it works good. Now I am trying to replace the Keypad and LCD screen by a FATEK HMI PN2043NK. I have the sketch for the Controllino, I can use RS485 to communicate both devices. I use FV Designer to program the HMI, but I don't understand how to run the sketch from the HMI. I need some help with a simple example Please, any help I could use to start learning to communicate the HMI with the Controllino and run the steppers will be welcome.

# Answer
The usual "sketch" is "always" running on your arduino (Controllino) unless it is put into a non-run mode (like when loading a program) or doesn't have power. What you need in your sketch is to do something IF a command is received on the serial (RS485). Rather than simply running the command you want, the sketch needs to check the serial and only execute the command if the HMI sent the correct signal.

For motor control, you could use G-code where your HMI sends G-code move commands over RS485 and your Controllino executes them. A handy RS232 example is grbl.
> 1 votes

---
Tags: arduino-uno, sketch, display, rs485, modbus
---


# Question
Title: acelermetor count goes down after 1 peak
I am using a Wemos D1 Mini and an mpu 6050 accelerametor. I managed to get the acceleratmetor to work and have 1 value come out of movements. So when a peak it hit (aka, the threshold of 1.00 is hit) n gets incremetented with 1. So it work a bit like a pedometer. This value is pushed to my firebase DB.

However mY problem is that after pushing it once, so the value of n is 1. The program blocks for a second and either slows down bad or the accelerametor value drops to 0. this only happens when i my piece of firebase code in. Im not sure if this causes any delays..

here is my part of my code:

```
#include <Wire.h>

#include "ESP8266WiFi.h"
#include "FirebaseArduino.h"

#define FIREBASE_HOST "xxxxxxxxxx.firebaseio.com" //Without http:// or https:// schemes
#define FIREBASE_AUTH "XXXXXXXXXXXXXXXXXXXXX"
#define WIFI_SSID "Bankai"
#define WIFI_PASSWORD "xxxxxxxxxxxx"

const float HI_THRESHOLD = 1.00;
const float LO_THRESHOLD = 0.70;
bool count_flag = false;

int n= 0; //will be used to store the count
int oldValue = n;
String myString;

const uint8_t MPU_addr = 0x68; // I2C address of the MPU-6050

const float MPU_GYRO_250_SCALE = 131.0;
const float MPU_GYRO_500_SCALE = 65.5;
const float MPU_GYRO_1000_SCALE = 32.8;
const float MPU_GYRO_2000_SCALE = 16.4;
const float MPU_ACCL_2_SCALE = 16384.0;
const float MPU_ACCL_4_SCALE = 8192.0;
const float MPU_ACCL_8_SCALE = 4096.0;
const float MPU_ACCL_16_SCALE = 2048.0;

struct rawdata {
  int16_t AcX; //Acceleration
  int16_t AcY; //Acceleration
  int16_t AcZ; //Acceleration
  int16_t Tmp;
  int16_t GyX; //Gyroscope
  int16_t GyY; //Gyroscope
  int16_t GyZ; //Gyroscope
};

// Using int variables to convert later on to degrees and decimals
struct scaleddata {
  float AcX; //Acceleration
  float AcY; //Acceleration
  float AcZ; //Acceleration
  float Tmp;
  float GyX; //Gyroscope
  float GyY; //Gyroscope
  float GyZ; //Gyroscope
};

bool checkI2c(byte addr);
void mpu6050Begin(byte addr);
rawdata mpu6050Read(byte addr, bool Debug);
void setMPU6050scales(byte addr, uint8_t Gyro, uint8_t Accl);
void getMPU6050scales(byte addr, uint8_t &Gyro, uint8_t &Accl);
scaleddata convertRawToScaled(byte addr, rawdata data_in, bool Debug);

//start connection, serial, and connection to db
void setup() {
  Wire.begin();
  Serial.begin(115200);

  mpu6050Begin(MPU_addr);

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(100);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
    Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

}

//if the value now is different from the current value it gets pushed to the DB, otherwise a flood of numbers apperars.
void loop() {
  rawdata next_sample;
  setMPU6050scales(MPU_addr, 0b00000000, 0b00010000);
  next_sample = mpu6050Read(MPU_addr, false);
  convertRawToScaled(MPU_addr, next_sample, false);

```

I feel likeit is thei part which creates the bottleneck.

```
  //myString = String(n);
  if(oldValue != n){
   Firebase.setInt("Reps/Value", n);
  }
  delay(100); // Wait 5 seconds and scan again

}

 float filterConstant = 0.05;
  values.AcX = (float) data_in.AcX / scale_value;
  values.AcY = (float) data_in.AcY / scale_value;
  values.AcZ = (float) data_in.AcZ / scale_value;
  filteredAx = filteredAx * (1.0 - filterConstant) + values.AcX * filterConstant;
  filteredAy = filteredAy * (1.0 - filterConstant) + values.AcY * filterConstant;
  filteredAz = filteredAz * (1.0 - filterConstant) + values.AcZ * filterConstant;
  float result = sqrt((filteredAx * filteredAx) + (filteredAy * filteredAy ) + (filteredAz * filteredAx ));

//  Serial.print(values.AcX); Serial.print("\t");
//  Serial.print(filteredAx); Serial.print("\t");

  Serial.println(result);

  //    Serial.print(values.AcY); Serial.print("\t");
  //    Serial.print(values.AcZ);
//  Serial.println();

 if( result > HI_THRESHOLD && !count_flag) //if analog_in > Hi_THRESHOLD and count_flag == false
     {
           n++;
           count_flag = true;
     }

     if(result <= HI_THRESHOLD) //set count_flag to false only when below the threshold
           count_flag = false;

  Serial.println(n);

  return values;
}

```

Can you help me find the problem? Thank you!

# Answer
> 1 votes
Logging the data is indeed what slows your program down. You can't avoid that. There are several ways to deal with it depending on what you need.

Instead of logging data all the time, you could try to accumulate a bunch of data and then write it. This approach of buffering data will still fail to read while you log, but you will be able to get bursts of good data in between.

---
Tags: esp8266, programming, accelerometer, datalogging, signal-processing
---


title: random soft wdt reset while request

text:
# Question
Title: random soft wdt reset while request
i am making post requests with esp8266 on nodeMCU. i have a messy code so i dont want to annoy you with showing it here. the problem is i get soft wdt reset time to time while making request. for example i change piece of code(removing or adding some `serial.println` lines) and i see i get soft wdt reset right there in `http.post`.

i tried my best to avoid Strings. I only used a few times, without in the loop. I am only using WiFiClientSecureBearSSL with FirebaseESP8266.

do you have any idea what cause this problem?

# Answer
> 3 votes
Show examples of the error - and install ESPexeption decoder to analyse the stack trace this will at least show why the wdt was caused
So the only thing as of now I can recommend
There is an issue with bearssl:

It's a WDT error caused by an extended SSL negotiation.

* Change the core frequency to 160MHz (if not already done) and try again.
* Use instead of LWIP1.4 (memory hog) low-mem LWIP2.0 with your program.
* Since SSL negotiation can take 5 seconds even at 160MHz for some websites be sure by adding a yield() not to trigger a wdt reset

So without code/ trace and error messages its hard to guess

---
Tags: esp8266, http
---


# Question
Title: NodeMCU stops responding after several hours
I'm controlling some devices through a relay and a NodeMCU, it works fine and reconnects without problem in the meantime I'm testing it, but after I leave it like for 3 or more hours, it stops responding. I need this system to always be working without sleeping or anything. Here is my code:

```
#include <ESP8266WiFi.h>

const char* ssid = "wifi_Guerrero ";
const char* password = "3245968530";

int ledPin = 13; // GPIO13
int ledPin2 = 12; // GPIO13
int desconectado = 5;
int conectado = 4;
WiFiServer server(80);
WiFiClient client;

int counter = 0;

void setup() {
  Serial.begin(9600);
  delay(10);

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

  pinMode(ledPin2, OUTPUT);
  digitalWrite(ledPin2, LOW);

  pinMode(conectado, OUTPUT);
  pinMode(desconectado, OUTPUT);
  digitalWrite(desconectado, HIGH);

  connectWifi();

  Serial.print(F("Setting static ip to : "));
  Serial.println(WiFi.localIP());

  // Start the server
  server.begin();
  Serial.println("Server started");

}

void loop() {

  delay(200);

  if (WiFi.status() != WL_CONNECTED) {
    delay(100);
    digitalWrite(conectado, LOW);
    digitalWrite(desconectado, HIGH);
   connectWifi();
  }

  // Check if a client has connected
  client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  int t = millis();
  while(!client.available()){
  delay(1);
  if (millis()-t>130) return;
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request
  if (request.indexOf("/switch") != -1)  {
    digitalWrite(ledPin, !digitalRead(ledPin));
    digitalWrite(ledPin2, !digitalRead(ledPin2));
    printSwitch();
  }else if (request.indexOf("/uno") != -1) {
    client.print("Canal 1 apagagado | Canal 2 encendido");
    digitalWrite(ledPin, HIGH);
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/dos") != -1){
    client.print("Canal 1 encendido | Canal 2 apagado");
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/tres") != -1){
    client.print("Canal 1 apagado | Canal 2 apagado");
    digitalWrite(ledPin, HIGH);
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/cuatro") != -1){
    client.print("Canal 1 encendido | Canal 2 encendido");
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/cinco") != -1){
    printIP();
  }else if (request.indexOf("/apagaruno") != -1){
    client.print("Canal 1 apagado");
    digitalWrite(ledPin, HIGH);
  }else if (request.indexOf("/apagardos") != -1){
    client.print("Canal 2 apagado");
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/prenderuno") != -1){
    client.print("Canal 1 encendido");
    digitalWrite(ledPin, LOW);
  }else if (request.indexOf("/prenderdos") != -1){
    client.print("Canal 2 encendido");
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/canaluno") != -1){

    if(digitalRead(ledPin) == HIGH) {
      client.print("Off");
  } else {
    client.print("On");
  }

  }else if (request.indexOf("/canaldos") != -1){

    if(digitalRead(ledPin2) == HIGH) {
    client.print("Off");
  } else {
    client.print("On");
  }

  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

void printSwitch(){
  if(digitalRead(ledPin) == LOW) {
    client.print("Canal 1 Encendido");
  } else {
    client.print("Canal 1 Apagado");
  }
  Serial.println("");
  if(digitalRead(ledPin2) == LOW) {
    client.print("Canal 2 Encendido");
  } else {
    client.print("Canal 2 Apagado");
  }
}

void printIP(){
  delay(100);
  client.print(WiFi.localIP());
}

void connectWifi()
{
  Serial.print("Connecting to "+*ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
  }

  // config static IP
  IPAddress ip(192, 168, 0, 8);
  IPAddress gateway(192, 168, 0, 1);
  IPAddress subnet(255, 255, 255, 0);
  WiFi.config(ip, gateway, subnet);
  digitalWrite(conectado, HIGH);
  digitalWrite(desconectado, LOW);
  Serial.println("");
  Serial.println("Connected");
  Serial.println("");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}//end connect

```

# Answer
> 0 votes
I think thatthe problem lies with this definition

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

```

which you define dynamically in loop this leads possibly to heap fragmentation, causing resets after sometime
Define a global char array

```
char request [256] ={'\0'};
char c;
uint cc = 0;

```

and work instead the String functions with

```
while(client.available()){
c = client.read();
if (c != '\r'){
  request[cc] = c;
   cc++;
 }
 else return;
}

```

then handle the filled request buffer like

```
if (strcmp(request,"/switch") != 0)  {
  ....
 }

```

This should keep you esp running

---
Tags: esp8266, nodemcu
---


# Question
Title: Arduino Mega2560, Ethernet Shield & OV0706: "Camera not found"
I want to take a picture with the OV0706 and save it to an SD card. I'm using an Arduino Mega2560, Ethernet Shield (with SD slot) and an OV0706. I tried the tutorial for this camera from Adafruit, but I'm still getting a 'No camera found?' error.

I thought it had something to do with assigning the pins, but if I connect the RX from the OV0706 with A15 on the Mega (see picture), it still gives the same error.

```
// On Mega: camera TX connected to pin 69 (A15), camera RX to pin 3:
SoftwareSerial cameraconnection = SoftwareSerial(69, 3);

```

The code (important part):

```
// This is a basic snapshot sketch using the VC0706 library.
// On start, the Arduino will find the camera and SD card and
// then snap a photo, saving it to the SD card.
// Public domain.

// If using an Arduino Mega (1280, 2560 or ADK) in conjunction
// with an SD card shield designed for conventional Arduinos
// (Uno, etc.), it's necessary to edit the library file:
//   libraries/SD/utility/Sd2Card.h
// Look for this line:
//   #define MEGA_SOFT_SPI 0
// change to:
//   #define MEGA_SOFT_SPI 1
// This is NOT required if using an SD card breakout interfaced
// directly to the SPI bus of the Mega (pins 50-53), or if using
// a non-Mega, Uno-style board.

#include <Adafruit_VC0706.h>
#include <SPI.h>
#include <SD.h>

// comment out this line if using Arduino V23 or earlier
#include <SoftwareSerial.h>

// uncomment this line if using Arduino V23 or earlier
// #include <NewSoftSerial.h>

// SD card chip select line varies among boards/shields:
// Adafruit SD shields and modules: pin 10
// Arduino Ethernet shield: pin 4
// Sparkfun SD shield: pin 8
// Arduino Mega w/hardware SPI: pin 53
// Teensy 2.0: pin 0
// Teensy++ 2.0: pin 20
#define chipSelect 4

// Pins for camera connection are configurable.
// With the Arduino Uno, etc., most pins can be used, except for
// those already in use for the SD card (10 through 13 plus
// chipSelect, if other than pin 10).
// With the Arduino Mega, the choices are a bit more involved:
// 1) You can still use SoftwareSerial and connect the camera to
//    a variety of pins...BUT the selection is limited.  The TX
//    pin from the camera (RX on the Arduino, and the first
//    argument to SoftwareSerial()) MUST be one of: 62, 63, 64,
//    65, 66, 67, 68, or 69.  If MEGA_SOFT_SPI is set (and using
//    a conventional Arduino SD shield), pins 50, 51, 52 and 53
//    are also available.  The RX pin from the camera (TX on
//    Arduino, second argument to SoftwareSerial()) can be any
//    pin, again excepting those used by the SD card.
// 2) You can use any of the additional three hardware UARTs on
//    the Mega board (labeled as RX1/TX1, RX2/TX2, RX3,TX3),
//    but must specifically use the two pins defined by that
//    UART; they are not configurable.  In this case, pass the
//    desired Serial object (rather than a SoftwareSerial
//    object) to the VC0706 constructor.

// Using SoftwareSerial (Arduino 1.0+) or NewSoftSerial (Arduino 0023 & prior):
#if ARDUINO >= 100
// On Uno: camera TX connected to pin 2, camera RX to pin 3:
//SoftwareSerial cameraconnection = SoftwareSerial(2, 3);
// On Mega: camera TX connected to pin 69 (A15), camera RX to pin 3:
SoftwareSerial cameraconnection = SoftwareSerial(69, 3);
#else
NewSoftSerial cameraconnection = NewSoftSerial(2, 3);
#endif

Adafruit_VC0706 cam = Adafruit_VC0706(&cameraconnection);

// Using hardware serial on Mega: camera TX conn. to RX1,
// camera RX to TX1, no SoftwareSerial object is required:
//Adafruit_VC0706 cam = Adafruit_VC0706(&Serial1);

void setup() {

  // When using hardware SPI, the SS pin MUST be set to an
  // output (even if not connected or used).  If left as a
  // floating input w/SPI on, this can cause lockuppage.
#if !defined(SOFTWARE_SPI)
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  if(chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
#else
  if(chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
#endif
#endif

  Serial.begin(9600);
  Serial.println("VC0706 Camera snapshot test");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }

  // Try to locate the camera
  if (cam.begin()) {
    Serial.println("Camera Found:");
  } else {
    Serial.println("No camera found?");
    return;
  }

```

Thanks in advance.

(Pictures: http://prntscr.com/apdvi9 )

# Answer
Since at least my camera needs up to 2 seconds to initialize, I think the

```
if (cam.begin()) {
Serial.println("Camera Found:");
} else {
Serial.println("No camera found?");

```

returns immediately what it thinks No camera found

Try it with

```
    unsigned long timer = millis();
    Serial.println("Camera initializing:");
    while (!cam.begin()) {
    Serial.print(".");
    if (millis()-timer>3000) {
      Serial.println("No camera found?");
      break;
      }
    }

```
> 0 votes

---
Tags: arduino-mega, sd-card
---


title: Car PA system enhancement

text:
# Question
Title: Car PA system enhancement
Hello i have one of these

My goal for this project is to have a higher quality mic and be able to play music through it

My question is how would i link a 3.5mm aux cable to the arduino as input and output to the rj9 line. I have prior knowlege on liking a aux as i have setup my Christmas lights as a vu meter using relays and a aux but the confusing part is the rj9 line

Are the speaker pins only to trigger a relay and allow power to flow from the car battery or am i completely wrong if im right i assume i could just solder the audio jacks positive negative to the rj9 mic positive negative and then find a method to triger the speaker relay

# Answer
> 1 votes
"how would i link a 3.5mm aux cable to the arduino as input and output to the rj9 line" - the arduino uno doesn't have a digital to analog converter, so without external hardware it's not possible to make him generate the audio signal. Also its ADCs are not fast enough to sample an audio signal coming from a microphone at a sufficient sample rate (I think the maximum are 1-2kHz). As you explicitly want to improve sound quality this is an issue.

When using an arduino uno you might be better off using an external audio circuit which only gets switched on and off by the arduino. Controlling the siren's buttons will not be a big difficulty. You have to do some reverse engineering to find out the siren's logic level and how the buttons are used in the device. You can probably simply replace them with mosfets, but that is an electronic issue.

---
Tags: arduino-uno
---


# Question
Title: Is there some better documentation somewhere for Arduino classes and API's?
For example, it looks like Serial extends HardwareSerial, which extends Stream, which extends Print. But I don't think you can figure this out by reading the reference documentation on https://www.arduino.cc/ and it doesn't appear that you can easily navigate the class hierarchy in the Arduino IDE. They seem to go out of their way to hide the class hierarchy?

I guess I'm spoiled by modern languages that have automatically generated documentation, but it seems like there should be a more complete reference somewhere?

# Answer
> 1 votes
What I did/do when loading a new core is generating a doxygen visualisation help class hierachy in HTML. Although most of the core libs have no detailed doxygen documenation the dot/graphviz solves the problem without installation of other IDEs (which also have their specific problems, or need a lot of learning).
As an added bonus I can document my source code in a clean and transparent way available in most IDEs and OS.

---
Tags: documentation
---


title: USB device not recognised - windows 8.1

text:
# Question
Title: USB device not recognised - windows 8.1
I'm a beginner with Arduino and i have acquired the Arduino UNO R3 board. i have followed the instructions on arduino website in order to install the board, however it fails and still remains as an unrecognised device.

**consequently, arduino IDE reports that COM1 is not found, and the 'ports' menu is grayed out.**

steps i have tried:

**1) install the Arduino 1.0.5 IDE**
\- the installation failes near the end when installing the arduino board **
2) install the Arduino 1.5.7 BETA IDE**
\- the installation is successful but arduino device is still unrecognized. **
3) i have tried manually installing the drivers by letting windows search in the arduino IDE installation folder/drivers/**
\- it reports that the best driver is already installed - "usb unrecognized device" **
4) i have tried installing the drivers by manulally loading the `.inf` files from the IDE installation folders, and installing all the `serial converter A/B/C/D` in the list**
\- all failed to install.

i have done all the above for both IDE 1.0.5 and 1.5.7b with windows installer And zipped files, under administrative rights in windows 8.1

How do i get this to work?

# Answer
The issue was resolved by changing my USB cable. the cable in the kit was new and seemed to supply power to the arduino board, but windows was unable to identify the board using that cable. maybe the data wires were damaged.
in any case, i changed the cable and everything worked smoothly.
> 1 votes

# Answer
To solve this problem.

**1.** connect your Arduino board to the PC / Laptop. **2.** open control panel. and go to **view devices and printers**

**3.** Here You can see a **unknown device**... i.e. your arduino board. double click on it.  **4** Click on hardware..................................................  **5.** Now Choose **Update Driver**... Choose the location where the **Arduino IDE is installed**... And go to **Next** **6.** Now your computer will recognise your arduino board
> 0 votes

# Answer
Right click on devices list from Manager update driver and choose the folder with name "driver" in your arduino IDE app that you use Ok and the card ll be recognized good luck
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Why is delay(1000) breaking my serial communication?
I have the following sketch...

```
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
}

void loop() {
  if(Serial.available() > 0){
    Serial.println("Hello world from Ardunio!");
  }
}

```

This works great with my client code...

```
import SerialPort from 'serialport';
const port = new SerialPort('/dev/ttyACM0', {
  baudRate: 115200,
  autoOpen: false
})

port.open(function (err) {
  if (err) {
    return console.log('Error opening port: ', err.message)
  }

  // Because there's no callback to write, write errors will be emitted on the port:
  console.log("port opened");
  port.on('readable', function () {
    console.log('Data:', port.read())
  })
})

```

Now I want to slow it down so I change the sketch to...

```
void loop() {
  if(Serial.available() > 0){
    Serial.println("Hello world from Ardunio!");
  }
  delay(10000);
}

```

I would expect this to delay each message by 10 seconds, however, it seems to never rerun so I do not get any messages. What am I missing? Why would delay break the loop?

# Answer
> 2 votes
NEVER use delay() in a loop - its a bad habit you get used to and then you return later on with complex code asking why nothing is happening or your webserver is dead for 10 seconds every time you receive a request.

So instead of

```
void loop() {
  if(Serial.available() > 0){
    Serial.println("Hello world from Ardunio!");
  }
  delay(10000);
 }

```

you would do

```
unsigned long timerStart = 0;
unsigned long myTimer = 10000;

setup(){....}

 void loop() {
  if(Serial.available() > 0 ){
     if(millis() - timerStart > myTimer){      // non blocking
       Serial.println("Hello world from Ardunio!");
       timerStart = millis(); // reset timer
     }
   }
 }

```

What your code does at the moment is enter the IF clause if exactly in this millis the buffer is filled, then wait for ten seconds ignoring whatever you do. Next chance tohit and so on. Delay() is blocking processing =\> not a good thing todo in communication scenarios,

# Answer
> 1 votes
Get rid of `if(Serial.available() > 0)`. You only need that if statement if you're expecting information from `Serial`, but it doesn't seem to be the case for your project.

Also, only use `delay()` if you have a really good reason to.

---
Tags: serial
---


title: Arduino "Phantom Powering"

text:
# Question
Title: Arduino "Phantom Powering"
I am using an Arduino Uno in my project. I recently found that if I disconnect the power from my Arduino (I am powering it by USB port, from a 5V regulator - 7805), then it remains under power from the input pins. I also found that if I disconnect the 3 digit 7 segment common anode display (which is also powered from same 7805) and if I remove the LM358 (which is again powered from the same 7805) from the socket, then my Arduino is not powered anymore. My questions are:

1. Is my setup correct - if I am powering it from the 5V regulator (7805) through the USB port ?
2. My Arduino and the other components from the schematic - the display, the LM358, the mosfet - will be powered on at the same time, when the 230V switch that is placed on the mains input of the 24V SMPS is closed. Could this be a problem in terms of "phantom powering" ? Is there any better way to power the Arduino when I have 5V regulated supply on the schematic ? I will always keep connected the Arduino to the 5V output of the 7805 to the USB port.

Please find attached 2 schematics, one is the main PCB (the one with Arduino) and the other schematic is the one with the display, which is placed on the front panel. The J2 connector from first schematic is connected pin to pin to the J2 from second schematic.

https://ibb.co/QnLHsM0

https://ibb.co/KxLFKsQ

# Answer
> 1 votes
> Is my setup correct - if I am powering it from the 5V regulator (7805) through the USB port ?

Yes.

> My Arduino and the other components from the schematic - the display, the LM358, the mosfet - will be powered on at the same time, when the 230V switch that is placed on the mains input of the 24V SMPS is closed. Could this be a problem in terms of "phantom powering" ? Is there any better way to power the Arduino when I have 5V regulated supply on the schematic ? I will always keep connected the Arduino to the 5V output of the 7805 to the USB port.

Not really.

Your problem only occurs when you "break" the system by separating the 5V from the Arduino - at which point current flows from the output of the op-amp and through the LED displays, through the IO pins, up through the clamping diodes inside the IO pins, and to the Arduino's 5V.

Since it only happens if you disconnect the 5V and you don't intend to disconnect the 5V then it's not a problem. However if you wanted to improve it then you could take the output of the 5V reguator and feed that direct into the Arduino's USB port. You could then power all the other devices that run at 5V from the Arduino's 5V pin. That way if you remove the 5V from the Arduino then you also remove it from all the other 5V devices that potentially feed power back in.

# Answer
> 1 votes
When you disconnect the arduino from 5V you must also remove either

* disconnect any other device that is connected to the arduino and has its own power supply
* or disconnect every device that is connected to the arduino from its power supply

When you disconnect 5V from the arduino while devices connected to a gpio are still powered, this gpio might see a voltage larger than zero. But the voltage at any pin must not exceed the arduino's actual supply voltage by more than 0.3V. Otherwise the atmega's supply rail will be pulled high through esd protection diodes and the atmega will try to operate. It will then probably draw more current than what the esd diodes are rated for and they will eventually fail (destroying that gpio).

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


title: Can not receive data from Python code

text:
# Question
Title: Can not receive data from Python code
I want to send 4 float numbers from Python code to an Arduino; I was trying to send it via serial and I have some problems.

**here is my Python code:**

```
import time
import serial
import struct

data = serial.Serial('COM6', 9600, timeout=1)
time.sleep(1)

while True:
   a = str(47.256*1000)
   data.write(a.encode())

```

**Here is my Arduino code :**

```
String msg;

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

void loop()
{
  if (Serial.available()) {
    msg = Serial.readString();
  }

  if (msg.toInt()>30){
    digitalWrite(13, 1);
  }
}

```

**end of code**

Thanks in advance.

My problem is that it does not work (LED does not turn on while I send data from the Python code in a while loop; when I remove the while and make it send data 1 time it works (LED turns on). Any ideas why this could be happening?

# Answer
It would be easier if you used Arduino \<--\> Python compatible libraries to ensure the communication between the two is robust and reliable. An example of such libraries would be pySerialTransfer and SerialTransfer.h.

pySerialTransfer is pip-installable and cross-platform compatible. SerialTransfer.h runs on the Arduino platform and can be installed through the Arduino IDE's Libraries Manager.

Both of these libraries have highly efficient and robust packetizing/parsing algorithms with easy to use APIs.

**Example Python Script:**

```
import time
from pySerialTransfer import pySerialTransfer as txfer

if __name__ == '__main__':
    try:
        link = txfer.SerialTransfer('COM17')

        link.open()
        time.sleep(2) # allow some time for the Arduino to completely reset

        while True:
            send_size = 0

            ###################################################################
            # Send a list
            ###################################################################
            list_ = [1, 3]
            list_size = link.tx_obj(list_)
            send_size += list_size

            ###################################################################
            # Send a string
            ###################################################################
            str_ = 'hello'
            str_size = link.tx_obj(str_, send_size) - send_size
            send_size += str_size

            ###################################################################
            # Send a float
            ###################################################################
            float_ = 5.234
            float_size = link.tx_obj(float_, send_size) - send_size
            send_size += float_size

            ###################################################################
            # Transmit all the data to send in a single packet
            ###################################################################
            link.send(send_size)

            ###################################################################
            # Wait for a response and report any errors while receiving packets
            ###################################################################
            while not link.available():
                if link.status < 0:
                    if link.status == -1:
                        print('ERROR: CRC_ERROR')
                    elif link.status == -2:
                        print('ERROR: PAYLOAD_ERROR')
                    elif link.status == -3:
                        print('ERROR: STOP_BYTE_ERROR')

            ###################################################################
            # Parse response list
            ###################################################################
            rec_list_  = link.rx_obj(obj_type=type(list_),
                                     obj_byte_size=list_size,
                                     list_format='i')

            ###################################################################
            # Parse response string
            ###################################################################
            rec_str_   = link.rx_obj(obj_type=type(str_),
                                     obj_byte_size=str_size,
                                     start_pos=list_size)

            ###################################################################
            # Parse response float
            ###################################################################
            rec_float_ = link.rx_obj(obj_type=type(float_),
                                     obj_byte_size=float_size,
                                     start_pos=(list_size + str_size))

            ###################################################################
            # Display the received data
            ###################################################################
            print('SENT: {} {} {}'.format(list_, str_, float_))
            print('RCVD: {} {} {}'.format(rec_list_, rec_str_, rec_float_))
            print(' ')

    except KeyboardInterrupt:
        link.close()

    except:
        import traceback
        traceback.print_exc()

        link.close()

```

**Example Arduino Sketch:**

```
#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  if(myTransfer.available())
  {
    // send all received data back to Python
    for(uint16_t i=0; i < myTransfer.bytesRead; i++)
      myTransfer.txBuff[i] = myTransfer.rxBuff[i];

    myTransfer.sendData(myTransfer.bytesRead);
  }
}

```

Note that you can send more than just individual chars with these libraries. It is possible to transfer floats, ints, bytes, arrays, and even structs (or any combination of the like) within your program using the libraries! See the examples in SerialTransfer.h for more info

**For theory behind robust serial communication,** check out the tutorials Serial Input Basics and Serial Input Advanced.
> 1 votes

---
Tags: serial, python, float, data
---


# Question
Title: Error messages while verifying code with Visual Studio Code
I move recently to use Visual Studio Code to develop for arduino. But I'm receiving some error messages while I'm trying to verify my code that confuse me. The messages are:

```
2020-04-12T13:53:40.409Z INFO c.a.u.n.HttpConnectionManager:148 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Connect to https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA, method=GET, request id=20892E5EE7E84976
2020-04-12T13:53:40.926Z INFO c.a.u.n.HttpConnectionManager:152 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Request complete URL="https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA", method=GET, response code=404, request id=20892E5EE7E84976, headers={null=[HTTP/1.1 404 Not Found], Cache-Control=[no-cache, no-store, must-revalidate], Server=[nginx], Connection=[keep-alive], Vary=[Origin], Pragma=[no-cache], Expires=[0], Content-Length=[0], Date=[Sun, 12 Apr 2020 13:53:41 GMT]}
2020-04-12T13:53:40.926Z WARN p.a.h.BoardCloudResolver:64 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Fail to get the Vid Pid information from the builder response code=404
2020-04-12T13:53:40.937Z INFO c.a.u.n.HttpConnectionManager:148 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Connect to https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA, method=GET, request id=D8C082A90BB14CDF
2020-04-12T13:53:41.044Z INFO c.a.u.n.HttpConnectionManager:152 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Request complete URL="https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA", method=GET, response code=404, request id=D8C082A90BB14CDF, headers={null=[HTTP/1.1 404 Not Found], Cache-Control=[no-cache, no-store, must-revalidate], Server=[nginx], Connection=[keep-alive], Vary=[Origin], Pragma=[no-cache], Expires=[0], Content-Length=[0], Date=[Sun, 12 Apr 2020 13:53:41 GMT]}
2020-04-12T13:53:41.044Z WARN p.a.h.BoardCloudResolver:64 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Fail to get the Vid Pid information from the builder response code=404

```

Based on this output it seems something is happening with these URLs but when I try to do the same in the same computer with Arduino IDE there is no such error messages.

Does anybody know how to get rid of these messages?

Thank you very much.

# Answer
> 1 votes
It works with Arduino IDE either 1.8.9 OR 1.8.12 BUT the VS code extension is broken. So

* You have to downgrade to January release 1.42 **AND**
* Then turn off automatic updates for the moment.

How to get the release: Click here

Before installing /downgrade
The excessive debug logging is caused by running Java with -DDEBUG=true. Adding -DDEBUG=false to the C:\Program Files (x86)\Arduino\arduino\_debug.l4j.ini fixes it for now.

---
Tags: visualstudio
---


# Question
Title: Why are my motors attached to an Arduino MEGA not running?
I verified my code and uploaded it to the board and that was successful.

Info: \- Using Mega 2560 Arduino Board with Adafruit V1 \- 3 DC 12 volt motors \- on HP computer

Here is my code:

```
#include <AFMotor.h>

AF_DCMotor motor(1, MOTOR12_8KHZ);
AF_DCMotor motor2(2, MOTOR12_8KHZ);
AF_DCMotor motor3(2, MOTOR12_1KHZ);

void setup()  {
  Serial.begin(9600);
  Serial.println("Motor Test!");
  motor.setSpeed(20); //set speed of motor
  motor2.setSpeed(20); //set speed of motor
  motor3.setSpeed(25); //set speed of motor
}

void loop() {
  Serial.print("tick");
  motor.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor.run(RELEASE);
  delay(5000);

  Serial.print("tack"); //first song starts
  motor.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor.run(RELEASE);
  delay(14000);

  Serial.print("tack");
  motor.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //first song ends
  motor.run(RELEASE);
  delay(13000);

  Serial.print("tick");
  motor.run(FORWARD);
  delay(2000);

  Serial.print("tock"); //second song starts
  motor.run(RELEASE);
  delay(24000);

  Serial.print("tick");
  motor.run(FORWARD);
  delay(2000);

  Serial.print("tock"); //second song ends
  motor.run(RELEASE);
  delay(17000);

   Serial.print("tick");
  motor.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //third song starts
  motor.run(RELEASE);
  delay(23000);

  Serial.print("tick");
  motor.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //third song ends
  motor.run(RELEASE);
  delay(21000);

  Serial.print("tick");
  motor.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor.run(RELEASE);
  delay(5000);

  Serial.print("tick");
  motor.run(FORWARD);
  delay(3000);

  Serial.print("tack"); //fourth song starts
  motor.run(RELEASE);
  delay(5000);

  Serial.print("tack");
  motor.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //fourth song ends
  motor.run(RELEASE);
  delay(21000);
   //waving motor
  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(5000);

  //Waving motor
  Serial.print("tick"); //first song starts
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

   Serial.print("tock");
  motor2.run(FORWARD);
  delay(1000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //first song ends
  motor2.run(RELEASE);
  delay(14000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(5000);

  Serial.print("tack"); //SEcond song starts
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

   Serial.print("tock");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //second song ends
  motor2.run(RELEASE);
  delay(15000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(5000);

  Serial.print("tack"); //Third song starts
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

   Serial.print("tock");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tock"); //third song ends
  motor2.run(RELEASE);
  delay(14000);

  Serial.print("tick"); //fourth song starts
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

   Serial.print("tock");
  motor2.run(FORWARD);
  delay(1000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //fourth song ends
  motor2.run(RELEASE);
  delay(7000);

  //dancing motor
  Serial.print("tock"); //first song starts
  motor3.run(RELEASE);
  delay(11000);

  Serial.print("tick");
  motor3.run(FORWARD);
  delay(22000);

  Serial.print("tock"); //first song stops //second song starts
  motor3.run(RELEASE);
  delay(16000);

    Serial.print("tick"); //Second song stops
  motor3.run(FORWARD);
  delay(28000);

  Serial.print("tock"); //Third song starts
  motor3.run(RELEASE);
  delay(15000);

  Serial.print("tick"); //Third song stops
  motor3.run(FORWARD);
  delay(33000);

  Serial.print("tock"); //fourth song starts
  motor3.run(RELEASE);
  delay(16000);

  Serial.print("tick");
  motor3.run(FORWARD);
  delay(5000);

  Serial.print("tock");
  motor3.run(RELEASE);
  delay(1000);

  Serial.print("tick"); //fourth song ends
  motor3.run(FORWARD);
  delay(16000);

  Serial.print("tock");
  motor3.run(RELEASE);
  delay(5000);
}

```

# Answer
As you did not give details I assume the following:

* You supply the MEGA via USB or external 5-12V power supply
* the motors are supplied via an extra external 12V power supply with sufficiant amperage
* All cabeling is checked and correct

Looks like this schematic (without 12V power supply attached to the motor shield)

To your code:

* Get rid of the delay()s - they block processing so what happens:

```
 motor.run(FORWARD);  // => You give a command via lib
 delay(2000); // You stop your processing so the motor is not running

```

so you have two options both need the definition of a timeStamp var

* working with a (blocking) while loops
* or creating a finite state machine (search here on SO for details)

So I will for simplicity use the first approach

```
 // Copy this var before your setup
 unsigned long timeStamp = 0;
// use your complete setup
 void setup(){...}
 // Change your loop functions like thes first three converted lines
 void loop(){
  timeStamp = millis();
  Serial.print("tick");
  while(millis()-timeStamp < 2000){
     motor.run(FORWARD);
  }
  timeStamp = millis();   // resets the time to current
  Serial.print("tock");
  while(millis()-timeStamp < 5000){
     motor.run(RELEASE);
  }
  timeStamp = millis();   // resets the time to current
  Serial.print("tack"); //first song starts
  while(millis()-timeStamp < 2000){
     motor.run(BACKWARD);
  }
// .... AND SO ON .....
}

```

Be aware that the whiles are blocking but for your sequential processing its ok.
> 4 votes

---
Tags: arduino-mega, motor, adafruit, hardware
---


# Question
Title: How to assign a string-variable to a StackString based on the StackString-library?
I'm trying to use the StackString-library which offers not to eat up RAM over time by re-assigning values to strings. I started from scratch and wrote a very basic democode which works. Then I added an assignment to a STackString-variable from a normal string or a function with return-value string See code below If I try to compile I get a compiler-error saying no matching function for call to 'Stack::StackString\<50\>::append(String&)'

here is the code

```
#include <StackString.hpp>
using namespace Stack;  // it is very important to have this line of code. Otherwise the code won't compile

StackString<50> myString = StackString<50>("Hello, World!");

String NormalString = "1234Test";

void setup()
{
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  Serial.println(myString.c_str());

  myString.prepend("Everybody say: ");
  Serial.println(myString.c_str());

  myString.append(" How are you doing?");
  Serial.println(myString.c_str());
  Serial.println();

  //myString = NormalString;
  myString.append(NormalString);

}

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

}

```

Do I have to do some typecasting? and if yes how does it look like? WHat I want to do is assigning a StackString a new value. This means the STackString is on the left side of the "=" assigning operator. I have tried different variants to no avail.

Could this be a problem of the special construction as a "namespace" ? No idea no clue

you find the STackString-library here: https://gitlab.com/arduino-libraries/stackstring

best regards

Stefan

# Answer
`StackString` doesn't know what a `String` is. The `append` function only accepts a `const char *`, a `const char` or an `int`:

```
void append(const char* string);
void append(const char character);
void append(int number);

```

You can get a `const char *` from a `String` easily enough with `.c_str()`, so use that in the append:

```
myString.append(NormalString.c_str());

```

There is also no simple assignment (or complete content replacement) with `StackString` \- you have to "clear" the string first. So to replace the content with what is in `NormalString` you would:

```
myString.clear();
myString.append(NormalString.c_str());

```
> 0 votes

---
Tags: string
---


# Question
Title: Arduino digital pin input used to power device?
I am attempting to debug a W65C02 and I am using an Arduino Mega to look at the inputs and outputs of the device, which is behaving weird.

I have Pin 22 to 52 connected as INPUT on the MEGA and they are all connected to A0-A15 and D0-D7 on the 6502. However when I unplug my Arduino and keep the 6502 powered on it seems to stay on in that the power light is on. Is something fried or is this normal behavior?

Nothing else is plugged in to the Arduino except GND and the digital inputs.

# Answer
> 1 votes
Arduino get the power from the port of 6502 via the protecting diod in the Arduino port. This the normal behavior. // Mikael

# Answer
> 1 votes
tl;dr: Don't **do** that.

As a general rule with CMOS digital circuits you don't want logic pin input voltages to be significantly higher than the VCC power input. (The same is true for TTL for that matter.) Doing that risks damage to the circuit.

That means that if a chip/board is not powered, you should not drive the logic lines at all.

`Carlmikael` says the behavior you are seeing is normal. I would call it *expected*, but I would not call it normal. It's "a normal error response" to a circuit being driven in a way that could damage it.

---
Tags: arduino-mega
---


title: Digispark - Bootloader stuck

text:
# Question
Title: Digispark - Bootloader stuck
I have a digispark that I want to reprogram, soldered into a circuit. I have burned the default t85 micronucleus firmware.

**This is the command I used:**

```
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" -C "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -pattiny85 -cstk500v1 -PCOM4 -b19200 -Uflash:w:D:\Documents\micronucleus-master\firmware\releases\t85_default.hex:i

avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATtiny85
         Chip Erase delay              : 400000 us
         PAGEL                         : P00
         BS2                           : P00
         RESET disposition             : possible i/o
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    12     4    0 no        512    4      0  4000  4500 0xff 0xff
           flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x1e930b (probably t85)
avrdude: safemode: hfuse reads as D7
avrdude: safemode: efuse reads as FF
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "D:\Documents\micronucleus-master\firmware\releases\t85_default.hex"
avrdude: writing flash (8116 bytes):

Writing | ################################################## | 100% 0.07s

avrdude: 8116 bytes of flash written
avrdude: verifying flash memory against D:\Documents\micronucleus-master\firmware\releases\t85_default.hex:
avrdude: load data flash data from input file D:\Documents\micronucleus-master\firmware\releases\t85_default.hex:
avrdude: input file D:\Documents\micronucleus-master\firmware\releases\t85_default.hex contains 8116 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.07s

avrdude: verifying ...
avrdude: 8116 bytes of flash verified

avrdude: safemode: hfuse reads as D7
avrdude: safemode: efuse reads as FF
avrdude: safemode: Fuses OK (E:FF, H:D7, L:F1)

avrdude done.  Thank you.

```

I have not set any fuses (I hope the frequency is right.)

The board is recognized by my computer and I can program a sketch into it using Arduino IDE. Despite all this the program I burned into it does not run. It seems it is stuck into the bootloader section.

**The sketch:**

```
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(0, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(0, HIGH);
}

```

Pin `PB0` has never a voltage bigger than `1.7V`(noise or floating). All pins have similar voltages (except `PB3`,`PB4` which are pulled up or high)

**The schematic:**

The circuit works. I tested both displays previously with the atiny which I directly programmed with the `Uno`. The upper right connector is directly plugged into the `digispark` with the following pins: `VIN`,`GND`,`5V`. The middle connector is also plugged into the `digispark`.

**I have tried:**

* Powered by USB: I am afraid this will be detected by the bootloader and enter the programming state thus never running the schematic(shouldn't happen but you never know...)
* Powered by VIN with a 9V battery. Nothing. All voltages are in check (`5V pin` has `5v` on it. All other pins are floating)
* Powered by `5V pin` using an `Arduino UNO` as the source. Nothing. In all cases the voltage on PB0 stays the same. It varies between `0.6V` and `1.6V`.

**In Arduino IDE:**

* Tried Digispark 16.5Mhz
* Digispark Pro 16Mhz
* Digispark(No Usb) 16Mhz

Always a succesfull uploading.

**Notes:**

* After uploading in Arduino this text comes up:

> Starting the user app ... running: 100% complete

So it is supposed to run the program but the board actually resets because it gets renumerated by windows.
* It's not quite possible to de-solder it and program the sketch directly with `Arduino` as `ISP`
* I use Windows 10
* Fuses used when I burned the `micronucleus` `L:F1` `H:D7` `E:FF`. These are the default "safe" values. The actual fuses needed by the firmware are `L:E1` `H:DD` `E:FE`.
* Difference in extended fuse: Self-programming is curently disabled...Is this the culprit?
* I managed to desolder `PB0`,`PB1` and `PB2` from the back of the pcb. Now I can't program it directly with `Arduino as ISP`. The setup I have should work because I can easily program an t45. So it has something to do with the digispark. Checked the connection between pins and the actual MCU. The error I get is `Yikes...` and sometimes it finds an 0x00ff00 or other junk id for the board but probably it's because of misconnection.

**Question #2:**

In the current configuration(soldered) would it be possible to use again `Arduino as ISP` to program it? `PB0`,`PB1`,`PB2` are connected to `Serial Clock`,`Serial Data` and `Serial Storage Clock` respectively. I am trying right now to set the right fuses but every time I get this:

```
avrdude -C "C:\Program Files (x86)\Arduino\hardware\tools\avr\etc\avrdude.conf" -c stk500v1 -p attiny85  -U lfuse:w:0xe1:m -U hfuse:w:0xdd:m -U efuse:w:0xfe:m -B 20 -b19200 -P COM7

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.06s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

make: *** [fuse] Error 1

```

# Answer
Solved it! I don't know what the real issue was but I constructed a HV programmer and just blasted the digispark with the new and proper fuses. Now it works as it should.
> 1 votes

---
Tags: attiny85
---


# Question
Title: NEMA17 and DRV8825 200 steps give only half revolution
I have this code:

```
#include <stdint.h>

# define STEP 14

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

long steps = 0;
void loop()
{
    if (steps < 200)
    {
        digitalWrite(STEP, digitalRead(STEP) ^ 1);
        delay(10);
        steps++;
    }
}

```

Simple implementation and I have a nema17 motor with 1.8 degrees per step, which should give 200 steps per revolution, but I only have half a revolution on 200 steps, I tried connecting all MODEx pins to VCC and this should give me 6400 steps per revolution but 6400 steps also gives mi half an revolution. Could there be an issue with the wiring of the motor? Why don't I receive a full revolution? By full revolution I mean that the motor shaft should complete the whole circle but it completes only half.

# Answer
> 1 votes
See page 33 of the DRV8825 datasheet https://www.ti.com/lit/ds/symlink/drv8825.pdf.

DRV8255 moves the stepper on a rising edge in the signal.

That requires the signal to go low, then high.

That is two cycles of your program.

Add two lines to your code so that it is `output low, delay 10, output high, delay 10`

---
Tags: stepper-motor
---


title: From Arduino and breadboard to PCB

text:
# Question
Title: From Arduino and breadboard to PCB
After building a working prototype with a breadboard, I was wondering what's next. So I read about integrating the arduino into a PCB layout.

But in my case, it's worth it?

My project will use a Arduino Mega, futhermore some wired piezo switches therefore I need pcb connectors, and a small amount of resistor and transistors. I am considering to buy a Mega of the shelf and use the contactpins on a header to fix it on my PCB. Also probably fix it with some screws.

It will save me a lot of pcb design time (a maybe some mistakes) and it will save me buying all diferent components. The ATMega2560 alone is already around 10,-

I think I only need 10 or 15 pcb's, definitly no massproduction.

Your opinions...

# Answer
I agree with Majenko's proposal for a proto shield, or
if you need a "flat" design beside the Mega get yourself a striped (one /two sided and in different sizes) vero board (its like a breadboard to solder)

You could even use Fritzing to design the most efficient layout for this option in regards to space/material saving or minimum solder points
> 2 votes

---
Tags: pcb-design
---


title: Arduino SIM900 No SMS received

text:
# Question
Title: Arduino SIM900 No SMS received
I tried the tutorial in this link

https://lastminuteengineers.com/sim900-gsm-shield-arduino-tutorial/

to send an SMS message using a SIM900 GSM shield

I completed the section to send AT commands successfully but I can't get the Arduino Uno to send an SMS. Below is the output I get after doing AT command tests

```
Initializing...
AT

OK
AT+CPIN?

+CPIN: READY

OK
AT+CSQ

+CSQ: 6,0

OK
AT+CCID

8944500105191448516F

OK
AT+CREG?

+CREG: 0,5

OK
AT+COPS?

+COPS: 0,0,"T-Mobile "

OK
AT+COPS=?

+COPS: (2,"T-Mobile ","T-Mobile ","310260"),,(0,1,4),(0,1,2)

OK

```

and below are the responses from the SMS code

```
Initializing...
AT

OK
AT+CMGF=1

OK
AT+CMGS="+1mycellphonenumber"

> Last Minute Engineers | lastminuteengineers.com

```

so no response from the AT+CMGS command and NO SMS received. Plug is 5V 2A.

Any idea what might be causing the issue?

Below is the code I used for the Setup() function

```
void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CMGS=\"+ZZxxxxxxxxxx\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("Last Minute Engineers | lastminuteengineers.com"); //text content
  updateSerial();
  mySerial.write(26);
}

```

# Answer
Changed my SIM card to Ting from Hologram and it worked just fine!
> 1 votes

# Answer
Normally in Setup() you have in the end this sequence

```
Serial.println("Connecting to the network...");

while( (sendATcommand("AT+CREG?", "+CREG: 0,1", 500) ||
    sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0 );

     sprintf(aux_str, "ATD%s;", phone_number);
     sendATcommand(aux_str, "OK", 10000);

     delay(seconds * 1000);

    Serial.println("ATH"); // disconnects the existing call

```

So after the registering you send

```
 Serial.println("AT+CMGS=\"1234567890\""); //CHANGE TO DESTINATION NUMBER

```

Did you use the \\" for the embracing the number. Without your real command its hard to guess. Better use a test program Soft Serial GPRS Code, serial monitor is error prone. **EDIT** The OP posted code parts. The code after:

```
  Serial.println("Initializing...");
  delay(1000);

```

should be in the loop()- Look at the linked examples how should communication take place if the code is run once so no recurring tasks like reading chars or similar.
> 0 votes

---
Tags: gsm
---