Timer 1 COMPA ISR - default behaviour? I'm creating a LCD frequency generator.

When TIMER1 reaches a set value, it's set to toggle Pin 9 (via OC1A).

Accidentally, I left the TIMER1 "interrupt on compare match A" enabled, but never defined the TIMER1_COMPA_vect interrupt vector.

This made the Uno reset itself - but not running through the bootloader, just the program part - whenever TIMER1_COMPA_vect would've been called.

Once I defined the ISR, even without it having any content, it would run as expected.

Is there a default content for ISRs, which resets the device / starts just after the bootloader? Shouldn't the compiler detect a completely missing ISR?

The compiler cannot detect a missing ISR since it is very difficult, in
the general case, to tell whether any particular interrupt-enable bit
has been set by the program.

The avr-libc library does indeed provide a “catch-all” ISR and, as
stated by the manual,

  the default action is to reset the device by jumping to the reset
  vector.

If you don't like this behavior, you can override this catch-all with
your own, as explained in the manual (search for “Catch-all
interrupt vector”).


Use Arduino as transmitter and receiver UART I know UART and serial communication model and data frame. But I want to ask about something else, when I searched in internet just found examples of one Arduino as (receiver) and another Arduino as (transmitter).
So my question is how can I implement two Arduino and both of arduinos can communicate each other when after transferring data from one to another
(example A->B). If the interpretation of the received data has to be forwarded to the first sender again(B->A).

You sure now Serial.write() and Serial.read(). That's already what you want. A hint to make it clear to you: When using the common Serial.print() function only the RxD line is in charge an thus only "half" of the serial interface is used. If you connect TxD of arduino A to RxD of another arduino B and RxD to TxD respectively you have full-duplex communication which is what you're asking.


Looking for learning resources to teach the "principles" rather than "follow this" projects I just got the Arduino starter kit as my background is software developer (C++, python, etc) and I'm interested to get into the electronics side, and I love LED effects and home automation of all kinds.
As such I'm quite comfortable with the type of C programming required (loops etc) but need to learn the principles of electronics.

Can you suggest any resources (websites, tutorials, books - I'm willing to pay for books if they are useful) whose focus is teaching the principles as well as doing specific projects?

The kit came with the "Arduino Projects Book" but I don't really like it as it's focused on "do this, do that, put the circuit together according to this diagram" rather than explaining the principles first. For example I did the "Spaceship Interface" (light up different LEDs in different patterns based on whether a button is pushed or not) and it introduces things like "You'll also need to add a 10k ohm resistor from ground to the switch pin that connects to the Arduino [...] it connects the pin to ground when the switch is open so it reads LOW when there is no voltage coming in through the switch". I understand that in principle I think, but why is it 10kohm, why do we have to connect it using a resistor when the switch is open, etc. (I see that we have to have a complete circuit and I'm assuming it is because the 10kohm is a "default" branch of most resistance with nothing else connected?)

I'm asking about general principles rather than the specific case of why do we have a 10kohm resistor in this case, but this is a pretty good example early in the book.

Welcome to the Arduino world!

First I'd like to try to answer your question: (This explanation does not apply to his situation as explained in the comments, but, I guess, it's a fun and useful read so I'll leave it here)

  "You'll also need to add a 10k ohm resistor from ground to the switch pin that connects to the Arduino [...] it connects the pin to ground when the switch is open so it reads LOW when there is no voltage coming in through the switch". I understand that in principle I think, but why is it 10kohm, why do we have to connect it using a resistor when the switch is open, etc. (I see that we have to have a complete circuit and I'm assuming it is because the 10kohm is a "default" branch of most resistance with nothing else connected?)

I haven't seen your circuit but I think I know the deal here. The author is basically telling you to create a pull-down circuit. What this does is, what it says. It pulls down the voltage on arduino pin to GND. Now, why would you want to do that? I think because in your project, the author was reading analog values from that pin. He wants the pin pulled down because otherwise when the switch is open, the pin would be floating i.e. not connected to anything. Floating pin means that you will get random analog readings from that pin. Basically, if you don't connect that pin to any source/sink, it will act as an antenna. You will get noise. (You can actually use this to create random numbers for your arduino!)

Now, about that 10kOhm resistor: Its depends on two things. First, if you put a low value resistor, then you will draw lots of current from the supply to the ground when the switch is closed. You normally don't want that, why spend energy more than you have to? So, you pick any big resistor that you can possibly pick. But how big can you really put there? This depends on the analog read pin's current consumption. Whenever you do an ADC (analog to digital conversion) a.k.a analog read, your pin sinks/supplies tiny amounts of current and samples it to determine voltage. Atmel datasheet says that:

As you can see, the good guys in Atmel already did some tests and determined that with the current Atmega328p (Arduino-UNO chip) chip, a source of 10kOhm internal resistance is sampled the best. (When you open the switch, the 10kOhm resistor is basically a 0V source with 10kOhm internal resistance)So basically, I guess, that's why the author used 10kOhm. Could you have used 20kOhm instead? Of course...

Now about the electronics book thing. The best practice with electronics is to both read and do. So, whatever book you pick, make sure it has examples and explanations that you can try. Don't buy a highly theoretical book with lots of math and physics. Don't use a simple do-this do-that book either. I can't provide you a single good book, because that's not how I prefer to learn. But I might have some good suggestions for you if you prefer to study like this as well:

Learn the basics or R,L,C. Study filters, energy, their differential equations etc. Any book, website will do.
Use software and simulate theoretical/explanatory circuits. LTSpice is best. For bigger projects, something like MATLAB is better.

If you do that, you'll gain some insights on how things actually work.

Move on to transistors: BJT, MOSFET etc. What are they and how they behave?
Combine transistors and R,L,C to create some digital-analog circuits. How do you make a RAM cell? Can you make an arithmatic logic unit?

At this point, you should be comfortable with most elements of electronics.

Since you started with arduino, study RISC/CISC architechture. What actually is a microcontroller?
Since you know software, try using assembly code to turn on and off some leds. This is where you meet software and hardware at the lowest possibly level you can.
Try to make your own microcontroller using FPGA! (I've done this -it was a simple and not-so-useful CPU but nevertheless it provided insight. You can invent your own assembly language!!)

At this point you should be able to understand most basic arduino projects.

Read atmega datasheets.
Read Transistor, motor driver IC etc. any driver datasheet and search the terms on google. What do they mean?

After that you can do this:

Pick a project, and do it from scratch. Without, copying any circuits from the internet. Can you place atmega chip to work stand alone, away from arduino board? Can you use that and make for example a BLDC driver?
Pick a project and ask stackexchange. (Well, obviously). There are some really brilliant people here that are willing to help. Personally, I feel I'm learning better if I try to answer other peoples questions and ask questions.

I guess the downside/upside is you never stop learning. Electronics combined with software is a huge area of expertise.

So I wish you Good luck!


Arduino and GPS module Neo 6m I have an Arduino Leonardo and a GPS module "NEO 6M"

Pinout:

PPS->free
rxd->11
txd->10
gnd->gnd
vcc->5v

I'm running this code:

#include "SoftwareSerial.h"
SoftwareSerial gps(10,11);
void setup(){
  Serial.begin(9600);
  gps.begin(9600);
}

void loop(){
  while (gps.available())
    Serial.write(gps.read());
}

In serial monitor I'm getting random characters like this

Where am I going wrong?

I tried the same with an Arduino Mega but have the same result.

Solved: GPS module was broken. Now I use another GPS module, same model. Sorry for my English.


Import library in Arduino IDE I'm trying to use an HX711 load cell amplifier with my NodeMCU 0.9. I've found this library on Github and, following this guide, I tried to use it.

Unfortunately I keep getting this error:

sketch/HX711.cpp:2:19: fatal error: HX711.h: No such file or directory
 #include <HX711.h>

I suppose that there's some problem with C++ but I don't understand what is.

Here's the initial code:

#include <ESP8266WiFi.h>
#include "HX711.h"

Here's the folder structure:

Samples
  |-- nodemcu_test
        |--nodemcu_test.ino
        |--HX711.cpp
        |--HX711.h

Original question

You want to import a library not an example.

Arduino Folder
    |-- libraries
        |--HX711
            |--HX711.cpp
            |--HX711.h

ex:

C:\Program Files (x86)\arduino-1.8.5-windows\arduino-1.8.5\libraries\HX711

Put the files in a folder called HX711 to have everything nice and tidy.

I use the standalone version of arduino ide, if you have it installed I suspect the folder would be under

My Documents\Arduino\libraries\

According to the documentation.

You should put the nodemcu_test.ino in your sketchbook folder as I would generally avoid putting non-library files in the libraries folder. If you do want to keep the examples for a specific library close to the library create a subfolder:

Arduino Folder
    |-- libraries
        |--HX711
            |-- examples
                |--nodemcu_test.ino
            |--HX711.cpp
            |--HX711.h

As Juraj pointed out, this has the additional advantage of them being accessable in the examples menu.

If you want the libraries close to your sketch you are actually working on, follow the guide and put the library files in your sketchbook folder for your project. I would not advise for the following reasons:

I read that in newer IDEs 1.8.X you would need to put the files in a /src/subfolder. For me it did work without that, but the main caveat remained:

#include <HX711.h>

means to look in the library folder as mentioned above.

If you want to put the files somewhere else, you have to use

#include "HX711.h"

and specify the path (or in this example it was located where my .ino was). But now I also need to change

#include <HX711.h>

to

#include "HX711.h"

in the HX711.cpp file. What a hassle!

So my takeaway message would be: Stick with Arduino\libraries\.


How to read an RFID reader? I want to connect an RFID reader to an Arduino board. The RFID reader has several wires attached, and the manual mentions them as follows:

Red: VCC +12V
Black: GND
Green: D 0/RX/4R+
White: D 1/TX/4R−
Blue: LED/CS
Yellow: Beep

There is also another black wire attached, but the manual does not mention it.
This is an image of it:

I have the red wire connected to the 5V pin and the black wire to the GND pin on Arduino board. Then I have the white wire connected to the RX pin on the Arduino board.

I'm trying to Serial-read the RX port using this code:

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

void loop() {
    if (Serial.available() > 0) {
        int b = Serial.read();
        Serial.print(b);
        Serial.print(" ");
    }
}

When I try to read a keyfob, only this is printed – nineteen times 248:

248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248 248

To me it looks like there's something wrong with the connection somewhere.

How can I properly read this RFID reader? If above assumption is not correct, is there something I should know?

Have you tried other baud rates? Could you paste a link to the manual or upload the manual itself? From what i could find quickly, the module supports 3 modes: RS232, RS485 and Wiegand 26/34. So the manual should provide some means of selecting a particular mode (perhaps the CS pin?). I suspect you arent actually using the RS232 mode, which is why you are getting strange results. If you can't find a way to select a mode, you could try brute-forcing it and try the WG26 mode next. This code from seeedstudio seems to do the job http://www.seeedstudio.com/depot/datasheet/RFID_630_WG.pde or you could look at the Wiegand protocol on Wikipedia and write your own code, since its relatively straight forward. Also a google image search turned up this link to Aliexpress: http://www.aliexpress.com/item/Waterproof-Security-Door-Access-Control-Wiegand-26-125KHz-RFID-ID-Card-Reader-EM4100-102A/1362129655.html; this is your reader, right?


Using an Arduino Nano to program (as ISP) a standalone 328p I uploaded the ArduinoISP sketch to an Arduino Nano to use it as a programmer for other chips.

It worked successfully to program an ATtiny45, I did the usual wiring between them, and added a 10uF between RST and GND of the Nano. Everything worked.

Now I'd like to program a standalone ATmega328p with the Nano, I did the usual wiring as well (see this tutorial), as well as this 10uF cap.

But it does't work:

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

The reason might be because this 328p comes from an Arduino Uno, probably configured to be ext-clocked by a crystal. Whereas I don't have any crystal here and wanted to clock the 328p with the internal clock.

Question: how can I restore the 328p to factory default / internal clock, if I don't have a crystal?

Or what other reason can this error be?

Edit: a solution is found here: Change the fuses of an Arduino Uno (can an Arduino Uno change its own fuses?)

You can temporarily put it in an UNO. Don't connect this UNO via USB, but use jumper wires to connect the ISP pins plus the power pins to the other Arduino that you are using as an ISP programmer. (You could also use the (2x3) ISP header on the UNO if that's more convenient.)

Or, you could use a high voltage programmer.

Or get/desolder a crystal from some junk electronics. Exact frequency doesn't matter that much. I think somewhere between 1 Mhz and 16 Mhz would work.

You can then reset the fuses, so it doesn't need a crystal.


Problem reading an EEPROM chip using the I2C protocol I am trying to read an EEPROM chip that supports the I2C protocol (cannot tell the IC model number as it is not printed). For sure it supports the I2C protocol, since I wrote a code to detect it using the I2C library and the device address I got it return is 0x51. Now I am trying to write a code that reads data from this IC chip. The code is as follows:

#include <Wire.h>

int addr = 0;

void setup() {
    Wire.begin(); // initialise the connection
    Serial.begin(9600);
    while (!Serial) {}
    delay(100);
}

void loop() {
  byte deviceAddress = 0x51;
  byte data = readData(addr, deviceAddress);
  Serial.print(data, HEX);
  Serial.print(" ");
  addr++;
  if(addr%16 == 0) {
     Serial.print('\n');
  }
  // check for 1Kbits first
  if (addr%128 == 0) {
     Serial.println("round complete");
     Serial.println();
     addr = 0;
  }
  delay(100);
}

byte readData(int address, int deviceAddress) {
  // sending device address
  Wire.beginTransmission(deviceAddress);
  Wire.write(address);
  Wire.endTransmission();
  Wire.requestFrom((short int)deviceAddress, 1);
  if(Wire.available()) {
    byte data = Wire.read();
    return data;
  }
  return 0xAA; // random data
}

The problem I am facing is, I get back the address (from which I want to read the data) as the data itself (For e.g. read(0) returns 0, read(1) returns 1 and so on). I even tried to debug the I2C communication using the logic analyzer (Saleae logic in this case). A screenshot is shown below.

The screenshot shows the logic for a read operation from a single address (0x78), but the story holds for each and every address i.e. I get back the address instead of the data from the address.

The output of the above code is as follows:

  0 1 2 3 4 5 6 7 8 9 A B C D E F
  10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F
  20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F
  30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F
  40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F
  50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F
  60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F
  70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F
  round complete

Can you help me identifying what possibly I am doing wrong here?

Thanks.

You need to pass the address as two bytes, one by one.

Do not do:

Wire.write(address);

Rather, do:

Wire.write((uint8_t)(address >> 8)); // MSB
Wire.write((uint8_t)(address & 0xFF)); // LSB


Programming a servo on an ATtiny85 Board: "ATtiny25/45/85"

Processor: "ATtiny85"

Clock: "Internal 1 MHz"

Programmer: "Arduino as ISP"

I want to run a servo forwards and backwards on an ATtiny85. The servo library is not compatible with the ATtiny85 so I had to write code from scratch. At this point, the code that makes the servo go forwards (clockwise) is:

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

void loop() {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(1000);
  // 1 millisecond determines the servo going forwards
  digitalWrite(PB1, LOW);
  delay(19);
}

And the code that makes the servo go backwards (anti-clockwise) is simply by changing the amount of microseconds to:

delayMicroseconds(2000);

I want to have the servo motor go forwards one cycle for a few seconds and then go backwards for a few. I want this to keep looping. At this point my code is:

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

void loop() {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(1000);
  digitalWrite(PB1, LOW);
  delay(19);
  digitalWrite(PB1, HIGH);
  delayMicroseconds(2000);
  digitalWrite(PB1, LOW);
  delay(19);
}

This however just makes the servo go back and forward at the same spot forever. I do realise I might need a for loop for this but I am confused as how I will do this.

The servo can't move back and forward in 40 milliseconds. It'll be more like tremble between both.
Try something like this:
// keep sending 0 position for about 400ms
for(int i = 0; i<20; ++i) {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(1000);
  digitalWrite(PB1, LOW);
  delay(19);
}

// keep sending second position for about 400ms
for(int i = 0; i<20; ++i) {
  digitalWrite(PB1, HIGH);
  delayMicroseconds(2000);
  digitalWrite(PB1, LOW);
  delay(18);
}


How do i generate exact number of PWM pulses in arduino? So my code here generates a PWM wave of 38Khz on Port B pin 7 of arduino Mega 2560 . For that I have used a prescaler of 8 and then set the ICR1 register value to 51 . I have also set the WGM10 ,WGM11, WGM12 and WGM13 bits to 1 , to enable fast PWM mode with Top reference value as ICR1 contents . Similarly , COM1A1  is set , to enable clear output on compare equal else high . CS11 is set to high to enable the prescaler 8 .

My code is as follows -

#include<avr/io.h>
#include <avr/iomxx0_1.h>
#include<util/delay.h>
void pwm_init()
{
        // Configure PB.7 as output pin
        DDRB |= (1<<PB7);
        TCCR1A =  (1<<WGM11) | (1<<WGM10) | (1<<COM1A1);
        TCCR1B =(1<<WGM12) | (1<<WGM13) | (1<<CS11);
        ICR1 = 51;
}

void pwm_generate()
{
    OCR1A = (50 * 52)/100 ;
}
int main()
{
pwm_init();
pwm_generate();
}

What I require from the program is that , it should stop producing pwm pulses once a sufficient number of pulses are transmitted . For example - The program should output 7 pwm pulses of 38Khz and then it should give logic 0 as output for specified time period . And then after that specified period , it should produce 38 Khz pwm wave again of say, 5 pulses and then again logic 0 for certain duration . And so on ...
How do i achieve this ?

PS- This program is actually being written to simulate a pwm wave required by the IR transmitters in TV remote . The PWM pulses represent the ON period and the Logic 0 conditions would represent the gap in between two successive train of PWM pulses.

Picture of waveform for reference -

One way to get a fixed number of pulses is to set up an interrupt handler that is invoked once per toggle (or, once per cycle, whichever is appropriate).  It can decrement a counter, and shut off an output pin when the counter gets to zero.  Or could set the output pin low and the CS bits to 0 to stop the counter.  For example, if timer 1 is in use:

volatile byte TogCounter;
...
// In setup():
TIMSK1 = 1<<TOIE1;  // Enable timer 1 overflow interrupt at TOP
...
// Define a timer 1 ISR
ISR(TIMER1_OVF_vect) {      // ISR for timer 1 overflows
  if (TogCounter) {         // Don't decrease if not counting
    --TogCounter;
    if (!TogCounter) {
      pinMode (TogPin, INPUT); // Disable output when count runs out
      // If desired, set a volatile wavetrain-is-done flag here
    }
  }
}

To output a specified number of cycles n, set the mode of TogPin to OUTPUT and set TogCounter to 2·n (or to n if counting cycles instead of toggles).  Note, waveforms will be of more-consistent length if you also clear the counter register just before starting any pulse train.

To generate a sequence like m1 cycles on, n1 off, m2 cycles on, n2 off, etc, you could set up an array containing m1, n1, m2, n2, etc; then each time TogCounter runs down, toggle TogPin from INPUT to OUTPUT or vice versa, and load the next array entry into TogCounter.


analogRead-ing Potentiometer Values in void setup() I've run into a problem while coding a speedometer meant for bicycles. The speedometer would require the diameter of the wheel in inches for maximum accuracy, so I'd like to have an adjustable (by potentiometer) numerical prompt appear on two 7 segment LEDs. So, for example, the device would be turned on, it would display "16," the user would turn the potentiometer knob until the 7 segment LED displays "24," then the user would push a button [indicating the beginning of the loop()], and the speedometer would begin measuring and displaying his or her speed.

This would be an easier task to accomplish in the loop section of the code, but, because I only want this series of potentiometer analogReads to occur once, it gets a bit trickier.

Some clarification: Every other component of the speedometer works (such as the 7 segment LEDs via shift register and the actual measurements), so I'm only looking for help with the code for the potentiometer.

Thanks!

You presumably know that:  The easiest and usual way to read a potentiometer is to connect the "track" between V_pot (often = Vcc) and ground and to connect the pot "wiper" to an analog input pin. You then use analogRead(Ax) to read the pot value in the range 0-255.

The use of analogRead() is valid in setup.

However a more "real" method would be to have a "flag" variable that indicates that the speedo initialisation code has or hasn't been run.
Set this flag to false in setup, detect and action it in loop and then set the flag to true so that the code is not repeatedly actioned.

eg

void setup()
{

...
boolean initialised = false ;
...
}

void loop()
{
if (initialised == false) {
// initialise speedo
//  ....
   initialised = true;
}

...

} // end of loop()

}


How to pass non-static class member to callback? I am using the arduinoWebSockets library in my own Arduino library. I'm having trouble with trying to assign a class member as the websocket library onEvent callback function.

MyClass.cpp:

#include <WebSocketsClient.h>
#include "Arduino.h"
#include "MyClass.h"

void MyClass::connect(String host, int port) {
  webSocket.begin(host, port, "/");
  webSocket.setReconnectInterval(5000);

  // tried all these variations
  // webSocket.onEvent(incomingEventHandler);
  // webSocket.onEvent(MyClass::incomingEventHandler);
  webSocket.onEvent(this->incomingEventHandler);
}

void MyClass::loop() {
  webSocket.loop();
}

void MyClass::incomingEventHandler(WStype_t type, uint8_t *payload, size_t length) {
  // do stuff with incoming data
  // need to access other member functions and class variables
}

MyClass.h:

#ifndef MyClass_h
#define MyClass_h

#include <WebSocketsClient.h>
#include "Arduino.h"

class MyClass {
  public:
    void connect(String host, int port);
    void loop();
    void incomingEventHandler(WStype_t type, uint8_t *payload, size_t length);
  private:
    WebSocketsClient webSocket;
};

#endif

The error returned is:

  sketch/MyClass.cpp: In member function 'void MyClass::connect(String,
  int)': MyClass.cpp:14:47: error: no matching function for call to
  'WebSocketsClient::onEvent()'
  webSocket.onEvent(this->incomingEventHandler);

From what I understand it seems like I need to create a pointer to the class member, I have tried a few different ways, this one seemed the most promising, but still failed:

typedef void (MyClass::*MyClassMemFn)(WStype_t type, uint8_t *payload, size_t length);

void MyClass::connect(String host, int port) {
  webSocket.begin(host, port, "/");
  webSocket.setReconnectInterval(5000);

  MyClassMemFn onEventCallback = &MyClass::incomingEventHandler;
  webSocket.onEvent(MyClassMemFn onEventCallback);
}

The above returns this error:

  sketch/MyClass.cpp: In member function 'void MyClass::connect(String,
  int)': MyClass.cpp:15:34: error: expected primary-expression before
  'onEventCallback'    webSocket.onEvent(MyClassMemFn onEventCallback);

I have also tried to use std::bind:

void MyClass::connect(String host, int port) {
  webSocket.begin(host, port, "/");
  webSocket.setReconnectInterval(5000);

  webSocket.onEvent(std::bind(&MyClass::incomingEventHandler, this));
}

Error:

  sketch/MyClass.cpp: In member function 'void MyClass::connect(String,
  int)': MyClass.cpp:12:47: error: no matching function for call to
  'WebSocketsClient::onEvent()'
  webSocket.onEvent(this->incomingEventHandler);

If I move the incomingEventHandler function outside the class definition, it works as expected, however then I can't call other class members or access class properties in the same scope.

In arduino c++ how can I pass non-static class member properties as a callback? Is there a better way to approach this?

Yes, a callback can be a member function. The error in your std::bind call is that while you do bind the first hidden this paramater to an object instance, in this case this object, you must also use placeholders for all your other function parameters.

Since you declared

void incomingEventHandler(WStype_t type, uint8_t *payload, size_t length)

You must bind as

webSocket.onEvent(std::bind(&MyClass::incomingEventHandler, this,  std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

Note that this webSocket.onEvent call only works if you are on a non-AVR platform, because the library defines

void WebSocketsClient::onEvent(WebSocketClientEvent cbEvent) {
    _cbEvent = cbEvent;
}

with

#ifdef __AVR__
        typedef void (*WebSocketClientEvent)(WStype_t type, uint8_t * payload, size_t length);
#else
        typedef std::function<void (WStype_t type, uint8_t * payload, size_t length)> WebSocketClientEvent;
#endif

i.e., it is a raw function pointer in __AVR__ but a std::function on non-AVR platforms -- std::bind will give you a std::function. Since you're on an ESP8266, this should work fine.

Refer to https://en.cppreference.com/w/cpp/utility/functional/bind (and maybe my old question)


Arduino/C++ byte manipulation Consider this scenario, I have a single byte of data; I have to use the 8 bits it is composed of to generate 4 extra bits from it.

Now, my problem is that I have to store this data somewhere while I operate on it and then return the final answer in byte form.

eg. 1 byte of 8 bits becomes 12 bits. Thus 2 bytes results in 24 bits which I want to transfer in packets of 3 bytes.

01001101 becomes this with added bits: _ _ 0 _ 1 0 0 _ 1 1 0 1

What would be the most efficient way to accomplish this?

Sometimes the brute-force way is also the most efficient. Just copy the bits one at a time from the corresponding source variable to the destination variable:

int merge_bits (int old_bits, int new_bits)
{
   int retval = 0;
   if (old_bits & 0x01) retval |= 0x001;
   if (old_bits & 0x02) retval |= 0x002;
   if (old_bits & 0x04) retval |= 0x004;
   if (old_bits & 0x08) retval |= 0x008;
   if (new_bits & 0x01) retval |= 0x010;
   if (old_bits & 0x10) retval |= 0x020;
   if (old_bits & 0x20) retval |= 0x040;
   if (old_bits & 0x40) retval |= 0x080;
   if (new_bits & 0x02) retval |= 0x100;
   if (old_bits & 0x80) retval |= 0x200;
   if (new_bits & 0x04) retval |= 0x400;
   if (new_bits & 0x08) retval |= 0x800;
   return retval;
}

On most microprocessors, this will compile into just a few instructions per statement.

This is also arguably more maintainable than a complex series of shift and mask operations.


Arduino LED flashes with one button press I want the LED to flash when I press the switch once, but it keeps flashing. I tried the idea of just lighting the LED and keeping it lit with just one button press, so I wrote:

int led=13,button=12;
void setup() {
pinMode(led,OUTPUT);
pinMode(button,INPUT);
}
void loop() {
if (digitalRead(button)==HIGH)
  digitalWrite(led,HIGH);
}

and this worked; it stayed on after I pressed the button once, so for the flashing LED I wrote:

int led=13,button=12;
void setup() {
pinMode(led,OUTPUT);
pinMode(button,INPUT);
}
void loop() {
if (digitalRead(button)==HIGH)
{
  digitalWrite(led,HIGH);
delay(1000);
 digitalWrite(led,LOW);
 delay(1000);

} }

but this didn't work. It stops flashing after I remove my hand from the switch. Why is this happening?

Because the digital writes only apply on if (digitalRead(button)==HIGH). If you don't press the button, then the code goes:

void loop() {
}

Essentially doing nothing. Your code needs a bit more to keep track of the button press. Pseudo Code:

if button == pressed {
    int tracker=1;
}
if tracker == 1 {
    led on;
    wait;
    led off;
    wait;
}
loop


LCD-Display showing wrong numbers Hy guys,

I am having an issue with my new LCD16x2 display. I connected a potentiometer and read the values. The values are properly read and send to Serial. I also display the values on the display. I am having no issues when increasing the values, but when I go down again at a certain point the displays doesn't display the correct value anymore, but on the Serial I can still see the right readings.

I suppose this has something to do with the display still storing previous values for this digit in the buffer and when I go down the values are not properly reset. But I don't wan't to clear the whole buffer, since then the whole thing just blinks every iteration.

Here's my code

// ESC_Calibration.ino
#include <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>
#include <Servo.h>

#define WHITE 0x7

Servo firstESC;
Servo secondESC;
int throttlePin = 2;
int firstESCPin = 2;
int secondESCPin = 3;

Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

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

    lcd.begin(16, 2);
    lcd.setBacklight(WHITE);
    lcd.setCursor(0, 0);
    lcd.print("throttle:");

    firstESC.attach(firstESCPin);
    secondESC.attach(secondESCPin);
}

void loop() {
    int throttle = analogRead(throttlePin);
    throttle = map(throttle, 0, 1023, 0, 179);

    lcd.setCursor(0, 1);
        Serial.println(throttle);
        lcd.setCursor(0, 1);
    lcd.print(throttle);

    firstESC.write(throttle);
    secondESC.write(throttle);

    delay(500);
}

Does anyone have a suggestion how to improve this and fix it, so it'll display the right readings, but doesn't blink?

Thanks for your help in advance! :-)

As you have surmised, the problem is that the LCD retains what was there before and you need to clear it away.

That means, as the numbers increase you get, say,

4
10
48
89
194
309

etc.

When they go down though, because the LCD remembers what was there, only the characters you print will be replaced:

309 (309)
194 (194)
894 (89 - the 4 remains from before)
484 (48 - the 4 remains from before)
104 (10 - the 4 remains from before)
404 (4 - the 04 remains from before)

Also, as you have noticed, clearing the whole screen is not very nice since it makes it flash.

To combat that it is important that you only overwrite the characters that you need to overwrite and leave those that want to stay.  There's two common ways of doing this:

Append enough spaces after the number to force an overwrite:

lcd.print(throttle);
lcd.print("   "); // 3 spaces should be enough for 3 extra digits

Format the data with snprintf():

char temp[5]; // enough room for 4 numbers and one NULL character
snprintf(temp, 5, "%4d", throttle); // %4d = 4 digits, right aligned
lcd.print(temp);

The latter method, though it is more complex and uses more resources, can be preferred because it creates a much nicer output with the numbers properly right-aligned.  Also arbitrarily adding spaces after the number could overwrite things you want to keep.

You could also achieve a similar result doing it manually:

if (throttle < 10) lcd.print(" "); // 0-9 add one space
if (throttle < 100) lcd.print(" "); // 0-99 add one space
if (throttle < 1000) lcd.print(" "); // 0-999 add one space
lcd.print(throttle);

Just like with cats, there's many ways to skin this problem...


Using functions in header files I want to include a function in my sketch I moved to a .h file.
I did it as follows:
My code:
#include "header.h"

void setup() {
  fct();
}

void loop() {

}

My header:
#include "Arduino.h"
#ifndef MYHELPERS_H
#define MYHELPERS_H

void fct() {
// stuff
}

#endif

The same process seems to work for variables but the IDE says this function in not declared in this scope...
I don't understand what I'm doing wrong...
Thanks guys!

I found a solution somewhere else on internet...
This portion:
#ifndef MYHELPERS_H
#define MYHELPERS_H

Was not written correctly... "MYHELPERS_H" should've been replaced by the name of my file. Now it works just fine.


What's the simplest way to get arduino functionality? I want to control a servo with the least amount of components. But generally, what is the simplest way to do this without actually using a fullblown arduino board?

If you what you're looking for is the cheapest option with the fewer components possible, then you can use a regular ATMega328p chip, with a few passive components attached to it.

You just need to program it with an Arduino Bootloader once, in order to be able to program it easily, but you can use any existing Arduino to do that. After doing this once, you can program it with any FTDI-type USB to Serial converter.

Here's an Instructable that explains the whole process.


Compatibility between Arduino and Arduino clones In a project I am using a Seeeduino v3.0 as an Arduino clone. On the seeeduino website it says that

  It is based on the Duemilanove schematic, 100% compatible to its existing program, shield and IDEs.

In fact I never had any problems with shields or the IDE.

My question is now: Is the seeeduino and other clones really 100% compatible? The seeeduino board was considerable cheaper then an arduino.

Over the years I have used original Arduino boards as well as a multitude of clones of varying provenance, from the excellent InduinoX that is listed on the Arduino site as an official compatible board, to the very well-made Chinese Meduino Nano Enhancement (3.3 / 5 Volt switchable), to dirt-cheap clones from eBay that are sometimes better constructed than the official boards.

There is nothing unique or sophisticated about the Arduino board: It's basically just the microcontroller (atMEGA328, atMEGA1280, SAM3X8E or others) and its minimal support hardware. Not much that can go wrong with that little, really.

The two common elements that ensure compatibility across these boards are:

The Arduino bootloader
Support for the board within the official Arduino software distribution

The bootloader can be replaced with a better or more up-to-date version if one is available for the microcontroller on your board.

The support files can either be found online, or minor edits to the nearest similar board's files can provide the requisite support for the Arduino environment.

In short: Yes, clones typically work just as well as the original Arduino, and clones with enhanced features often work far better while retaining compatibility (e.g. InduinoX)


IR receiver receives only 0 I am trying to decode IR codes of my Samsung tv remote
But the receiver always receiving "0"
Schematics:

Code:
#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn();
}

void loop()
{
  if (irrecv.decode(&results))
    {
    int value = results.value;
    Serial.println(" ");
    Serial.print("Code: ");
    Serial.println(results.value);
    Serial.println(" ");
    irrecv.resume();
    Serial.println("*****************");
    }
}

Please help me to decode my IR codes

Next update with 3.1 of the library, you need to call irrecv.decodedIRData.decodedRawData to get the data. This code worked for me:
#include <IRremote.h>

int IRpin = 11;
IRrecv irrecv(IRpin);

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
  if (irrecv.decode())
    {
      Serial.println(irrecv.decodedIRData.decodedRawData); // Print the Serial
      irrecv.resume();   // Receive the next value
    }
}


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

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

My code at line 360 is

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

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

Exception 28 is, according to the exception list document:

  Access to invalid address

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

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

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


Resistor pull-ups for ESP8266 I'm using 4.7kOhm resistor as pullups for GPIOs 2,0,2,16, CH_PD and RESET, and also 4.7kOhm pulldown for GPIO 15. The ESP8266 boots and works fine. Would it be okay for a long shot? Should I use 10kOhm instead of 4.7kOhm?

In general it makes little or no difference what the value of resistor you use is.

The only things it can affect are:

The current consumption while a button is pressed - a lower value resistor will cause more current to flow while for the time the button is pressed (it makes no difference at other times).
The LOW voltage (VIL) read at the IO pin if the button has a high resistance (for example if it's on the end of a 500m length of cable).
Noise immunity - a lower value resistor will pull the pin up "harder" making it more difficult for noise induced in a long wire (see the previous point, too) from causing a false button press (although this is less of a concern with modern digital inputs that tend to all have Schmitt triggers).

10k is often chosen not because it's "better" than any other value, but purely because it's more common that many other values, and it's in the right kind of ball-park for most setups.  It's low enough to give good noise immunity while being high enough to not cause undue current flow while the button is pressed. But more importantly, it's a resistor that everyone has in their kit, and is most likely the most common resistor used in a number of other places in the circuit as well. It's a good all-rounder as far as resistors go.

To take a closer look at the current flow aspect - if you are running (as with an ESP8266) at 3.3V and you have a 10k resistor the current flow, when the button is pressed and the resistor connected directly to ground, though the resistor would be (I=V/R) 3.3/10,000 = 330uA. If you used a 4.7k resistor (as you are doing at the moment) the current rises to 3.3/4,700 = 702uA. Yes, that's just over double the current, but twice peantus is still peanuts. So 4.7k, under most general circumstances, is perfectly fine.

However if power consumption is a real concern and you want to keep all consumption to an absolute minimum switching to 100k (as you often see in low-power circuits) would be beneficial, since 3.3/100,000 is 33uA.

If your input is connected to a momentary button which will be pressed for fractions of a second at a time it's not that much of an issue. But if the input is connected to a switch that could be activated for days or weeks at a time it obviously becomes of greater interest.

So in short: when running on batteries higher value pullup resistors are better, but when running off a power supply it really makes no difference.


arduino mega overheat when connected to TFT 7" and TFT shield I have bought a 7" LCD (TFT01-7) and a shield to make it work with arduino mega (http://www.elecfreaks.com/store/lcd-tft01-mega-shield-v10-p-214.html), but when I upload my code to the arduino and plug my LCD to the shield the arduino get overheated and the LCD lose power and I don't know why even when I power my arduino with external 9V 2A adapter, I even tried uploading an example from the library but it does the same, I used to work with the same code and the same shield but with 5" LCD ITDB50 and I didn't have this problem before, how can I fix this?

7" LCDs need a lot of current. They need it for the back light.

That current comes from the 5V pin.  That 5V pin is supplied by a linear regulator that has limited current capacity.  As you draw more current it gets hotter and hotter and eventually shuts down.

You will need to power your LCD screen with another external 5V source. The best solution may be a powerful (2A) phone charger (USB) which you then plug direct into the USB port of the board thus bypassing the weak regulator.


Using nrf24l01 with mpu 6050 unstable I am trying to connect the wireless module nrf24l01 with the gyro mpu-6050.  Each works perfectly on its own.  However, when connecting both to a single atmega328 (in order to send over wireless the gyro data), the code runs for between 30 seconds and 5 minutes.

I have seen many people have issues, none of the suggestions have worked, but it seems like it is more about the combination than the mpu itself.  I have not had any errors, in that all the attempts have uploaded fine.

Some things I have tried (If you have experience with this device, im sure you will know what i am referring to ):
Changing clock rates from 24 to 12, and 400 to 200
Changing the header file for mpu from 100 hz to 20 hz and back
Adding pullup and pulldown resistors on sla/sda
Using external variable power supply to make sure exact voltage
Powering devices off arduino 3.3 and external 3.3
Running code without using serial reader on computer and just transmitting data

Edit:

After more debugging, I reduced the issue (I think).  As each module works fine independently, i thought there could be a code issue.  It seems though, that the issue is the combination of buffers.  I don't think this is exactly right, but to us it seems like the gyro needs to run quickly to stop the risk of causing the arduino to hang(even though we clear the buffer).

The second part is the wireless.  It seems like the code is looking by default for an acknowledgment the package is received.  This slows down the broadcasting.  So, if we disable the ack requirement, the gyro becomes stable.  However, the receiver stops receiving any packets at all.  If someone knows why, please explain.

So what we thought would work is by sending only some packets as the write with ack on a particular pipe.  This way, the gyro will be able to run stably, and the data can sometimes be sent and we can see if this is really the problem.  Again, this does not get recognized by the receiver at all.

Questions:
Does it make sense that the buffers are working against eachother, and this is not solvable through hardware.
Is there a clear reason why the receiver can not find packets that are being sent, just without the ack requirement?

I could not figure out what was wrong, but I changed to this library for NRF24: http://tmrh20.github.io/RF24/

and I started using the GY-85 with the FreeIMU Library : http://www.varesano.net/projects/hardware/FreeIMU

Following this advice:
http://forum.arduino.cc/index.php?topic=164222.msg1539961#msg1539961

It works now, so if it was SRAM as @Avamander suggested, it was not on my side.


Water pressure an salinity sensor connected to arduino I am trying to design a project that Arduino would have connected water and salinity sensor, would be packed in a special box be droped into ocean up to 500 meters. What sensors should I use and how should they be conencted. I assume that I would need professional equipment, not chineese stuff from ebay.
Hardware needs to be able to work under 50*C and up to 50bar

Update:

Budget is about up to 400 pounds for sensors.
Resolution of pressure 0 to 100 bar
Resolution of salinity doesnt matter so much. Few percents of mistake, just to measure it somehow

I suggest that you look for a sensor from Honeywell. The problem is that the pressure is very high for a board mounted sensor and the atmospheric pressure is varying. The board mounted sensors measure a maximum of 10 bar.  It is not clear what accuracy you require. Is there a connection to the surface? If so you should measure differential pressure between the seabed and the surface.  Can you be content with a maximum depth of 100 m?

I don't think salinity varies much offshore so it might not be worth measuring.


interrupting an interrupt What should be expected if the code in the timer interrupt ISR does not finish before the interrupt is called again?  For example Timer0 ISR(TIMER0_COMPA_vect){} on the Uno.  This is for debugging purposes in a complex program.  Thanks.

the timer will set the Timer Interrupt Flag (TIFR0 register)
The ISR will be called, and the flag will be cleared
you do some long calculations or something
the timer will match OCR0A, and set the interrupt flag again.
you calculations are done, and the ISR function will end.
the uC will jump back to the main loop code, and execute 2 1 instructions.
The uC will see the flag, and call the ISR again. As per step 2.

PS please note that by default the ISR macro will turn off global interrupt (cli) at the beginning of the function, and set it back at the end. You can re-enable interrupts inside the ISR, but you have to be very careful here, as interrupts can be nested, and cause stack-overflows.

You can re-enable interrupts inside the ISR, but that only means other interrupt may interrupt this ISR, but never the same vector. (i.e. only one ISR per vector can run at the same time). So in your case the timer ISR can't be interrupted by the same timer interrupt.


Crash when disabling bluedroid i have an ESP32 and i want to use deepsleep when it's not used. Before sending it to sleep i clean up everything, so disconnect, deinitialize and disable everything i build before. But i get a crash when i try to disable bluedroid. Does anyone have an idea why this happens?
void bt_deinit() {

    Serial.println("Deinit AVRC");
    if (esp_avrc_ct_deinit() != ESP_OK)
        Serial.write("Failed to deinit avrc");

    Serial.println("Deinit A2DP");
    if (esp_a2d_source_deinit() != ESP_OK)
        Serial.println("Failed to deinit a2dp");

    Serial.println("disable bluedroid");
    if (esp_bluedroid_disable() != ESP_OK)
        Serial.println("Failed to disable bluedroid");

    Serial.println("Deinit bluedroid");
    if (esp_bluedroid_deinit() != ESP_OK)
        Serial.println("Failed to deinit bluedroid");

    Serial.println("Stop BT");
    if (btStop() == false)
        Serial.println("Failed to stop bt");
}

output:
Port closed
Uploading to I/O board
Opening port
Port open
Hello there!
Bluetooth init success
good night
Deinit AVRC
Deinit A2DP
disable bluedroid
/home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/queue.c:719 (xQueueGenericSend)- assert failed!
abort() was called at PC 0x4008de6f on core 0

Backtrace: 0x40091918:0x3ffce3b0 0x40091b49:0x3ffce3d0 0x4008de6f:0x3ffce3f0 0x4013bfb6:0x3ffce430 0x4013c5f6:0x3ffce460 0x400fdbe2:0x3ffce480 0x400fdc35:0x3ffce4a0 0x400fe12e:0x3ffce4c0 0x400f6bd9:0x3ffce4e0 0x4008e559:0x3ffce510

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8
Hello there!
Bluetooth init success

it works fine if i just do not deinitialize everything and send him directly to sleep. But this is not the elegant way.

decoded backtrace in your question is missing, one of the choices to see stack trace is https://github.com/littleyoda/EspStackTraceDecoder
i dont know exactly if this is your case or not, but calling esp_ble_gap_stop_scanning() before esp_bluedroid_deinit() possibly avoids your crash.


ESP32-Cam No Response and Unable to Program - Timed out waiting for packet header I recently purchased an ESP32-CAM but have had no luck in programming the board or getting any response whatsoever. I first tried to program it using the an FTDI programmer and the Arduino IDE (following the steps from this tutorial: https://randomnerdtutorials.com/esp32-cam-video-streaming-face-recognition-arduino-ide/).

I used this exact wiring diagram:  but got the Timed out waiting for packet header error message. This was with the jumper on the FTDI on the 3.3V section.

Other things I've tried:
-Moving jumper to 5V, powering ESP from 5V pin
-Powering ESP from external 5V source (Arduino pin)
-Powering ESP from external 3.3V source
-Switching computers (Linux and Windows)
-Programming board directly from Arduino (bypassing FTDI)
-Various combinations of pressing/holding reset button during flash process

The other thing is that there is no LEDs that turn on when the board is powered. I couldn't find a concrete reference online that said an LED turns on when the device is on, but I assume the one LED would at least flash or something. Also monitoring the serial output with putty during boot did not yield any output. I'm all out of ideas and I am just starting to suspect that the board is completely dead. Any ideas would be appreciated, thank you.

You're right. There is no LED when you power up your ESP32 cam. So this is normal.

Try to power it with the 5V, so you can power it from your USB instead of the 3.3V regulator of your FTDI. The ESP just need 50mA when in programming mode, so it should not be a problem for your FTDI.

Do you see anything on your serial output? Once you connect it in this way, you should set the baudrate to 115200 on your serial terminal and see some characters.

Then, try to program it.
Once you see the output "...___...", press the reset button! Since you are just connecting RDX and TDX, you have to manually press "RESET" on your ESP32 module.

At this point the ESP will reset and enter in the programming mode.


Problem in RS485 Communication between Arduino and PC I'm trying to sending and receiving data via RS485 communication. Interfacing Arduino and PC(laptop)
using SN75176 RS485. I wrote a program to send a string "Hello" from arduino via Tx pin. My intention is to receive
the "Hello" string in my PC's hyperterminal. After uploading the program im receiving junk data. The baud rate i've mentioned in
my program and i gave in hyperterminal are same. I've checked the wire connection, it is ok. Then, what is the problem?

Code:

#include <SoftwareSerial.h>
int Txpin = 1;
int ditpin = 5;  //for 1st rs485
int ditpin1 = 2; //for 2nd rs485
void setup()
  {
          // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(Txpin,OUTPUT);
    digitalWrite(ditpin, HIGH); //For transmit data from arduino
    digitalWrite(ditpin1, LOW); //For receive data to hyperterminal
  }

void loop()
  {
    Serial.println("Hello\r\n");
    delay(1000);
  }

Wire connection:

You cannot connect from Arduino serial input/output with RS485 circuit and then to the PC RS232 port. You need a TTL to RS232 adapter. For instance an adapter based on MAX3222.

Cheers!


Change css form color from esp32 if statement I am fairly new to arduino and ESP though am very familiar with css and javascript.

I have an esp webserver that includes a button

client.print("<button style='background-color: #F30C0C; color:#000;'></button>");

but need it to change the css backbround-color when pin is reading HIGH

 if (c == '\n') {
          currentLineIsBlank = true;
          buffer = "";
        }
        else if (c == '\r') {
          if (buffer.indexOf("GET /?relay1") >= 0)
            relayPIN1read = digitalRead(relayPIN1);

          if (relayPIN1read == HIGH) {
            digitalWrite(relayPIN1, LOW);
          }
          if (relayPIN1read == LOW) {
            digitalWrite(relayPIN1, HIGH);
          }
        }
      }

Does any one know of any way to do this?

First print everything up to the colour. Then print the colour, which you change depending on the state of the pin. Then print the rest.

client.print("<button style='background-color: ");

if (digitalRead(PIN) == HIGH) {
    client.print("#0CF30C");
} else {
    client.print("#F30C0C");
}

client.print("; color:#000;'></button>");


How do nested for loops work? In the following code from an Arduino sketch will it run the first "for" statement before enacting the second "for" statement. Also how does it know go run the first stamens again? Will it continue to run till both statements are true?

for(int r = 0; r < 8; r++){
    for(int c = 0; c < 8; c++){
        lc.setLed(0, r, c, HIGH);
    }
}

A for statement repeats everything between { and }, (or just the next line if there is no { and } a certain number of times.  It's not as simple as you might at first think, but it makes more sense if you write it out as a while loop explicitly.

For instance, for (a; b; c) { ... } could be re-written as:

a;
while (b) {
    c;
}

So if you had:

for (int i = 0; i < 100; i++) {
    Serial.println(i);
}

it could be re-written as:

int i = 0;
while (i < 100) {
    Serial.println(i);
    i++;
}

The two mean exactly the same thing.  A for has the three elements - initializer, comparison and iterator.  The initializer is run before the loop starts, the comparison is used to work out when the loop should finish, and the iterator is used to move through each iteration of the loop.

To re-write your specific example:

for(int r = 0; r < 8; r++){
    for(int c = 0; c < 8; c++){
        lc.setLed(0, r, c, HIGH);
    }
}

You would end up with:

int r = 0;
while (r < 8) {
    int c = 0;
    while (c < 8) {
        lc.setLed(0, r, c, HIGH);
        c++;
    }
    r++;
}

Now, if we were to do away with the loops altogether and write it all out longhand, what would it look like?  Well, let's start with the inner c loop.  That loops from 0 to 7 (while less than 8), so replacing that loop with 8 discrete calls to the function replacing c each time would end up with:

int r = 0;
while (r < 8) {
    lc.setLed(0, r, 0, HIGH);
    lc.setLed(0, r, 1, HIGH);
    lc.setLed(0, r, 2, HIGH);
    lc.setLed(0, r, 3, HIGH);
    lc.setLed(0, r, 4, HIGH);
    lc.setLed(0, r, 5, HIGH);
    lc.setLed(0, r, 6, HIGH);
    lc.setLed(0, r, 7, HIGH);
    r++;
}

We could take it a step further and unroll the outer r loop.  A subset of what you would end up with would be like this (note, I have skipped a lot of the middle ones):

lc.setLed(0, 0, 0, HIGH);
lc.setLed(0, 0, 1, HIGH);
lc.setLed(0, 0, 2, HIGH);
lc.setLed(0, 0, 3, HIGH);
lc.setLed(0, 0, 4, HIGH);
lc.setLed(0, 0, 5, HIGH);
lc.setLed(0, 0, 6, HIGH);
lc.setLed(0, 0, 7, HIGH);
lc.setLed(0, 1, 0, HIGH);
lc.setLed(0, 1, 1, HIGH);
... skipped a lot ...
lc.setLed(0, 6, 6, HIGH);
lc.setLed(0, 6, 7, HIGH);
lc.setLed(0, 7, 0, HIGH);
lc.setLed(0, 7, 1, HIGH);
lc.setLed(0, 7, 2, HIGH);
lc.setLed(0, 7, 3, HIGH);
lc.setLed(0, 7, 4, HIGH);
lc.setLed(0, 7, 5, HIGH);
lc.setLed(0, 7, 6, HIGH);
lc.setLed(0, 7, 7, HIGH);

There would, of course, be 8 × 8 = 64 entries in there.

for loops can be used in lots of other fun ways too.  It's not just a simple "run this X number of times".  For instance, you can loop through a C string until you reach the NULL character at the end of the string:

for (char *p = str; *p != 0; p++) {
    ... do something with *p
}

You can iterate through the entries in a linked list:

for (struct mylist *scan = myListHead; scan; scan = scan->next) {
    ... do something to scan->whatever ...
}

You can even embed functions in there:

for (char c = 0; c != '\n'; c = Serial.read()) {
    ... Do something with character `c` until `c` is a line feed ...
}

As you can see for is an incredibly powerful and flexible tool that is often overlooked in favour of the more explicit while.


Why do we need a transistor with a dc motor while we don't need one with a servo motor? I was wondering why do we need to attach a transistor as we don't need one while we connect the Arduino with the servo motors. I am using mini servos.

A servo typically has 3 wires: Power, Ground, and Signal

Inside the servo are a bit of electronics that read the input signal duty cycle, the absolute position of the horn, and power the motor in forward or reverse accordingly. There are transistors inside the servo housing to handle the high current of the motor.

A standalone motor doesn't have any other control electronics that separate power from control inputs.

EDIT:

Just to clarify: the signal wire for the Servo doesn't carry any significant power. The IO pins on the Arduino should not be asked to provide more than 40mA of current, and the PWM signal to the servo falls under that current limit.

But to operate a motor, or other device which draws significant operating power, it (the motor) asks for much more than 40mA of current, which can burn out the IO pin and damage it forever. This is why a transistor or other "switch" is necessary: the device which switches the high-current on and off can itself be operated by a very low current.


Arduino Uno R2 and Ethernet Shield R3 compatibility I bought an Ethernet Shield R3 for my Arduino Uno R2, but since R3 has extra pins it does not fit. Can I use the shield? Should I cut off the extra pins. What do I need to do to make it work?

The only issue that may create an incompatibility seems to be the IOREF pin next the 5V output pin which is extra on Revision 3 but not in Revision 2.

However, I just had a look at the board schematics and the shield does not use IOREF.

Pin 2 is extending IOREF

So, the shield should work correctly with the Uno Revision 2. As far as the extra pins are concerned, I would recommend not damaging them in any way. If you absolutely need to, then just try to bend them outwards very carefully.


HC-06 Bluetooth module and slow communication I'm communicating from an Android command line Bluetooth app interface to my Arduino. The Arduino is using a HC-06 Bluetooth module. The Arduino is supposed to receive this data and act accordingly.

However the Arduino seems to be missing bytes or just be plain slow most of the time. When testing from the computers serial connection it all works fine.

What's my issue?

There are a few things that may be causing your issues:

The HC-06 may be a cheap knock off and may not perform to the level that you expect.
There could be an intermittent wiring fault or loose connection.
The signal strength may be causing your issue - it just can't 'hear' your data.
The antenna on the HC-06 module might be compromised in some way resulting in the loss of signal.
The data rate (baud rate) may be too high.
Your code may have blocking functions or delays that is causing you to miss the data.
The Android app may have bugs in it.
The Arduino program may have bugs in it.


Function only taking the first 4 elements of a character array I'm writing a function for my arduino program that takes a character array of any size and will mark all the characters that aren't in the alphabet by changing their value to '1'.

I have a switch variable (foundSym) that will turn to 0 if the character IS part of the alphabet. At the end of my first for loop if the switch never changed, that means the character was NOT a letter and will be marked. Note I also don't want to mark space characters (' ').

The issue I have is every array I pass into the function will only have a length of 4, no matter the size.

I've checked the length of each array before it enters the function and when it is in the function, everytime the size gets shortened to 4 elements!

Here is my function...what am I doing wrong??

void markSymbols(char str[]){
  for(int i = 0; i<sizeof(str); i++){
    int foundSym = 1;
    for (int j = 0; j<26; j++){
      if (str[i] == alphabet[j]) {
        foundSym = 0;
        break;
        }
    }
    if (str[i] == ' ') foundSym = 0;
    if (foundSym == 1) str[i] = '1';
  }

}

You are passing a pointer (char str[]) and the sizeof operator is giving you the size of that pointer (4 bytes it appears in your case - on some Arduinos it would be 2 bytes).

The length of a character array is found by using strlen - assuming the string is terminated by a null (0x00).


Arduino webserver: faster alternative to "indexof" for parsing GET requests? I have a webserver successfully running on an Arduino Mega, but I'm trying to make sure it's parsing the GET requests in the fastest way possible. This is what the relevant code for the GET requests looks like:

String readString;
EthernetClient client = server.available();
if (client) {
  while (client.connected()) {
    if (client.available()) {
      char c = client.read();

    if (readString.length() < 20) {
      readString += c;
    }
    ...
    ...
      if (readString.indexOf("?a1o") >0){
        mySwitch.send(a1o, 24);
      }
      if (readString.indexOf("?a1c") >0){
        mySwitch.send(a1c, 24);
      }

The sketch checks for 40 possible GET variables. I'm running it as a local webserver with the address: http://192.168.0.180.

-Is there a command faster than "indexOf" that I could be using?

-I saw some information suggesting that sometimes "parseInt" can be faster. Is there any way for me to make that work even though my local base URL is already full of integers? I would be willing to convert the commands into integers (like "11" instead of "a1o") if there was a way to use parseInt or another faster command with it.

Thanks!

Well, for fast parsing I wouldn't use String for a start. I've written an example (below) which does away with the String class, and also demonstrates parsing the line once.

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
byte mac[] = {  0xB3, 0x8D, 0x72, 0x1D, 0xCE, 0x91 };

// Our IP address
IPAddress ip(10,0,0,241);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

void setup()
  {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) { } // wait for serial port to connect.

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print(F("Server is at "));
  Serial.println(Ethernet.localIP());
  }  // end of setup

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 100;
// the maximum length of paramters we accept
const int MAX_PARAM = 10;

// Example GET line: GET /?foo=bar HTTP/1.1
void processGet (const char * data)
  {
  // find where the parameters start
  const char * paramsPos = strchr (data, '?');
  if (paramsPos == NULL)
    return;  // no parameters
  // find the trailing space
  const char * spacePos = strchr (paramsPos, ' ');
  if (spacePos == NULL)
    return;  // no space found
  // work out how long the parameters are
  int paramLength = spacePos - paramsPos - 1;
  // see if too long
  if (paramLength >= MAX_PARAM)
    return;  // too long for us
  // copy parameters into a buffer
  char param [MAX_PARAM];
  memcpy (param, paramsPos + 1, paramLength);  // skip the "?"
  param [paramLength] = 0;  // null terminator

  // do things depending on argument (GET parameters)

  if (strcmp (param, "foo") == 0)
    Serial.println (F("Activating foo"));
  else if (strcmp (param, "bar") == 0)
    Serial.println (F("Activating bar"));

  }  // end of processGet

// here to process incoming serial data after a terminator received
void processData (const char * data)
  {
  Serial.println (data);
  if (strlen (data) < 4)
    return;

  if (memcmp (data, "GET ", 4) == 0)
    processGet (&data [4]);
  }  // end of processData

bool processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;
  switch (inByte)
    {
    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte
      if (input_pos == 0)
        return true;   // got blank line
      // terminator reached! process input_line here ...
      processData (input_line);
      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;
    }  // end of switch
  return false;    // don't have a blank line yet
  } // end of processIncomingByte

void loop()
  {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client)
    {
    Serial.println(F("Client connected"));
    // an http request ends with a blank line
    boolean done = false;
    while (client.connected() && !done)
      {
      while (client.available () > 0 && !done)
        done = processIncomingByte (client.read ());
      }  // end of while client connected

    // send a standard http response header
    client.println(F("HTTP/1.1 200 OK"));
    client.println(F("Content-Type: text/html"));
    client.println(F("Connection: close"));  // close after completion of the response
    client.println();   // end of HTTP header
    client.println(F("<!DOCTYPE HTML>"));
    client.println(F(""));
    client.println(F(""));
    client.println(F("<title>Test page</title>"));
    client.println(F(""));
    client.println(F(""));
    client.println(F("
My web page
"));
    client.println(F("
Requested actions performed"));
    client.println(F(""));
    client.println(F(""));

    // give the web browser time to receive the data
    delay(10);
    // close the connection:
    client.stop();
    Serial.println(F("Client disconnected"));
  }  // end of got a new client
}  // end of loop

The incoming lines from the client are captured in a static buffer. This eliminates issues with memory fragmentation (caused by using String).

processIncomingByte is called for each byte from the client. Once an entire line is assembled it calls processData. If that finds a "GET " line it calls processGet. That looks for the parameters on the GET line. The GET line looks like this:

GET /?bar HTTP/1.1

So we need to get between the "?" and the next space, to get the parameter ("bar" in this case). This can be accomplished by finding their positions with strchr.

Finally (as a simple example) I tested with strcmp for a direct match on various words. You could probably make that more efficient but I doubt it would matter much.


Powering up LED strip - How many amps? I want my Arduino to drive a LED strip.
The LED strip in particular is the 3528 non-waterproof type.
To power this up, I need a 12V power supply.
My LED strip is going to be 5 meters.

Now my questions are:

Is it important on how many amps, my powers supply will feed? One guy did it with 12V, 5A power supply. Considering the length (5m), is a particular amperage value necessary?
Can I power up the Arduino Nano with the power from the power supply? Voltage wise, I am clear, since the nano can handle 12 volts... What I am scared of is the amperage... Considering that I need a particular value of amps to power up my LED strip, can the nano handle this many amps? Is there a limit to how many amps the power supply line that I will feed my Arduino has to be?

Usually strips have not individual LEDs, but are composed of a lot of "pieces" in parallel, and each piece is composed by three leds in series along with a resistor.

Usually the strips are composed by 60 leds/m (i.e. pieces of 5cm), but sometimes also 120 leds/m or 30 leds/m. Let's assume it is the 60 leds/m version (you can check the length of the piece you can cut - which should be 5 cm - and that it contains 3 leds).

This means that in 5m there are 100 pieces. Now, usually the 3528 leds absorb 20mA of current for each segment (the 5050 version should be rated at 60). This means that the whole led strip should absorb 2A @ 12V.

Now the power supply. 2A is the nominal current the whole strips should absorb. Add about 200mA for the nano, and increase a bit the current requirement not to stress the power supply: you get a 12V 3A power supply at least (note that, while 12V should remain the same, you can take any current greater than this value - if for instance you have a 12V 5A power supply it is perfectly fine).

Now, the nano. It surely can't handle the 2A current. This means that you can power the arduino nano from the 12V. BUT beware: you should connect the 12V power to the VIN input (so the onboard regulator lowers it to 5V). Then you can't power the LEDs directly from the nano, but you need a transistor to decouple them. You can take any nMOS with a drain current greater than 3A or an NPN with collector current >3A and build the appropriate curcuit to drive them, then connect the + terminal of the strip to the +12V wire, the transistor source (or emitter) to the ground wire and the gate (base) should be driven by the nano.


pubsubclient won't compile in Arduino and VSCode IDEs I've compiled successfully a year ago in Arduino IDE, but lately I'm getting fatal errors:

/Users/davidjeffers/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.cpp: At global scope:
/Users/davidjeffers/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.cpp:473:8: error: redefinition of 'size_t PubSubClient::write(uint8_t)'
size_t PubSubClient::write(uint8_t data) {
^

In file included from /Users/davidjeffers/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.cpp:7:0:
/Users/davidjeffers/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:160:19: error: 'virtual size_t PubSubClient::write(uint8_t)' previously defined here
virtual size_t write(uint8_t) {};
^

I've tried using VSCode. I've tried opening an issue on GitHub.

Thanks for any thoughts.

The library is somehow modified. There should be no {} in virtual size_t write(uint8_t) {}; or the whole line shouldn't be in this .h.

Reinstall the library.


Simple Speed question - Mapping PWM values I am working on an Arduino project for school to power a 12V DC cooling fan.

I want to adjust the speed of the fan. The instructions say to set the motor pin at an equation of (0 to 9) * 10 + 150 to get a range of 150 to 240.

I need to write a mathematical equation but can not figure out what 150 to 240 means.  Is this voltage, resistance...?  Thanks for the help.

The analogWrite() function takes a value that is between 0 (fully off) and 255 (fully on).

Your value of 150 to 240 is a value within that range of 0 to 255 and represents a percentage of the "on time" of the PWM signal.

(150 / 255) * 100 = 58.8% on time
(240 / 255) * 100 = 94.1% on time.

You seem to have an "input value" of between 0 and 9 inclusive.  Let's call this value "i".  You want an output value, let's call it "o".

The instructions say "0 to 9 times 10 plus 150 to get a range of 150 to 240". That is simple enough to convert to a formula.  0-9 is i, remember:

o = i × 10 + 150

If i is 0 then o = 0 × 10 + 150 = 0 + 150 = 150.

If i is 9 then o = 9 × 10 + 150 = 90 + 150 = 240.

As Ignacio mentions, the Arduino API has a map function which is meant to be used for this kind of thing;

o = map(i, 0, 9, 150, 240);

However: the map() function is quite heavyweight since it is designed to be a generic mapping function for scaling values. Doi g the calculation manually will always be far more efficient since map will use steps and calculations that are not really part of your needed result. It's a bit like the differende between 1 + 2 and 1+ 5 - 3 + 2 - 4 + 2. The result is the same, but one is far simpler to calculate than the other.


Arduino Mega keep states after reprogramming Based on:

https://forum.arduino.cc/index.php?topic=440978.0

And some previous experience with Arduinos. What I would like to accomplish here is that I have a 8 channel relay board with the relays in different states. The Arduino is connected to a RaspberryPI via USB.

The first problem is well known the automatic reset of the Arduino which can be taken care of with a resistor or desoldering a pin on the Mega board so you can reconnect your Arduino as many time as you wish (while running on an external +5V power source) to the Raspberry and it will never reset.

However I also remember that doing this to the boards will also make them impossible to program because they cannot reset at the end when the sketch is uploaded.

I have think of a workaround:

1, Create a programming command on the arduino which is when it's received from the RPI it will connect that cut off pin with a relay which will make resetting possible again

2, Save all relay states to the EEPROM

3, After reset the Arduino always checks this programming flag in it's EEPROM and if it's present it either does not touch the relays or set them to the same position ON/OFF depending on the value it read back from the EEPROM

The last guy claims that: When the Arduino is in reset, all pins act like they aren't connected to anything. If you have an output which must be in a specific state during that period, you must add an external resistor to pull it up or down as required.

Is there any other solution for this problem? Like using a newer Arduino board which can keep pin states over reprogramming?

You have basically 2 distinct problems here. The problem to somewhat automatically enable/disable the reset from USB and the problem to keep the relays at their set states over reprogramming.

Enable/disable reset: The easiest way is to use a jumper, that you disconnect everytime you want to program the board. If you want to do it remotely, you already described a valid way, though I think, that you don't need a relay for that. A transistor or MOSFET should be sufficient for it.
Keep the relay states:

  Like using a newer Arduino board which can keep pin states over reprogramming?

I don't think, that something like that exists. It does not make sense for general purpose microcontrollers to do that; they all start from a clean state. So you need to save the state of the relays outside of the Arduino. What type of device you want to use for that is up to you. Majenko mentioned flipflops, which gives you the most basic functionality for this. You could also use devices, which are interfaces serially, like shift registers or even port expanders. Using flipflops will be the easiest way, since the programming does not change much. There are many examples how to use each of these devices with an Arduino on the web.


Use timer0 without affecting millis() and micros() I'm writing a library which needs an ISR to turn off an LED some time after it was turned on. Since it's all about turning an LED on and off it doesn't need to be very precise. On the other hand I would like to use this library in a program where timer1 and timer2 are given out to other (more important) tasks, and I also need the millis() and micros() functions. Last, I'm using an ATmega328P microcontroller, which only has 3 timers (and I can't easily replace it with another one).

So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions, and – if that can be done – what would be the restrictions of such an ISR (e.g. I suppose I could not use all the timer/interrupt modes...) and the disadvantages or side effects in using this timer in a non-Arduino library and the Arduino millis() and micros() functions.

Thanks in advance for any answer!

So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions,

Yes. A few ways, depending on your level of comfort:

You can declare the stock Arduino Timer0 OVF "weak" and write your own where you can insert your ISR. But you have to handle the interaction between the millis() / micros() related variables.
You can modify the stock Arduino Timer0 OVF to insert your own ISR.

And – if that can be done – what would be the restrictions of such an ISR (e.g. I suppose I could not use all the timer/interrupt modes...)

The stock ISR would look like this:

ISR(TIM0_OVF_vect) {
    ...
    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;

    //insert your isr here
    _mytmr0_isrptr();
}

Where _mytmr0_isrptr() is a function pointer to your own ISR handler.
The simplest is probably to use the output compare interrupts. You can get it to behave like a virtual timer and can do lots of other stuff.

Obviously, you can think of tons of other ways and this is just a starting point.

  What are those interrupts? How can I use them? –

Timer0 has three interrupts associated with it: overflow and compare channel A and channel B. The overflow interrupt is already being used by the timing functions millis() and micros(), as shown earlier.

The compare channel A/B interrupts are unused. And this discussion is about using them for timing purposes.

The general ideal is demonstrated in blog post Using Spare Output Compare Channels as Timers – the Collection.

The task there is more complicated than what you are trying to do here, but the basic ideal is the same. To do what you wanted here it is much simpler than that.

If you still cannot figure it out, I can provide you with code pieces to get you started.


Solar Tracker Code - how to limit steppers to max & min angle? a couple of friends and i are working on a double axis solar tracker with a Adafruit Motor-shield V2 and 2x Adafruit bipolar stepper motors (200/rev).
We got the following code so far but are stuck with getting the steppers to stop at a certain angle (90° for vertical and 180° for horizontal) so that we dont tangle up the wires and avoid unnecessary movement. Any help and sugestions would be much appreciated.

Cheers

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *stepperh = AFMS.getStepper(200, 1);  // declaring horizontal stepper
Adafruit_StepperMotor *stepperv = AFMS.getStepper(200, 2);  // declaring vertical stepper

int ldr1 = A0;  // right ldr
int ldr2 = A1;  // centre ldr
int ldr3 = A2;  // left ldr
int ldr4 = A3;  // top ldr
int ldr5 = A4;  // bottom ldr

const int threshold = 550;  // limit to stop tracker from moving at night

const int tol = 50;  // tolerance for ldrs // maybe vertical AND horizontal depending on difference?

//int = countv
//int = counth

//const int maxh = ?    // to prevent overturning horizontal (50 steps = 90°)
//const int minh = ?    // combine with count int's // i.e. if counth > 90 - stop
//const int maxv = ?    // to prevent overturning vertical
//const int minv = ?

void setup()
{
  AFMS.begin();
  stepperv->setSpeed(10);
  stepperh->setSpeed(10);
}

void loop()
{
  int right = analogRead(ldr1);
  int centre = analogRead(ldr2);
  int left = analogRead(ldr3);
  int up = analogRead(ldr4);
  int down = analogRead(ldr5);

  //STOP MOVEMENT//
  if ((left < threshold) && (right < threshold) && (up < threshold) && (down < threshold)) {}  // stop any movement if sensor values below threshold
                                                                                // at begining to check after every sensor reading

  //HORIZONTAL MOVEMENT//
  if((right > centre + tol) && (left + tol < centre))   // && (right - ? > tol)
  {
    stepperh->onestep(BACKWARD,DOUBLE);  // add +1 to int counth // if (minh < counth < maxh) - move // else - stop // counth=counth++ , counth=counth--
  }
  else if((left > centre + tol) && (right + tol < centre))  // && (left - ? > tol)
  {
    stepperh->onestep(FORWARD,DOUBLE);
  }
  else {}  // do nothing

  //VERTICAL MOVEMENT//
  if((up > centre + tol) && (down + tol < centre))  // && (up - ? > tol)
  {
    stepperv->onestep(BACKWARD,DOUBLE);
  }
  else if((down + tol > centre) && (up + tol < centre))  // && (down - ? > tol)
  {
    stepperv->onestep(FORWARD,DOUBLE);
  }
  else{}  // do nothing
}

The only sure way is to use one or more position or limit switches. Steps can be lost (motor didn't move as commanded due to, f/ex, overload), the motor could be back-driven while powered down or if over-powered by the mechanical system, or your step counting could be faulty due to a bug or a power glitch.

At power-up or at any time your software thinks it might have got out of sync with the mechanicals, back into the limit switch at low speed (so you don't hard-crash), and reset your software counters, and reposition from there.


JSN-SR04T-2.0 with NodeMCU not starts after reset or reconnect usb power I have bought a NodeMCU (1.0) and a JSN-SR04T waterproof ultrasonic sensor compatible with HC-SR04.

If I upload my program to NodeMCU it works but sometimes it measures a wrong distance - it is an another question, but it may connect to this question.

If I press the reset button my application not starts or if it is unplugged and plugged in to usb power it not starts.

If I unplug the ultrasonic sensor 3.3V and ground it starts.

It starts with the following code:

const int trigPin = D4;
const int echoPin = D3;

void flashLed() {
  digitalWrite(LED_BUILTIN, LOW);
  delay(400);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(100);
}

void setup() {

  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

  flashLed();
  Serial.begin(115200);
  flashLed();
  delay(10);

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    digitalWrite(LED_BUILTIN, HIGH);
    delay(1000);
    digitalWrite(LED_BUILTIN, LOW);
    delay(1000);
  }
  Serial.println("");
  Serial.println("WiFi connected");

  server.begin();

  Serial.println("Web server running. Waiting for the ESP IP...");
  delay(10000);

  Serial.println(WiFi.localIP());

  digitalWrite(LED_BUILTIN, HIGH);

}

I have uploaded the full source code to github project:

https://github.com/kisdaniel/nodemcu-wif-http-HC-SR04/blob/master/HomeDashboardUltrasonicHttp.ino

Why it not starts?

UPDATE:

I have make a minimal version of code to reproduce the problem:

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

void loop() {
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(2000);
}

Wiring:

Node MCU 3.3V -  Vcc (ultrasonic sensor)
Node MCU GND  -  GND (ultrasonic sensor)
Node MCU D4   -  Trigger (ultrasonic sensor)
Node MCU D3   -  Echo (ultrasonic sensor)

To enable ESP8266 firmware flashing GPIO0 pin must be pulled low
  before the device is reset. Conversely, for a normal boot, GPIO0 must
  be pulled high or floating.

The D3 pin is equivalent  GPIO0. For a normal boot, GPIO0 must be pulled high or floating while powering up or resetting the module. After that (normal boot), you can use the output for other purposes.

You can use a different output or try to use a pull-up resistor for the D3.


Sparkfun Pro-Micro stuck on uploading I have read multiple posts on how to reset the sparkfun pro-micro when it gets stuck during upload, and this seems to work to get it back to a state where I can upload new code again - However, I am here to ask if it is possible that it is something in my code that is causing this issue?
The reason I suspect it is my code is because I have tried:

Different pro micro
Different USB cable
Downloaded latest IDE
Downloaded latest AVR boards package
Tried reverting back to an older AVR boards package as suggested in a different post

Not sure if this is a coincidence, but when I upload a simple blink sketch I don't have any trouble, but as soon as I upload my code (below), it gets stuck on uploading...
I can get it to eventually upload after many attempts using the reset during upload trick, but it seems to be unstable. I say unstable because sometimes it will print out the values requested, and other times it will print nothing...

int clampVal = 0;

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

void ClampReading()
{
    const int numRead = 400; //amount of calibration values we will average
    double vals[numRead];      // the readings from the analog input
    int readIndex2 = 0;                 // the index of the current reading
    double total2 = 0;                  // the running total
    int calibration2 = 0;               // calibration incrementer

    for (int thisReading2 = 0; thisReading2 < numRead; thisReading2++) {
    vals[thisReading2] = 0;
    }
    while(calibration2<numRead)
    {
      int rawClamp = analogRead(A0);
      total2 = total2 - vals[readIndex2];
      vals[readIndex2] = rawClamp;
      total2 = total2 + vals[readIndex2];
      readIndex2 = readIndex2 + 1;
      if (readIndex2 >= numRead) {
        readIndex2 = 0;
     }
      clampVal = total2 / numRead;
      calibration2++;
    }

}

void loop() {
 ClampReading();
 Serial.println(clampVal);
}

EDIT:
Once I reset and upload an EMPTY sketch, I can upload the empty sketch with no problems. I did it 5 times in a row with no issues. Then tried to upload the code above once, and it worked..but then tried to upload second time, and stuck in uploading again... it has to be the code, but I can't narrow down what it is.

Uno's Mega's and so on have a separate MCU (u3) that contains the boot loader and is responsible for the USB connection and for driving the virtual serial port. Micros ( and also Leonardos and Esploras ) have built in USB support in the main MCU (u4). So if your program does something that breaks the USB part of the MCU the communication breaks also. This  happens for instance if you disable the interrupts.

The only thing you use in your program that might cause a problem is the Serial connection. The blink example has no serial output.

If you add a Serial.begin(115200) and a Serial.println("Hello") to the blink example, I guess the problem occurs also.

The IDE establishes the programming connection by connection to the selected com port at 1200 Baud. The boot loader recognizes that, performs an auto reset and opens a second (programming port) from then the IDE has access to this port and uses it to communicate with the boot loader. On a UNO this is handled by the separate MCU and on the Micro the main CPU is responsible for that.

Perhaps it helps if you add a time delay, before the Serial.begin(). Then you will have more time to start the programmer.

There is also a trick to enlarge the time you can start the programming after a reset to 8 seconds. https://forum.arduino.cc/index.php?topic=224416.msg1643210#msg1643210

And one additional hint:

Your code is unnecessarily complicated. If you want, you can try the program below. I think it does the same as yours. I have no compiler and no micro at the moment so it's complete untested.

You used a calibration variable. I guessed that it is for skip the first calibration values. If you need the values you can store them in a separate array.

My prog. has a lower memory footprint because I store the integer values from the analog input into an integer array. You used a double array.

You also did a lot of unnecessary computations after you read an analog value. This can slow down the readings. Perhaps therefore you missed some values you expected to see.

//amount of calibration values we will average
const int valueCount = 400;
const int calibCount =   0;

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

void loop()
{
  // the readings from the analog input
  int vals[ valueCount ];

  for (int idx = 0; idx < valueCount + calibCount; idx++)
  {
    int rawValue = analogRead( A0 );
    if ( idx >= calibCount )
    {
      vals[ idx - calibCount ] = rawValue;
    }
  }

  double total = (double) 0.0;

  for (int idx = 0; idx < valueCount; idx++)
  {
    total += (double) vals[ idx ];
  }

  Serial.println( total / valueCount );
}


Infinite "while" statement I am building a robot that is both obstacle-avoiding and remote-controlled. The robot uses an infrared remote.  When the front button is pressed the robot moves front, when the right button is pressed the robot turns right, and so on...
When a certain button is pressed the robot switches to obstacle-avoiding mode and starts to drive around. When the ultrasonic sensor detects an object 15cm away the robot turns right, reverses, and then continues moving forward. the obstacle-avoiding code has a problem, though. Here is the code:

#include <EEPROM.h>
#include <IRLib.h>
#include <AFMotor.h>
int frontlights = A1;
int backlights = A2;
int buzzer = A3;
int pingPin = A4; //setup pingpin as A4

//ir variables
int RECV_PIN = A0;
IRrecv My_Receiver(RECV_PIN);
IRdecode My_Decoder;
unsigned int Buffer[RAWBUF];

void obstacle_avoiding(){
   while (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){  // when the automatic mode button is pressed and the stop button is not pressed do...

 motor4.setSpeed(230);
 motor3.setSpeed(230);
 motor2.setSpeed(230);
 motor1.setSpeed(230);

    long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  delay(90);

      if(cm>15){          // if an object is greater than 10cm move forward
      motor_forward();
      Serial.println("forward");
      digitalWrite(backlights, LOW);

      }

     else if (cm<=15)     // if an object is less than or equal 10cm move backward then turn right
     {
      motor_stop();
      digitalWrite(frontlights, HIGH);
      digitalWrite(backlights, HIGH);
      digitalWrite(buzzer, HIGH);
      delay(200);
      digitalWrite(buzzer, LOW);
      delay(2000);
      motor_backward();
      digitalWrite(backlights, HIGH);
      Serial.println("backward");
      delay(500);
      motor_stop();
      digitalWrite(backlights, HIGH);
      delay(900);
      motor_right();
      digitalWrite(backlights, LOW);
      Serial.println("right");
      digitalWrite(frontlights, LOW);
      delay(400);

   }
   if (My_Decoder.value==0xFF0AF5){   //the stop button is pressed break the "while" loop and stop the robot
   break;
   motor_stop();
   }
 }
}

void loop() {
   long duration, inches, cm;
    if (My_Receiver.GetResults(&My_Decoder)){
       //Restart the receiver so it can be capturing another code
       //while we are working on decoding this one.
       My_Receiver.resume();
       My_Decoder.decode();

    //automatic code here
            else if (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){
              obstacle_avoiding();

            }

          }

        }

The code is working however when the "while" statement becomes true it will loop infinitely not stopping even when the condition has become false. I thought while statements should loop until the condition becomes false. Am I misinformed?

My_Decoder.value doesn't change inside obstacle_avoiding(). Hence, while is running infinitely.

I think you have to delete the while, and let loop() take care of controlling the execution.

Addendum

The intent of the loop() is to read some IR data in value. I under the impression that getResults() sometimes block, acording to this:

  However the IRrecvLoop is not interrupt driven and so when you call
  GetResults it sits in a tight loop and does not release control back
  to you until the complete signal has been received.

I also want to check that value doesn't change if getResults() return nothing with this loop()

void loop() {
bool r = My_Receiver.GetResults(&My_Decoder)
Serial.print("getResults()=");
Serial.print(r);
Serial.print(" value=");
Serial.println(My_Decoder.value);

if (r) {
    //Restart the receiver so it can be capturing another code
    //while we are working on decoding this one.
    My_Receiver.resume();
    My_Decoder.decode();
} else {
    if (My_Decoder.value == 0xFF807F && My_Decoder.value != 0xFF0AF5) {
        obstacle_avoiding();
        }
    }
}

I hope this works!