text:
Strange Arduino Serial Behavior
I have a quirky question today.
I have an Arduino MEGA 2560 with a very simple setup. It's connected to my pc over usb, and has one device connected on its onboard TX/RX2 port group. Whenever I open the COM port on my pc I see a short spike in voltage on the TX2 pin. An analogous behavior happens on even the simplest sketches so I don't think it's the library I'm using to talk to this device.
With the sketch below instead of a short spike in voltage, the TX2 line stays high and when the pc's COM port is opened that TX2 line drops to 0v for maybe a half second.
Not super relevant info about device
It's a Noritake GU140X32F-7000 display. The mfg website doesn't list it's model directly but the
info on the 'B' variant, and it's supplied AVR code, work just fine.

MFG Website for this model>> https://noritake-vfd.com/gu140x32f-7000b.aspx
Code Library>> https://www.noritake-elec.com/codeLibrary.php#gu7000

Relevant bare-minimum code to see this effect on an oscilloscope connected
GRD <-> AVR Ground, POS <-> Pin16(TX2)
void setup() {
  Serial.begin(115200); // Connection to computer
  Serial2.begin(38400); // Connection to TX2 pin 16
  Serial2.write('akjlahsdkjahsdkjlhasdkjhaskldjhaksjhd');
}

uint8_t serialByte = 0;
void loop() {
  if (Serial.available() > 0) {
    serialByte = Serial.read();
  }
}

What happens, which I don't want happening, is after I've had the Arduino draw to the Noritake screen, and I open or reopen the COM port from my pc to the Arduino, the screen blanks itself. Doesn't matter if I use PUTTY, python's serial library with
ser = serial.Serial('COM4', 115200, R timeout=0,parity=serial.PARITY_NONE, rtscts=1)
or Serial Port Monitor's trial version from https://www.com-port-monitoring.com/ via the send dialog - it happens either way.
Especially weird is I don't see data going over this COM port in the Serial Monitor software when the COM port is opened and yet my oscilloscope (fairly crappy DSO138) catches a spike in voltage happen the moment this serial line is opened from my pc. When I use the Noritake library the TX line is normally low when there's no data, whereas the Arduino built in Serial2 line is normally high until there's data. Then when I connect it goes low for about a half second. The code Noritake uses to communicate over this serial line is a bit odd, not actually using the Serial or Stream built in classes, instead opting to write data manually to this port and only including these two external libraries.
#include <avr/pgmspace.h>
#include <util/delay_basic.h>

What causes Serial2 to go low when my PC opens the COM port to Serial on my Arduino? What can I do to prevent it from writing to Serial2?

You're probably over-researching things and finding a problem that isn't a problem. The simplest reason: when you open serial the Arduino resets and your sketch runs from the start again.

Ok this answered my question. Thank you! Do you want to get credit for it or should I answer this thread myself?

Why would we delete this question? I suggest @Majenko post his comment as an answer and the answer get selected. Don't delete valuable debugging info. like this from the internet.

Interrobang, you can also answer your own question, and then select it as the right answer in 2 days. I suggest keeping the question and answering it yourself, quoting Majenko.

I'm going to wait the two days, thanks Gabriel!

As to why this happens: connecting to the Arduino with the built in USB port would wipe the display because the Arduino would reset and re-initiate the display initialization routine. The spike in current was actually the initialization signal. In the bare minimum sketch the signal going high, low, then back high was again due to the Arduino resetting.
The solution I'm going with is just changing how I connect to my Arduino with python by adding dsrdtr = 1 to my serial declaration. I tested this and my Arduino no longer resets, and uploading sketches is not impacted.
# Python 3.7.5
import serial
ser = serial.Serial('COM4', 115200, timeout=0, parity=serial.PARITY_NONE,
                   rtscts=1, dsrdtr = 1)

I removed the part with links to mostly obsolete and not applicable information about auto-reset. Leonardo is very different in this and the current Uno/Mega boards have pads which can be cut to disable auto-reset and eventually connected again with solder. the solution for Python is nice. upvote for this


text:
Can the Arduino interface with a fingerprint sensor on my mobile?
I own a OnePlus 6 and it has a fingerprint sensor. Instead of using a fingerprint scanner module like the R305, could I just use my mobile for scanning the fingerprints? If yes, how do I implement this?
This is for creating a smart home security system.

JRobert has a good point in his answer. what for to send the fingerprint to arduino if the phone is already authenticated?

You'd need an app on your mobile to read the sensor and communicate the result to your Arduino in a secure way that cannot be spoofed by an intruder. That secure communication over an open channel (WiFi, I assume?) is not trivial to do right, so that would be a weak point in your security.
Blynk, an app+server+Arduino library combination provides an authentication token to pair with your Arduino in a relatively secure way. You quickly make (drag-and-drop) a control panel for your Arduino system with it. It doesn't offer fingerprint sensing directly, but if you keep your Blynk authentication token a secret, keep your Blynk app+token on your mobile, and the mobile is fingerprint-locked, you'd have essentially the same thing, and the pieces already exist. You'd only need to code the smart-home parts for the Arduino.

Majenko in his answer described how to do it if you can code an application for phone. Other option is a little  overkill, but should be a ready solution. You could use 1Shield. It is a shield, a library and a phone app to use phone resources with Arduino. It supports fingerprint sensor. I have no experience with it, I only read about it.

Technically, yes it is possible.

Write an app for your phone that scans your fingerprint and does "something" with it.
Decide on (and implement) some form of communication protocol between the phone and the Arduino and send data from the phone depending on what you decide the "something" above is.
Write a sketch for your Arduino that responds to that communication protocol and performs whatever task you require.

The Arduino side of things, effectively, has nothing at all to do with the fingerprint scanner - it just accepts data from your phone. The fact that the phone is generating that data using the fingerprint scanner as a stimulus is of no importance to the Arduino.
99% of the work for the fingerprint scanner will be done on the phone, and done using phone software. Not Arduino software.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Ultrasonic sensor and ledstrip color problem
So I've made a parking sensor with the Ultrasonic sensor and a ledstrip. But the ledstrip doesn't turn yellow or green. I think it has to do with the Thresholds. Can anyone help me to set this up? I also want a longer distance greater than 1 meter. This is my code:
#include "FastLED.h"
 #include <math.h>

    #define NUM_LEDS 32
    #define BRIGHTNESS 10
    #define DATA_PIN 4

    // Define the array of leds
    CRGB leds[NUM_LEDS];

    // Module Pins
    #define trigPin 11
    #define echoPin 12

    // Thresholds (in CM)
    long SECTION_SIZE = 80;
    long STOP_DISTANCE = 60;
    long WARNING_THRESHOLD = 50;
    long MAX_THRESHOLD = 375;

    long RED_THRESHOLD = STOP_DISTANCE;
    long YELLOW_THRESHOLD = RED_THRESHOLD + SECTION_SIZE;
    long GREEN_THRESHOLD = YELLOW_THRESHOLD + SECTION_SIZE;

    const int numReadings = 5;

    int readings[numReadings];      // the readings from the analog input
    int readIndex = 0;              // the index of the current reading
    int total = 0;                  // the running total
    int average = 0;                // the average

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

      FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
      FastLED.setBrightness(10);

      // HC-SR04 Setup
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);

      // initialize all the readings to 0:
      for (int thisReading = 0; thisReading < numReadings; thisReading++) {
        readings[thisReading] = 0;
      }
    }

    void loop() {
      long distance, lastRun;
      bool red, yellow, green;
      total = total - readings[readIndex];
      readings[readIndex] = calculateDistance();
      total = total + readings[readIndex];

      readIndex++;
      if (readIndex >= numReadings) readIndex = 0;

      distance = abs(total / numReadings);

      yellow = distance <= YELLOW_THRESHOLD && distance > RED_THRESHOLD;
      red = distance <= RED_THRESHOLD;
      green = distance > YELLOW_THRESHOLD && distance <= GREEN_THRESHOLD;

      if (red) {
        setRed();
      } else if (yellow) {
        setYellow(distance);
      } else if (green) {
        setGreen(distance);
      } else {
        setGreenStandby();
      }

      Serial.print(distance);
      Serial.println(" cm");
      FastLED.show();
      delay(1);
    }

    void lightItUp(const CRGB& pColor, const CRGB& sColor, uint16_t travel) {
      uint16_t travelFix = travel * (NUM_LEDS/SECTION_SIZE);
      uint16_t leftStop = travelFix/2;
      uint16_t rightStop = NUM_LEDS - leftStop;
      for (int i = 0; i < NUM_LEDS; i++) {
        if (i < leftStop || i > rightStop) {
          leds[i] = pColor;
        } else {
          leds[i] = sColor;
        }
      }

      FastLED.show();
    }

    long calculateDistance() {
      long duration;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      return (duration/2) / 29.1;
    }

    void setGreenStandby() {
      return fill_solid(leds, NUM_LEDS, CRGB::Black);
    }

    void setRed() {
      return fill_solid(leds, NUM_LEDS, CRGB::Red);
    }

    void setGreen(long distance) {
      long travel = GREEN_THRESHOLD - distance;
      return lightItUp(CRGB::Yellow, CRGB::Green, travel);
    }

    void setYellow(long distance) {
      long travel = YELLOW_THRESHOLD - distance;
      return lightItUp(CRGB::Red, CRGB::Yellow, travel);
    }

what is longer distance greater than 1 meter?  .... please describe exactly what you want the code to do ..... also describe exactly what it does right now ..... add the information to the question above .... DO NOT add info to comments

I believe your mistake is in this part of your code:
  yellow = distance <= YELLOW_THRESHOLD && distance > RED_THRESHOLD;
  red = distance <= RED_THRESHOLD;
  green = distance > YELLOW_THRESHOLD && distance <= GREEN_THRESHOLD;

  if (red) {
    setRed();
  } else if (yellow) {
    setYellow(distance);
  } else if (green) {
    setGreen(distance);
  } else {
    setGreenStandby();
  }

In particular, you are defining three boolean variables independently and then switching based on their values.
Assuming you are seeing the right values output on serial monitor (like 90 cm, 60 cm, etc...), which is something I'm unsure of as I'm not getting how you are determining the distance, then the following should be easier to follow/understand:
if (distance > GREEN_THRESHOLD) {
  setGreenStandby();
} else if (distance > YELLOW_THRESHOLD) {
  setGreen(distance);
} else if (distance > RED_THRESHOLD) {
  setYellow(distance);
} else {
  setRed();
}

You have only one variable determining the led strip configuration, no need to go to 3 and then try to reduce again ;-)
Please note that your YELLOW_THRESHOLD is defined as 140, if you don't ever see a message in the serial monitor greater than that value you don't have a chance of seeing any colour other than red.... I'm asking because you mentioned I also want a longer distance greater than 1 meter that might imply your sensor is unable to go farther than 1 meter...
With the code above I'm checking the distance in a greater to smaller order: the first matching is the only one activated and it's impossible for the distance variable to match more than one condition. Generally speaking, simpler is better.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Triggering an SPI transfer with an interrupt in Arduino Due
I have a DDS that is controlled by an Arduino DUE,  loop() waits for Serial commands and based on them calls one or another function that sets the DDS's frequency, phase, amplitude etc via SPI. In addition to that I want to be able to use an external interrupt triggered by a TTL signal to reset the DDS's phase accumulator. The phase reset is done by writing an SPI register - resetPhase().
Somehow the resetPhase() is triggered correctly, but as soon as I add a SPI.transfer to it the SPI communication stops working altogether, not just through interrupts, but also the functions triggered via serial commands stop working.
Is there a way to get it to work?
SPISettings spiSettings = SPISettings(10000000, MSBFIRST, SPI_MODE0);

void setup()
{
    pinmode(chipSelect, OUTPUT);
    int syncPIN = digitalPinToInterrupt( interruptPin);
    SPI.usingInterrupt(syncPIN);
    attachInterrupt(syncPIN, resetPhase, RISING);
}

void resetPhase():
{
    SPI.beginTransaction(spiSettings);
    digitalWrite(chipSelect, LOW);
    SPI.transfer(controlRegister);
    digitalWrite(chipSelect, HIGH);
    SPI.endTransaction();
}

Probably SPI transfers use an interrupt, which can't trigger because you're already in an interrupt.  You should have the SPI operations outside the interrupt and just update some variables and set a flag in your interrupt.

I am not familiar with the internal workings of the Due SPI library to be sure though.  Best to be safe and not do SPI in an interrupt regardless.

@Majenko I thought that the SPI.usingInterrupt is specifically for that purpose// If SPI is used from within an interrupt, this function registers  // that interrupt with the SPI library, so beginTransaction() can  // prevent conflicts.  The input interruptNumber is the number used  // with attachInterrupt.  If SPI is used from a different interrupt  // (eg, a timer), interruptNumber should be 255.  static void usingInterrupt(uint8_t interruptNumber);

In general, it's best to do as little as possible in your interrupt service routine (ISR).
resetPhase is your ISR here, and typically it would set a flag or semaphore to signal lower priority code that certain work needs to be done and, in this case, probably nothing more. Then your loop code on noticing the flag is set would clear the flag and do its work.
I imagine the library authors thought SPI.usingInterrupt would ease use of SPI, but performing I/O in an ISR seems a bit contrary to best practices. These concerns are echoed here, along with some other caveats regarding interrupts and ISRs. Possibly not the answer you're looking for, but I hope it helps.


text:
How to make Built in LED blink systematically?
I am trying to make my built in LED on my arduino blink every 1 second while recording my data and putting it in the EEPROM, but I am not sure how to do that. I am supposed to print data to the EEPROM every minute, until the EEPROM is full and while that is going on my built in LED should blink for approx 1 second. My problem seems to be that I am setting a delay to delay how long the data is stored on the EEPROM, but it is also affecting the time it takes for my LED to blink as it is waiting to blink as the data is stored. Any help would be appreciated, the code is below:
#include<EEPROM.h>
const int SWITCH = 4;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(SWITCH, INPUT_PULLUP);

}

void loop() {
  // put your main code here, to run repeatedly:
  int addr = 0;
  int r = analogRead(0);

  if (digitalRead(SWITCH) == LOW) {
    Serial.println("----Recording----");
  }
  while (addr <= 1024) {
    digitalWrite(LED_BUILTIN, HIGH);
    delay (250);
    digitalWrite(LED_BUILTIN, LOW);
    delay(750);
    Serial.println(r);
    EEPROM.put(addr, r);
    addr = addr + 2;
    delay(600);
  }
  while (true);
}

If you add up all your delays you get 1600ms. Removing the last delay(600); would make the duration of you loop a lot closer to 1 second. Indeed the other code would take a bit of time to, but my guess would be that it only takes 5ms per cycle. Depending on you application, that might be good enough. It might also be the case that you need it so precise that the precision of the crystal the Arduino uses isn't good enough.

Do not use delay(). Use the example Blink without delay example as the starting point.
https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
Find it under Examples    02.Digital
Simple code like delay() is called blocking code. It prevents other things from happening until t is through. That is acceptable in very sequential linear programs where only one thing is ever happening. And you have discovered the limitation of that. Time to get more sophisticated in your programming.
Please open the example and play with it. Make sure you understand it before thinking of how to modify your code.

Would you be able to clean up my code to do this? I'm not sure how I am supposed to go about doing what you said

I added more to the answer. Open the example and learn what it does. Don't think about your program yet. You need to learn this kind of thing and not just copy someone's code.

As Rudy mentions in his answer, don't use delay(), and start with the BlinkWithoutDelay example that comes with the Arduino IDE. Here is a sketch to get you started. If you compare it to the BlinkWithoutDelay example, it's very similar, except I added some button code to "start" and "stop" the LED flashing.
const byte SWITCH = 4;
const byte ledPin = 13;
const unsigned long oneSecond = 1000;
unsigned long previousMillis = 0;
byte ledState = LOW;
byte recording = 0;

void setup(){
  pinMode(ledPin, OUTPUT);
  pinMode(SWITCH, INPUT_PULLUP);
}

void loop(){

  unsigned long currentMillis = millis();

  if(digitalRead(SWITCH) == LOW){
    recording = 1;
  }
  else{
    recording = 0;
    digitalWrite(ledPin, LOW);
  }

  if(currentMillis - previousMillis >= oneSecond){

    previousMillis = currentMillis;

    if(recording){
      if(ledState == LOW){
        ledState = HIGH;
      }
      else{
        ledState = LOW;
      }
    }
    digitalWrite(ledPin, ledState);
  }
}

I didn't post modified code because I want him to understand what is happening in the example without proceeding with his program. I feel it is more important to learn than to just get an answer.

I agree with you Rudy. As I mentioned in my answer, this sketch is almost identical to the BlinkWithoutDelay example, with the addition of the "button code" that Thomas already wrote. I just wanted Thomas to start heading in the right direction. Thomas still has to figure out how to add a "minute" timer to the sketch, get the analog reading and store it in EEPROM. That will keep him busy for a while :)


text:
Accessing multiplexed I2C and UART pins of STM32F103 in arduino IDE
I want to access both of the multiplexed I2C and UART pins in the same program. I am programming in Arduino IDE.Can anyone please tell me how to access same pins for different functionalities?

I want to use Serial debug and MPU6050 in my application. All other pins are occupied with one or the other sensors and other devices. Only PB6 and PB7 is left., which is UART and I2C and I need both.

And how do you propose to remove the I2C device when using UART, and to remove the UART connection when using I2C?

If your chosen MCU doesn't have the resources that you need then you have chosen the wrong MCU.

do you have a network connection on the MCU? WiFi or Ethernet? use Telnet for debug output

No I dont have any network connection in the MCU

@Majenko Cant I do that in program? That is connecting both I2C and UART devices to the same pins and doing TDMA. like for some 100ms UART device will send information and for the next 100 ms I2C device will send data. When one device is sending data the other device will not be active.

this is the only one I2C device you use?

Yes. this is the only one

You can't. (Well, you can, but you mustn't).
I2C and UART are electrically incompatible bus systems.  UART is a Push-Pull system, whereas I2C is an Open-Drain system.  The Push-Pull connections will interfere with the Open-Drain outputs and I2C will not function.
If you want to have both you will need to include extra hardware (and the necessary control pins) to physically isolate the different devices from their respective bus when not in use.

Can I use a multiplexer to isolate the devices?

how do you want to control the multiplexer?

Only if it's a specialised multiplexer that knows about both UART and I2C. And I doubt such a thing exists.

In order to use two different peripherals on the same pins, you have to initialize I2C and de-intialize UART when using I2C and doing the opposite when using UART.
It’s not possible to initialize two different peripherlas on the same pins, concurrently.


text:
CAN bus libraries for STM32F103 in Arduino IDE
I need to implement CAN communication between two STM32F103 microcontroller boards. I am finding it difficult to get libraries for the same. Can anyone please suggest where I can find working CAN bus libraries for STM32F103?

Have you tried stm32duino.com forum pages?  http://www.stm32duino.com/search.php?keywords=CAN+bus

Yes, but there are no valid libraries in that @smajli


text:
How to avoid Multiple definition of 'Blynk' error?
By including
 #include <BlynkSimpleEsp8266.h>

Blynk library (https://github.com/blynkkk/blynk-library) from more than 1 module/cpp file, "Multiple definition of `Blynk’" error is thrown at compile time. The header file contains following:
static WiFiClient _blynkWifiClient;
static BlynkArduinoClient _blynkTransport(_blynkWifiClient);
BlynkWifi Blynk(_blynkTransport);

How can I get the Blynk declarations into a second or third module, without multiple definitions error? Editing the header/library file/s is not an option!
By the question in How to create global variables/includes/functions for use in multiple source files it is still not clear what a working solution is...

Whole magic of "possible duplicate" is the extern keyword in header file and instance must be defined in .cpp file (without extern). The extern means this variable is placed somewhere else.

You want to include header, that CAN NOT be included in more than one cpp file, in more than one cpp file without any change in that header file. You may think we don't read your question, but it's just because there is no other way than fix to the library using extern.

The Blynk "simple" header files are not ready to be included into multiple cpp files. They are meant to be included only in the main ino file. The reason is that the variable allocations are in headers file, which is bad practice for  C and C++. The h files should contain only declarations. The right way would have
extern BlynkWifi Blynk;

and the lines which are now in the h file should go in a cpp file. Then every cpp file that includes the .h will know about the variables but the variables would be allocated only once.
The fix is to change the library or to copy the BlynkSimpleEsp8266.h include to your project as for example MyBlynk.h and change the Blynk variable in MyBlynk.h to extern and add a MyBlynk.cpp file with variables allocation
#include "MyBlynk.h"

WiFiClient _blynkWifiClient;
BlynkArduinoClient _blynkTransport(_blynkWifiClient);
BlynkWifi Blynk(_blynkTransport);

As good as Blynk is - and it is; I use it for many of my projects - and even though it is actively being maintained and improved, this issue has remained uncorrected. It is one of the few blemishes in an otherwise incredibly useful project.

it is a compromise. that is why it is called "simple". they can't create cpp for this, because the builder would try to compile all the cpp for different networking libraries and board architectures. they could make ifdefs for architectures but not for libraries


text:
strtok keep original char
I want to make a vocab program for an arduino. The vocabs are saved in a char array seperated with an '/'. Now I want to split a random picked char and split it at the '/' so I can save it into two variables. But if I do it with strtok the original string gets sacrificed. If now the same vocab comes again...
I hope you can help me, but if you think a other way to do it would be better I'm open for suggestions.
Here's my code
long random1, random2, random3, random4;
int lengtharray = 5;
char* vocab1;
char* vocab2;
char* vocab3;
char* vocab4;
char* german1;
char* english1;
char vocabs[5][16] = {"Apfel/apple","er/he","Zoo/zoo","sie/she","Hallo/hello"};

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

void loop() {
randomSeed(analogRead(0));
random1 = random(0,lengtharray);
randomSeed(analogRead(0));
random2 = random(0,lengtharray);
while(random2 == random1){
    randomSeed(analogRead(0));
    random2 = random(0,lengtharray);
}
randomSeed(analogRead(0));
random3 = random(0,lengtharray);
while(random3 == random1 || random3 == random2){
    randomSeed(analogRead(0));
    random3 = random(0,lengtharray);
}
randomSeed(analogRead(0));
random4 = random(0,lengtharray);
while(random4 == random1 || random4 == random2 || random4 == random3){
    randomSeed(analogRead(0));
    random4 = random(0,lengtharray);
}

vocab1 = vocabs[random1];
vocab2 = vocabs[random2];
vocab3 = vocabs[random3];
vocab4 = vocabs[random4];

Serial.println(vocab1);
Serial.println(vocab2);
Serial.println(vocab3);
Serial.println(vocab4);
Serial.println("//");
delay(1000);

german1 = strtok(vocab1,"/");
english1 = strtok(NULL,"/");
Serial.println(german1);
Serial.println(english1);
}

sorry for my english

Personally I would store them as separate words within a struct to pair them up. No splitting required.

Personally I would take a completely different tack. I'd store the word pairs as separate items within a struct:
struct wordpair {
    const char *german;
    const char *english;
};

struct wordpair pairs[] = {
    { "Apfel", "apple" },
    { "er", "he" },
    { "Zoo", "zoo" },
    { "sie", "she" },
    { "Hallo", "hello" },
};

#define NWORDS (sizeof(pairs) / sizeof(pairs[0]))

Now you have instant access to the words.  For example:
pairs[3].german

is "sie", and
pairs[3].english

is "she".
You don't need to waste time splitting words up, since they are already split up.  You don't need to worry about words getting corrupted, because you're never writing anything to the words.  Indeed, if you tried to, because they are tagged as const, the compiler should complain.
So:
struct wordpair *vocab1 = &pairs[random1];

Serial.println(vocab1->german);

The macro NWORDS gives you the size of the array for easy reference.

Make a buffer large enough to hold the largest of the word-pairs. Copy the selected pair into the buffer and run strtok() in that buffer. Strtok will damage the buffer contents but that is a throw-away; the original word-pair string is still unchanged.


text:
L298 module - unusual power specs
I would like to purchase this dual H-bridge module. I plan on connecting it to an Arduino Uno. In the products datasheet the specified power supply (Vd) is 6.5-12V, and the voltage for the motor control pins is 2.3V HIGH and -0.3V LOW.
My question is whether this product is compatible with the standard 5V of Arduino Uno for both the power supply and logic; i.e. can I connect the Vd to the 5V terminal of the Arduino and the control pins to the digital terminals?
If not, what modifications do I need in order to use this H-bridge with an Arduino?
Note: Originally I bought this cheap module and connected the motor control pins to the Arduino, but each output returned a different output voltage!

Yes, it's compatible with the Arduino, but realistically speaking it is not compatible with motors or batteries.  The L298 (L293, etc) is a terribly lossy, antiquated part based on bipolar transistors, and only keeps showing up as module vendors have latched onto intertia from past usage dating from 20 years ago when there were few alternatives.  Get something modern that uses FET's instead.

That's a very poor datasheet. I think it's using equals signs where it means less-or-equal, so:

High level: 2.3V = Vin = Vss

Intends to say that Vin between 2.3 and Vss will be considered high, and

Low:-0.3V = Vin = 1.5V

Intends to say that Vin between -0.3 and 1.5V will be considered low.
"Vss" in the high level definition is confusing, because in the rest of the datasheet, "VD" is used for the logic voltage and "VS" is used for the motor; you'd expect the upper limit to be the logic voltage.
The diagram at the end of the datasheet shows how it can be used with an Arduino. A 7.5V source is going into the Vin pin (instead of the barrel jack, which is unusual). There's a protection diode on the power input which incurs a ~1V voltage drop, so the Arduino Vin pin should be outputting 6.5V, which drives the board. The digital outs from the Arduino, when driven high, are at 5V, well above the 2.3V threshold given on the datasheet.
I'd recommend powering the Arduino through the barrel jack with a 7.5V or 9V supply to drive the logic side of the board. (Powering through the USB port will put 5V or less on the Vin pin.)
You'll want a more robust supply for the motor side, because the Arduino can't deliver very much current.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
how to break out servo.write(angle) after it reach the angle?
I used a servo as a grabber so I don't know the angle I need specifically.I need it to break the serve.write(angle) when the grabber holds something.
I used a simple code
#include <Servo.h>
Servo myservo;
void setup() {
  myservo.attach(9);
}
void loop() {
  myservo.write(100);
  delay(500);
  myservo.write(50);
  delay(500);
}

when it holds anything it deos not return to the small angle until I remove the obstacle from its way.

You change the angle in small increments until the sensor triggers:
bool closing = false;
bool openeing = false;
int angle;

void loop(){

    //read touchSensor

    if(sensorHit){
        closing  = false;
    }
    if(closing){
        if(angle <= minAngle) closing = false;
        angle -= 1;
        myservo.write(angle);

    }

    if(opening){
        if(angle >= maxAngle) opening = false;
        angle += 1;
        myservo.write(angle);

    }

}

The to start moving the grasper you set opening or closing to true. You can also add some trigger logic in the places where they get set back to false for the next movement if applicable.

when I control it manually by joystick, if I hold press a little I can not reverse the angle. I don't use touchSensor.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Setting a default arduino program in NodeMCU
Just after saying farewell to my old broken D1 mini I could not resist myself and bought a brand new nodemcu in the morning. I tried my previous arduino sketches to board and everything works fine, just needed to change the pin setup.
I was wondering is it possible to set a default arduino program to nodemcu? such that every time I turn on my Nodemcu 12-E it runs it as a default program.
Searching the internet I cam across this link. Downloaded the flasher,selected the port to which 12-E is connected and flashed it.
After following all instructions and connecting to AP and 192.168.4.1/edit I tried to setup an arduino code as default code but failed. Is that because original firmware on supports Lua programming language? Is it possible to setup an arduino sketch as a default program? If not is it possible to convert arduino sketch to Lua programming language? as I have zero knowledge of Lua

What do you mean by "default" program to run? The NodeMCU only runs one program, and that is the program that you flashed to it. If you want it to run a different program then flash a different program to it. If you are programming it in Lua then we can't help you. This isn't a Lua site, it's an Arduino site.

@Majenko everytime i upload the code to 12-E using USB cable it works fine but when I detach the cable and plug it again the serial monitor will not show anything besides I have connected three leds they are also in off state

Are you uploading Arduino code or Lua code?

@Majenko Its an arduino code

You are using the Arduino IDE for this programming? With the ESP8266 core installed?

Yes indeed the code is compiling fine without any error  It runs fine for the first time fetches the http scripts after WIFI connection and turns the respective leds on but when I restart it it does nothing.
Actually I am using my older arduino scripts

Then chances are you are causing it to always boot up in programming mode not run mode. Check which pins you're using and stay away from the special ones (0/2/15 IIRC).

@Majenko I checked the nodemcu12E pinout I am using D1,D2,D3 pins the D3 pin also mentions Flash infront of it maybe this the issue I will check it in the morning. What is the purpose of Flash pin by the way D1 never had this one

Why is this tagged arduino-uno? What is Uno's involvement in this?

GPIO D3 on the NodeMCU is the ESP8266's GPIO0, which does put the device in flash mode when pulled low on power-up. Either put a pull-up resistor on that pin, or use a different pin for IO.


text:
Using a button to toggle an LED ON/OFF
I'm fairly new to Arduino and am trying to use a push button to toggle an LED on and off using a momentary press of the button. This code is lifted straight off the tutorial on the Arduino website but is not working for me. It seems to send the LED on a loop - switching between on and off by itself, and pressing the button pauses the cycle.
Any ideas as to why it is doing that?
int buttonPin = 2;         // the number of the input pin
int ledPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup()
{
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);

}

void loop()
{

  reading = digitalRead(buttonPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
if (reading == HIGH  && previous == LOW && millis() - time > debounce) {
  if (state == HIGH)
    state = LOW;
  else
    state = HIGH;
time = millis();
}

else
  if (state == LOW)
    state = LOW;
  else
    state = HIGH;
  digitalWrite(ledPin, state);
 //Serial.println(buttonPin);
  //
 Serial.println(reading);
previous = reading;
}

Please give a link to that tutorial. You have chosen the wrong example sketch, there are a number of problems with it. I like the Bounce2 library: https://github.com/thomasfredericks/Bounce2/wiki That library is in the Arduino IDE in the library manager.

Just cheak your "If …else "logic ,it seems to get a mistake.

pinMode(buttonPin, INPUT);

Do you have an external pull-down resistor?  Without one, the pin is floating when the button isn't pressed so it might read anything and you may be picking up spurious noise.
It is much more common to wire a button so that it connects to ground and reads LOW when pressed.  If you wire it that way, you can use the internal pull-up resistors by using pinMode(pin, INPUT_PULLUP) and you won't need any external resistor for the button.

The problem is in the "else" part. Just remove it and you are ready to go ! Also make sure that in the circuit, the digital read would be low, when not pressing button.

My one line answer
If (isPressed(BTN)) digitalWrite(LED, ~digitalRead(LED));
Is all you need to flip an led when a button is pressed.

The correct code: if(digitalRead(button)) digitalWrite(led, !digitalRead(led));


text:
Arduino Micro Interrupt
I have built a custom Arduino Micro PCB, but I have made a mistake, I accidentally attached an interrupt pin for a Gyro sensor to pin 12 of the Micro, not realizing it wasn't an external interrupt pin.
I tried using the interrupt pin change command found on the Arduino website, but I am having some trouble getting it working. If there is a way to make pin 12 on the Arduino Micro an Interrupt pin, how would I go about doing that in the simplest way.

You can use a pin change interrupt - or you can probably just poll, especially if you do so with knowledge of how often the sensor usually is ready.  To get an actual answer, you'll need to post the code of your attempt and explain the specific problem.

This is the pinmapping: http://www.pighixxx.com/test/portfolio-items/micro/ You mean pin 12 which is PD6 ? There is no PCINT on that pin. For PCINT I prefer the EnableInterrupt library: https://github.com/GreyGnome/EnableInterrupt How old is that gyro sensor ? because today the sensors are accelerometer + gyro + magnetometer in a single chip.

The MPU6050's INT pin is not very mandatory, from what I can read on the various pages. You can try to modify the library you are using so that it does not have to have an interrupt

I can add to @frarugi87 that some code poll the interrupt bit in the sensor. I also advise to use the newer MPU-9250. And if you use the AHRS code by Kris Winer then you don't need an interrupt: https://github.com/kriswiner/MPU9250 Tell us what your project is, perhaps you don't need to sample data at a high speed (100 samples per second is high speed for these sensors). The I2Cdev library has too much overhead anyway, I hope you did not plan to use that library, did you?

I am using a MPU-6050, which is a gyro + accelerometer. I am using it for a drone, so I need a very high refresh rate for the drone to fly. I used to have it not using the interrupt pin, put that data was coming in too slow and too delayed for it to fly correctly. Using the interrupt pin solved that issue.

Then you are in trouble, since you probably need the fifo of the sensor with the interrupt. You can add comment to the answer of @dannyf below how to turn a 'T1' input of a Atmega32u4 into a interrupt.

If there is a way to make pin 12 on the Arduino Micro an Interrupt pin

you should take a look at the device datasheet and see what other functionalities pin 12 has.
if it is a pcint pin, you are golden;
if it is a timer input pin or an input capture pin, they can be programmed to act like an interrupt pin as well.
all begins with reading the datasheet.

this library will let you attach a function to a pin using pin-change-interrupt, api is quite simple
https://github.com/neu-rah/PCINT#api
Arduino pin change interrupt library compatible with AVR and SAM with consistent interface.
Allows handlers to be called with a predefined cargo (void*) for user data or just regular void returning functions with no params.
This library use meta-programing to achieve consistency.
Example
#include <pcint.h>

#define led 13
#define btn 12

void setled() {
  digitalWrite(led,digitalRead(btn));
}

void setup() {
  pinMode(led,OUTPUT);
  pinMode(btn,INPUT_PULLUP);
  PCattachInterrupt<btn>(setled,CHANGE);
  setled();//initial led status
}

void loop() {}

API
Just two methods:
void PCattachInterrupt<pin>(userFunc,mode);
void PCdetachInterrupt<pin>();

Unfortunately I have tried this and it will not compile for the Arduino Micro.

its good to know it doesn't, i might check that.. but i wont bother to post the results, or risk yet another minus.
still i've been using it on Uno and Nano


text:
Wireless Communication with NRF24L01+
I have decided to use NRF24L01+’s for my Arduino project for wireless communication. I am using the RF24 library by TMRh20 to talk back and forth.
Github Link: https://github.com/nRF24/RF24
I want to be able to send and receive data as fast as possible between the remote, and the receiver. After reading through the library I was able to create a some simple code that allowed the remote to transmit ~600 32-byte messages a second and the receiver was able to read ~490 messages a second.
Transmitter Loop Code:
if (radio.available())
  { radio.read( &myData, sizeof(myData) ); }
Receiver Loop Code:
radio.write( &myData, sizeof(myData), 1);
With this code however, the remote control cannot receive telemetry data back from the receiver. It is only a one way communication with no acknowledgments.
I have a few questions about wireless communication with the NRF24L01+. First, what is an acknowledgement? I understand it is a way for the transmitter to know that the receiver got the message, but what is being sent in the acknowledgment?
What is the difference between commands such as radio.write, radio.writefast, radio.startwrite, and radio.startwritefast. The RF24.h file has explnations of these commands but their desrciption does not make too much sense to me.
After doing some research, I found that to write, I must stop listening, write the message, and then start listening again for messages. The issue with this code is that the NRF is never listening long enough to receive a message (unless I add in a delay where it stays in RX mode). Is there anyway to keep a reading pipe open while writing and then pick it up from the FIFO when I am ready to read?
It seems that it is possible to write an ACK Payload, and this allows the NRF to transmit a message without leaving RX mode. Is this a possibility, and what is an ACK Payload?
What is the best practice for achieving the fastest speed two-way communication. Is it common practice to have two NRF’s and have one dedicated to listening and one dedicated to writing on each Arduino? Is there a good way to achieve high speed two-way communication rates with a single NRF?

I’d suggest reading the data sheet for the NRF24. Have a good look at the state diagram in it. The ACK is there to acknowledge that the packet was received, and not lost due to interference or weak signal. You can indeed send some data along with the ACK packet. To increase speed; the NRF has three speeds. Set it to the highest value. Also see which channel works the best, so you have the least number of lost packets. You can’t send and receive at the same time. Write will wait for the message to be send, before returning. WriteStart will not block, so you can run code while it is sending.

I second reading the data sheet.  Be prepared to use SPI commands and write directly into the nRF24L01+ registers.  You can do that in void setup after the rest of your radio setup.

I really reccomend you to read the documentation of the nRF24L01+ from nordicsemi. It describes its capabilities and modes of operation in depth.

firstly, the radio.write command is used for checking for the acknowledgement from the RX after the FIFOs are full for a single write. But radio.writefast will not wait for the acknowledgement from the RX and would continuously transmit the payload for a single write. Similarly for radio.startwrite and
radio.startwritefast commands.
Coming to the keeping the NRF in listening mode, even I haven't tried it before so I cannot suggest an exact solution for this problem. But as far as I know,  you can go for writestart command to keep the reading pipes open while you are sending. But I would personally suggest you to confirm this from datasheet again before experimenting.
For ACK payload, it depends upon the master unit controlling the SPI communication with the NRF chip and thus, by maintaining a mutual understanding between the RX and TX units, you can define the payload for acknowledgement signal as well.
Coming to best speed possibility, To increase speed, NRF has three speeds from which you can select the highest value available. Also see which pipe/channel works the best for you so that you can achieve the least number of lost packets.

Just to add to the conversation, the NRF24L01 radios support Ack-Payloads. That is the receiving radio can place data in the ACK it sends back to acknowledge a received payload. Using this method at 2MBPS, you can achieve a 1MBPs bidirectional communication channel fast enough for audio, remote control and telemetry, etc.


text:
How can I call the constructor of a Class after it called once?
I have a problem with Classes.
I have a bunch of code, that code is uses Adafruit MQTT FONA library. I call the Class for make new Instance and Connect to specified server with this code;
Adafruit_MQTT_FONA mqtt(&fona, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

When I want to connect to another server, I call this Instance's constructor after it called once. But it don't let me to construct it again. How can I construct the same instance again after it constructed once?
void connectMqtt()
{
    Adafruit_MQTT_FONA mqtt(&fona, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
}

connectMqtt();

Thanks for helps! Have a good day!

note:  your question is not about Arduino .... it is a C++ programming question

You can't. Once constructed, an object remains constructed until you delete it.
You could either use dynamic allocation and new and delete to create and destroy objects at will, or you could create multiple objects with different settings and use different objects at different times.
Another option would be to modify the library to create a new function that accepts and assigns new server settings. All the constructor does is store the settings in variables - there's no reason why you couldn't just change those variables.


text:
Arduino Resetting in Automotive Application
I have a complicated problem with my Arduino circuit being reset/crashing, I will try to describe the best I can.
The Setup:
Basically I have a Arduino 328P circuit that is monitoring some temperatures in an automotive environment.  Several one wire temperature sensors connect to the PCB with various distances from 2-10 ft. Each is on a seperate pin.  I have also tried analog LM35 sensors.  The system works outside the car just fine.
The Problem:
When the car is shut off (not the PCB) the Arduino is being reset despite power still being connected.  There is no power spike or loss to the PCB. The car is not actually running, I am just turning the key on and off.
What I have learned:
-When I disconnect the temperature sensors from the PCB, problem goes away.
-It makes no difference if the wires to the sensors are shielded.
-It makes no difference if I use one wire digital or analog sensors.
-It makes no difference if I connect the PCB directly to the battery
-The problem goes away if I run the PCB on a battery not connected to the car. (fully isolated)
-The problem comes back if I ground the PCB to the chassis, but still leave the +12V isolated.
-The chance of a reset changes when the sensors are moved or the length of wire is changed.
-It only resets when the key is turned off, never when turned on.
I tried to explain the best I can without writing a novel.  I think I might need to isolate the ground to my PCB somehow.  The problem is in the ground or the long wires to the sensors.

So you are saying that peak or pulse in the GND level resets the atmega328p. That is not hard to do, I had that with a power supply. Can you show the schematic (with the reset circuit)?

There is no power spike or loss to the PCB. The car is not actually
  running, I am just turning the key on and off.

And did you verify that with a digital scope? I doubt it.
I don't think you understand how ugly the electrical system in a car really is. If there is a coil or relay switched then there will be spikes. Do some research on electronics for use in an automobile.
Automotive relays can have a resistor in parallel with the coil to control the level of the back emf when the relay is turned off. You would think that a reversed diode should be used but a diode causes the coil current to discharge too slow and that causes the contact arcing to be extended. A resistor can be used to speed up the discharge but at the cost of a voltage spike on the electrical system.
An Arduino board is not appropriate. There needs to be a lot more protection.And one wire devices are basically an antenna looking for trouble.
https://www.st.com/content/ccc/resource/technical/document/application_note/1f/d7/fc/6d/2e/27/48/98/CD00181783.pdf/files/CD00181783.pdf/jcr:content/translations/en.CD00181783.pdf
https://electronics.stackexchange.com/a/40425/195251
https://en.wikipedia.org/wiki/Load_dump
https://electronics.stackexchange.com/a/163861/195251

Yes, I checked both 5v and 12v with a scope.  The problem lies in the temperature sensors, when they are disconnected, the problem goes away.  Most of the car has been disconnected, fuel pump, injectors, coils etc there is basically nothing left to interfere.

@user1113986 A battery that can give a lot of amps and wires of some length, that is all that is needed for spikes. If a relay is still in the car and turns on or off then there will be spikes. Can you tell what kind of scope it is? Even with a expensive scope an experienced engineer has still some guessing to do when it comes to spikes.

Snap-on Modis scope.  Interference is on the ground to the temperature sensors.  With the ground disconnected, no problem, but then the system won't work...

What I would try is to use twisted conductors with an external shield. Connect the shield only at the PCB. If possible have the sensor shielded. Use the twisted conductors for the sensor. Do not use the shield for the sensor. If you can't get it to work then you might want to consider a sensor that is measured, then converted to digital, and the digital signal goes to the Arduino and an optocoupler is used to provide electrical isolation.


text:
Connect old USB webcam to USB Host Shield 2.0 Arduino Uno / Mega
Does anybody know how to interface an old USB webcam with the USB Host Shield 2.0 connected to an Arduino (Uno or Mega 2560 or other models - excluding Yun).
I've got the USB Host Shield set up properly and I can run all the examples.
My goal is to make the arduino force the webcam to take a picture (the webcam itself has a button for taking pictures) every second and save it to the SD card of the ethernet shield.
I know how to read and write data to the SD card of the ethernet shield. That's not the problem.
The problem is making the Arduino talk to the USB webcam.
Can anybody please share a basic .ino file with me so I can see what magic they used to do the trick?
I tried the Arduino PTP Camera Control library by felis over at:
https://github.com/felis/Arduino_Camera_Control
But I'm having lots of trouble getting the included examples to work properly with my old USB webcam. I always get the 'can't read data' error in the serial monitor...
Thanks for any help!

This will not be practical.  USB Webcams are not PTP devices - that is for already recorded images.  Don't use an Arduino for this project, use something more like a Raspberry Pi, though preferably without the delicate SD card dependency - possibly even the Linux (not Arduino) side of that Yun you want to avoid, or perhaps a hackable router/NAS box which is what that is a repackaged and repurposed variation of.  Cheapest and simplest of all of course would be to just get a cheap still camera that records to an SD card.

Most simple webcams use USB video device class UVC protocol. Ptp is supported on some webcams but UVC is much more common.

Re-read the first comment: an Arduino is not remotely suitable to this task.

"how to interface an old USB webcam" -  maybe you just need to start looking for actual specifications for this "an old USB webcam", what it is adhered to? Why do you think that some arbitrary "library" is supposed to work with "an old webcam"? Did you try your "an old webcam" under regular Windows or Linux environment? Does it work? What kind of driver does it use?

In case it matters: I'm using an old intel cs330 webcam. This is what it looks like:
https://www.ebay.com/p/Intel-CS330-Web-Cam/66777500
When plugging in this webcam in Ubuntu it is recognized by Cheese so I'm guessing it utilizes either the PTP or the UVC protocol or similar.


text:
Arduino fingerprint verification from server
I am thinking to do a hobby project related to fingerprint verification. The flow which I wanted to implement is something like below:

A user can register a fingerprint using an Arduino device
This fingerprint will be saved on a remote server so that user can be verified on some other Arduino devices
When a user tries to verify, the fingerprint will be matched against the fingerprint stored on the server

For this, I am thinking to use the Go language on the server side as an API server, MySQL/SQLite as a database system. Further, in the future, I will build a mobile application to perform some query with the server like running devices, the number of registered users, revoke users etc.
For now, I am planning to buy the following devices:

Arduino UNO
A wifi shield
A fingerprint sensor
An LCD screen

Now the question is, will the devices mentioned above will work for my setup, or I need to buy something else (Are they compatible?)
Also, is there a way to store the fingerprint on a server? I am thinking to store some kind of hash (probably RSA encrypted) of a fingerprint on a server, will it work?
Any relevant example of storing fingerprint on a server?

This question was closed as being too broad, but I don't agree that it really passes that test.

According to the adafruit driver's code, it is capable of loading and storing fingerprint templates (256byte each) from and to its flash
  uint8_t emptyDatabase(void);
  uint8_t storeModel(uint16_t id);
  uint8_t loadModel(uint16_t id);
  uint8_t getModel(void);

These functions would allow you to sync the local database of each device with a server for example or even download and test for each template individually, which would obviously be pretty slow and only viable, if you had to store more templates than the flash itself can.
You can encrypt this data before transmitting in whatever way you wish but that is a topic on its own.
Other than that your components seem to be compatible.
An idea for syncing:
Every unit should check on a fixed interval of 1 second for instance, whether the online database has changed. This may be represented by a simple counter i.e. version that increments with each change and is copied to local storage after downloading the latest changes.
So whenever an Arduino uploads a new fingerprint model or your mobile app removes a fingerprint, the counter on the server is incremented and every other device knows to update its database in case the local version is lower.
Another tip if changes happen very frequently:
Every flash memory just has so many write cycles before it dies.
If you happen to update the database a lot, you should try to minimize the stress on each fingerprint sensor's memory by assigning an arbitrary, unique id to each fingerprint and storing a local 'map' where you have stored which id on this specific device.
This way you can update only the fingerprint(s) that have actually changed.
Good luck.

Another tip if changes happen very frequently I got some FRAM so that I wouldn't have to worry too much about destroying internal EPROM. Adafruit sells some and when combined with the Extended database library, you can have a pretty strong combo.

I believe fingerprint templates must be stored on the device in order to be comparable. I might be wrong tho

@mystery I am thinking to use TCP socket, so if a device updates the fingerprint on the server, the server will inform every other device to sync fingerprint models to their local one, is this approach fine?

Sure, more complicated than polling but go ahead if it works out


text:
data integrity when interrupts are too fast
I have an encoder that fires ~54000 interruptions per second.
This is way too fast for my arduino uno.
But I'm trying to see what I can get from it anyway. For science.
unsigned long tickACount = 0;
unsigned long tickBCount = 0;

void myInterrupt(){
  tickACount++;
  tickBCount++;
}

Then in my main loop, every second I print tickACount and tickBCount.
I can see my arduino is able to handle only about 2050 interrupts per second. No surprise here.
What surprises me, is that tickACount and tickBCount have different values! tickBCount is consistently higher that tickACount.
Ok now I switch them to volatile. And according to the documentation, volatile only makes sense for 8bit values. The counts will eventually overflow but it doesn't really matter. I just want to see if those two variables are still different.
volatile uint8 tickACount = 0;
volatile uint8 tickBCount = 0;

void myInterrupt(){
  tickACount++;
  tickBCount++;
}

The result is that the two values are still different.
Also, wrapping them into some ATOMIC macro does not help.
From what I read, interrupts cannot be interrupted.
And beside, if my interrupt was aborted midway, then tickACount would be higher than tickBCount, not the other way around.
Therefore, what can be the explanation for those two variables to be different?
Thank you for any idea!

They are the same. But when you print one and then print the other one, there has been interrupts between that. Make a full sketch that shows the problem. With a lot optimizations, the uno board might do more than 54kHz interrupts, perhaps 100kHz. Interrupt tutorial: https://gammon.com.au/interrupts

You can save quite a few CPU cycles by creating your own ISR instead of relying on the one from the Arduino core to call your interrupt handler. See this answer, section Write your own ISR.

If you want simple counter, why don't you use Timer1 or Timer2 with external clock source?

Would you consider using extra hardware to reduce microcontroller load?  How about using shift registers to count pulses.

I was convinced that 54kHz is way to fast for Arduino, which runs at 16MHz. That's only ~300 cycles per interruption + it has to handle the normal loop.
I replaced my interrupts by the Encoder library https://github.com/PaulStoffregen/Encoder, and it now seem to work fine. I digged a bit into that library, it seems to do about the same thing as I did, but in assembly with probably some big optimization done.
Well done, about the tickCountB > tickCountA. The possibility of tickCountB being incremented during the 2 prints hasn't come to my mind. I guess that's experience!

54000 interruptions per second [...] is way too fast for my arduino
  uno

Your test is probably flawed. My Uno does handle that interrupt rate
with no issues. See my test code below.

my arduino is able to handle only about 2050 interrupts per second

You are probably doing something wrong, like blocking interrupts for too
long, or using a library that does so.

What surprises me, is that tickACount and tickBCount have
  different values!

As previously stated in comments, this is not the case. Instead, the
counters have been incremented while you were printing them.

And according to the documentation, volatile only makes sense for 8bit
  values.

Either the documentation is grossly wrong, or (most likely) you have
misread it.

From what I read, interrupts cannot be interrupted.

This is indeed the default behavior. You could change it, by issuing
interrupts() within the interrupt handler, or by declaring an ISR as
ISR(XXX_vect, ISR_NOBLOCK)
{
    ...
}

but that is seldom done.
Below is my test code. I used Timer 2 to generate a square wave on
pin 3, which is both a PWM pin (OC2B) and an interrupt pin (INT1).
The PWM frequency is about 54.054 kHz.
const uint32_t PRINT_PERIOD = 1e6;  // print counts every second

struct TickCounts {
    uint32_t tickA;
    uint32_t tickB;
};

volatile TickCounts rawCounts;

void myInterrupt() {
    rawCounts.tickA++;
    rawCounts.tickB++;
}

// Atomically read both counts.
static TickCounts getCounts() {
    TickCounts counts;
    noInterrupts();
    counts.tickA = rawCounts.tickA;
    counts.tickB = rawCounts.tickB;
    interrupts();
    return counts;
}

void setup() {
    // PWM at 54 kHz on OC2B = PD3 = INT1
    DDRD  |= _BV(PD3);    // pin PD3 as output
    OCR2A  = 37 - 1;      // period = 37 * 0.5 us = 18.5 us
    OCR2B  = 37/2 - 1;    // duty cycle ~ 50%
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // mode 7: fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(WGM22)   // ditto
           | _BV(CS21);   // clock at F_CPU/8 = 2 MHz

    Serial.begin(9600);
    attachInterrupt(1, myInterrupt, RISING);
}

void loop() {
    static uint32_t last_time_printed;
    if (micros() - last_time_printed >= PRINT_PERIOD) {
        last_time_printed += PRINT_PERIOD;
        TickCounts counts = getCounts();
        Serial.print(counts.tickA);
        Serial.print(" ");
        Serial.println(counts.tickB);
    }
}

And here is the output:
54053 54053
108107 108107
162161 162161
216215 216215
270269 270269
324324 324324
378377 378377
432431 432431
486485 486485
540539 540539
...


text:
Running many devices on 5V pin. How to provide external power
I'm using my Arduino DUE 5V pin to power a lot of sensors and I'm worried about the drop in current.
I'm powering the board using the USB port. Is this the correct way or is there a different way of powering the board to make sure the current drop is limited as much as possible?
Thanks in advance.

There is a maximum current you can use from the 5V pin(s), so it is good to split the current going into the Arduino.
You can use a breakout board for a USB, connect the USB to the breakout board, connect it both to the Arduino, and in parallel to the sensors; meaning the current used for the sensors is not going through the Arduino. You might need 2 break out boards, one for the input USB, one for the output USB.
Note there is a maximum current for USB too.


text:
Can I power Raspberry Pi 3 via 3V3 and GND pin?
Can I power my Pi 3 using the 3v3 pin (pin 1) and GND pin (pin 6)? Also, if I want to protect the board from power surges can I just put a fuse between my power supply and the 3v3 pin?
Thanks in advance,

This is not an Arduino question BUT definitely do NOT try this!
The Foundation Hats Master has recommendations.
"It is possible to power the Pi by supplying 5V through the GPIO (sic) header pins 2,4 and GND. The acceptable input voltage range is 5V ±5%. ⋯ Implement a duplicate power safety diode ⋯ supply 5V at a minimum of 1.3A ⋯ Under no circumstances should a power source be connected to the 3.3V pins."

Thank you, I'm sorry I posted it on the wrong stackexchange forum. I didn't know there even existed a raspberry forum.


text:
Serial Commmunication between two arduino
I want to send the voltage magnitude received on an analog pin of atmega328Pu to another arduino uno using Serial communication pins TX and RX and display the value on the receiver arduino's Serial monitor.
Transmitter Arduino Code:
void setup()
{

  Serial.begin(9600);

  pinMode(A0, INPUT);

}

void loop()

{

  int voltage=analogRead(A0);

  Serial.println(voltage);

}

Receiver Arduino Code:
void setup()

{

  Serial.begin(9600);

}
int incomingByte = 0;

void loop()
{
if (Serial.available() > 0) {
    incomingByte = Serial.read();
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
}

}

Problem: Now the Problem I am facing is that Serial Monitor of Receiver arduino does not shows anything, it remains blank. Please analyse this system help me in finding out the best way to get around this problem?

You need to connect GND (0V) between the to. Electricity flows in circles.

Connect the grounds of the two Arduinos together. Their serial transmitters and receivers need the same voltage reference.
pinMode(A0, INPUT); is not needed. pinMode() only affects the digital part of the pin driver. (But it probably isn't doing any harm, either).
The transmitter Arduino will be sending 1, 2, 3, or 4 ASCII bytes - the digits 0-9, representing the D/A result, 0 - 1023. In decimal, those digits will look like 48, 49, ..., 57 (for a '0', '1', ... '9', respectively). So the receiving Arduino will be handling characters, not numbers. It needs to collect all of the characters, then repeat them onto it's terminal output.

Thanks for the Help. It works Now

The problem is that a serial connection usually connects two devices, in your case it's three (sensor arduino, receiving arduino and your pc).
To get around this you have to use an additional software serial on different pins on the receiving arduino (unfortunately the atmega328 has only one hardware serial interface).
As long as you don't have to send anything from pc to the receiving arduino and from the receiving arduino to the sensing one you could try to simply disconnect the wire receiving-TX to sensing-RX and see if it works. In this latter case you could actually get rid of the receiving arduino at all.
Edit: another important point was mentioned in JRobert's answer: grounds of devices communicating with each other must always be connected!

Thank you very much for the help.

If your problem is solved please accept an answer so the question is closed


text:
How to generate gcode for Arduino Mega 2560 and Ramps 1.4 CNC Router
I had a Prusa I3 3D Printer which use Arduino Mega 2560, Ramps 1.4 and Pololu - A4988 Stepper Motor Driver.

I want to convert my 3D printer to CNC Router using my Dremel with Flexible shaft like this.

I found the one project on instructables.com at here
http://www.instructables.com/id/Arduino-Controlled-CNC-3D-Printer
They give config for Mega 2560 as CNC router.
But i don't know how to generate g-code for these cnc router.
Please help me to generate g-code from STL, DXF and Image(PNG or SVG) files to use with this type of cnc router.

Inkscape (free) will generate gcode from an svg using "gcode tools" add-on (also free)

For generating g-code from an SVG, you could try to parse the SVG into a set of relative commands, and using the relative commands to generate G-code. Since you were originally using the frame as a 3d printer and now you want to use this as a CNC machine, you could try to invert the data. But, for generating the code I would go read up on how to parse the various file formats, and read the specs on each of the formats. However, most of the file formats you listed are proprietary, and you won't be able to find an open spec for them.
Of the formats that you listed, it would probably be the easiest to parse the SVG, as it's an open spec, and is a lot like XML.
This is going to be really difficult to actually do, because you're essentially reimplementing a full CNC controller.
I would start with getting 2 dimensional stuff down like drawing shapes and setting routing depth.
Some Resources
Here are some resources that might help you with parsing the various file formats. I only listed the ones that have an open standard.

http://www.w3schools.com/svg/default.asp
This link describes the SVG format, and it does a fairly decent job at it.
http://en.wikipedia.org/wiki/G-code
http://en.wikipedia.org/wiki/STL_%28file_format%29


text:
No serial data from Adafruit GPS (on Arduino 101)
New Adafruit GPS connected to my Arduino 101 board.
When trying to use the RX/TX hardware serial (on digital pins 0 / 1), with a simple sketch (described by Adafruit) to output a serial response, I'm not seing anything in the serial monitor (9600 baud).
// this sketch will allow you to bypass the Atmega chip
// and connect the Ultimate GPS directly to the USB/Serial
// chip converter.

// Connect VIN to +5V
// Connect GND to Ground
// Connect GPS RX (data into GPS) to Digital 0
// Connect GPS TX (data out from GPS) to Digital 1

void setup() {}
void loop() {}

Wires connected as in the sketch, also tried swapping them out in case of faulty wire.
Went on to try TinyGPS++ default example code, across a variety of pins: 3,4 & 8,9 & 0,1.
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample code demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx). EDITED BELOW.
*/

static const int RXPin = 8, TXPin = 9;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

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

  Serial.println(F("FullExample.ino"));
  Serial.println(F("An extensive example of many interesting TinyGPS++ features"));
  Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
  Serial.println(F("Sats HDOP Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum"));
  Serial.println(F("          (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail"));
  Serial.println(F("---------------------------------------------------------------------------------------------------------------------------------------"));
}

void loop()
{
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

  printInt(gps.satellites.value(), gps.satellites.isValid(), 5);
  printInt(gps.hdop.value(), gps.hdop.isValid(), 5);
  printFloat(gps.location.lat(), gps.location.isValid(), 11, 6);
  printFloat(gps.location.lng(), gps.location.isValid(), 12, 6);
  printInt(gps.location.age(), gps.location.isValid(), 5);
  printDateTime(gps.date, gps.time);
  printFloat(gps.altitude.meters(), gps.altitude.isValid(), 7, 2);
  printFloat(gps.course.deg(), gps.course.isValid(), 7, 2);
  printFloat(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
  printStr(gps.course.isValid() ? TinyGPSPlus::cardinal(gps.course.value()) : "*** ", 6);

  unsigned long distanceKmToLondon =
    (unsigned long)TinyGPSPlus::distanceBetween(
      gps.location.lat(),
      gps.location.lng(),
      LONDON_LAT,
      LONDON_LON) / 1000;
  printInt(distanceKmToLondon, gps.location.isValid(), 9);

  double courseToLondon =
    TinyGPSPlus::courseTo(
      gps.location.lat(),
      gps.location.lng(),
      LONDON_LAT,
      LONDON_LON);

  printFloat(courseToLondon, gps.location.isValid(), 7, 2);

  const char *cardinalToLondon = TinyGPSPlus::cardinal(courseToLondon);

  printStr(gps.location.isValid() ? cardinalToLondon : "*** ", 6);

  printInt(gps.charsProcessed(), true, 6);
  printInt(gps.sentencesWithFix(), true, 10);
  printInt(gps.failedChecksum(), true, 9);
  Serial.println();

  smartDelay(1000);

  if (millis() > 5000 && gps.charsProcessed() < 10)
    Serial.println(F("No GPS data received: check wiring"));
}

// This custom version of delay() ensures that the gps object
// is being "fed".
static void smartDelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

static void printFloat(float val, bool valid, int len, int prec)
{
  if (!valid)
  {
    while (len-- > 1)
      Serial.print('*');
    Serial.print(' ');
  }
  else
  {
    Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1); // . and -
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
      Serial.print(' ');
  }
  smartDelay(0);
}

static void printInt(unsigned long val, bool valid, int len)
{
  char sz[32] = "*****************";
  if (valid)
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  smartDelay(0);
}

static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
{
  if (!d.isValid())
  {
    Serial.print(F("********** "));
  }
  else
  {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d ", d.month(), d.day(), d.year());
    Serial.print(sz);
  }

  if (!t.isValid())
  {
    Serial.print(F("******** "));
  }
  else
  {
    char sz[32];
    sprintf(sz, "%02d:%02d:%02d ", t.hour(), t.minute(), t.second());
    Serial.print(sz);
  }

  printInt(d.age(), d.isValid(), 5);
  smartDelay(0);
}

static void printStr(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
  smartDelay(0);
}

Serial is spitting out this for every update:

No GPS data received: check wiring

GPS is on, and can see based on the fix LED that satellite fix has occurred in both tests – no difference in output. Wires checked.
Maybe suboptimal pin solder job, but can't see that it should give no signal?

EDIT: After suggestions, re-soldered pinheader – still nothing in the serial prompt on hardware serial (pin 0,1), software serial (pin 3,4) and TinyGPS++ throws the same error (pin 3-4 + 8-9). Double-checked RX/TX order.
A colleague found an old Ublox Neo 6-M GPS, I plugged it in and repeated the above with the same empty serial results, not sure what to make of this..

@depwl9992 I agree the TX pin may need a bit more solder.  You can also use the serial monitor in the Arduino IDE to look for the raw data output (without writing or modifying any code).  This way you can tell if the problem is with the code or the wiring... its easy to get TX/RX swapped and I've done it before!

Accidentally fixed it when booting up the board tonight – not sure what changed but the serial prompt is on fire.
Wires: 5V - VIN, GND – GND, TX – 8, RX – 9
Code:
#include <SoftwareSerial.h>

// setup gps serial
int gpsTxPin = 8;
int gpsRxPin = 9;
SoftwareSerial gpsSerial(gpsTxPin, gpsRxPin);

void setup()
{
  Serial.begin(9600);  //set monitor to 9600

  gpsSerial.begin(9600); //adjust for GPS unit

  Serial.println("Ready!");
}

void loop()
{
  while(gpsSerial.available())
  {
    char c = gpsSerial.read();
    Serial.print(c);
  }
}

Excerpt from serial monitor:
...

$GPVTG,248.75,T,,M,0.19,N,0.35,K,A*3F
$GPGGA,231351.000,,,,,0,05,,,M,,M,,*7A
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSV,2,1,07,13,65,290,32,30,54,066,36,20,48,286,33,15,31,288,31*75

...


text:
Trying to flash ESP8266 with Arduino UNO
This is my first project other than some of the starter projects. I am trying to flash the firmware onto an ESP8266 wifi module using and arduino uno. It would be nice to know if anything is wrong/redundant in the picture below (I was looking at a few different diagrams to try and figure out what was right). I have found some tutorials saying that TX should go to RX instead of TX to TX so that is what I am doing. I am trying to use the level shifter to go from 5v to 3.3v because I wasn't sure if I had enough current going to the ESP8266 when just directly hooked up to 3.3v on arduino (I read in a few places that the arduino doesn't have a strong enough current to operate the wifi module). I found some tutorials which use a voltage regulator, I tried doing that but had the same results I am getting now. I have also read that you don't need a level shifter or voltage regulator but it might harm the components so I haven't tried that way yet.
I am the point where I plug it into my computer via USB, open the Arduino IDE > Tools > Serial Monitor.
I type the command 'AT' and there is no response - I tried every baud setting. Sometimes it randomly outputs a question mark or two.
Other things of note: When I plug it in, the ESP8266 blue light flashes once. When I was modding the header pins of the ESP8266 I kind of fumbled it a lot - could that have broken some aspect of the chip? Also while modding the header pins, I pushed them all in to make them longer and bent them on the other side, so it would work with the breadboard - I'm wondering if the soldering connections need to be stronger (you can kind of see in the picture).

This is the schematic for what I was trying to achieve basically, while also using the level shifter:

Any advice with regards to anything you see here would be great, I am new to the world of circuits.
Note: there is a ground wire that is not in the frame of the picture connecting one side of the breadboard to the other, that part of this is one thing I was wondering about.

Ohhh... That solder! That is NOT ok!

You do not need the level shifter. The input pins of the ESP8266 contain over-voltage (though not over-current) protection. All you need to do is limit the current that can flow through the over-voltage protection circuit, and all that needs is a series resistor in the region of 100Ω or so.
And the Arduino already has that protection between the ATMega16U2 and the TX/RX pins anyway in the form of 100Ω resistors that it uses to prevent short circuits between the two MCUs on the board, so you don't need to add it in this instance (you do if you want to communicate between the ATMega328P and the ESP8266, but only between the Arduino's TX and the ESP8266's RX pins).
When it comes to actively running the ESP8266 it can be beneficial to power it from a more powerful 3.3V regulator than the 150mA one on the Arduino since when transmitting the ESP8266 wants more than that, but for simple flashing of it the Arduino's 150mA regulator should do the job fine.
One thing to note though: I don't like the look of the soldering on your ESP8266 pins. I would be inclined to re-solder those joints. Add a bit of flux to help the solder flow properly.

Thanks @Majenko, I'm gonna solder those joints. from your comments at the bottom: I don't have a regulator on hand and I was wondering if I could use the equation here https://learn.sparkfun.com/tutorials/voltage-dividers to use as sort of a rough regulator...would that be unsafe...I guess i'll solder and then try again just to make sure it wasnt a connection

Definitely not. https://hackingmajenkoblog.wordpress.com/2016/08/30/why-you-cant-use-resistors-as-a-voltage-regulator/

great that explained it, communication not power, thanks for link.

but I can still try with 3.3v on arduino as power source, u said that should be enough for flashing

would my level shifter help for 5v to 3.3v?

Not for power, no. Logic signals only.

What I have done was connecting ESP8266 and UNO as the schematic described.
But instead of using the default program in ESP8266, I programmed ESP8266 via UNO using the ESP8266 Library on Arduino IDE
If your way still did not work you can maybe try this method.


text:
'DynamicJsonBuffer' was not declared in this scope
I have this code:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "xxxx";
const char* password = "xxxx";

bool a = false;
bool b = true;
int heldVal = 0;

WiFiServer server(80);

void setup () {

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

  pinMode(2, INPUT);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

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

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

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

      HTTPClient http;  //Declare an object of class HTTPClient

      int readVal;
      if (!a) {
        if(b) {
          readVal = digitalRead(2);
        }
      }
      else {
        a = false;
        readVal = heldVal;
      }

      if (readVal == 0)
        http.begin("http://192.168.1.100/gpio/0");  //Specify request destination
      else
        http.begin("http://192.168.1.100/gpio/1");

      int httpCode = http.GET();                                                                  //Send the request

      if (httpCode > 0) { //Check the returning code

        String payload = http.getString();   //Get the request response payload
        Serial.println(payload);                     //Print the response payload

      }

      http.end();   //Close connection
      return;
    }

    // Wait until the client sends some data
    Serial.println("new client");
    while (!client.available()) {
      delay(1);
    }

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

    // Match the request
    bool toWrite = true;
    if (req.indexOf("/gpio/0") != -1) {
      heldVal = 0;
      b = false;
    }
    else if (req.indexOf("/gpio/1") != -1) {
      heldVal = 1;
      b = true;
    }
    else if (req.indexOf("/mode") != -1) {
      toWrite = false;

      client.flush();

      Serial.println(String(heldVal));
      Serial.println("---in mode request---");

      String input = "{\"mode\":"+String(heldVal)+"}";
      DynamicJsonBuffer jsonBuffer; //----- PROBLEM LINE -----//
      JsonObject& root = jsonBuffer.parseObject(input);

      // Generate the JSON string
      root.printTo(Serial);

      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: application/json");
      client.println("Connection: close");
      client.println();
      root.printTo(client);
      delay(1);
    }
    else {
      Serial.println("invalid request");
      client.stop();
      return;
    }

    // Set GPIO2 according to the request
    if(toWrite) {
      a = true;

      client.flush();

      // Prepare the response
      String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
      s += (heldVal) ? "high" : "low";
      s += "</html>\n";

      // Send the response to the client
      client.print(s);
      delay(1);
      Serial.println("Client disonnected");

      // The client will actually be disconnected
      // when the function returns and 'client' object is detroyed
    }
  }
  else {
    ESP.restart();
  }

  delay(30000);    //Send a request every 30 seconds

}

I put a comment, //----- PROBLEM LINE -----//, next to the problem line  above. The error is:
/Users/eamonwhite/Documents/Arduino/tempcontrolesp/tempcontrolesp.ino: In function 'void loop()':
tempcontrolesp:110: error: 'DynamicJsonBuffer' was not declared in this scope
       DynamicJsonBuffer jsonBuffer;
       ^
tempcontrolesp:110: error: expected ';' before 'jsonBuffer'
       DynamicJsonBuffer jsonBuffer;
                         ^
tempcontrolesp:111: error: 'JsonObject' was not declared in this scope
       JsonObject& root = jsonBuffer.parseObject(input);
       ^
tempcontrolesp:111: error: 'root' was not declared in this scope
       JsonObject& root = jsonBuffer.parseObject(input);
                   ^
tempcontrolesp:111: error: 'jsonBuffer' was not declared in this scope
       JsonObject& root = jsonBuffer.parseObject(input);
                          ^
exit status 1
'DynamicJsonBuffer' was not declared in this scope

I put it just inside the loop function and it is still giving the same error:
void loop() {
  DynamicJsonBuffer jsonBuffer; //still throws error

How is it not being used correctly? Its just a declaration...

Did you forget to include the ArduinoJSON header file:
#include <ArduinoJson.h>


text:
SoftwareSerial interfers with TVout
I'm using an Arduino uno and a Nodemcu for making a game with the phone as a WiFi controller.
The Nodemcu is the server that receives inputs from the phone connected via WiFi and sends to the Arduino a signal via SoftwareSerial.
The Arduino reads the signal and then decides what to do and sends output to TV.
It works good but every time the nodemcu sends something, the TV signal gets distorted.
note: the code for the game is not completed
code for Nodemcu:
#include<SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid = "SpaceInvaders";
const char* password = "12345678";

IPAddress local_ip(192,168,1,1);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
SoftwareSerial SUART(4, 5); //SRX=Dpin-D2; STX-DPin-D1
ESP8266WebServer server(80);

void setup() {
  SUART.begin(115200);
  Serial.begin(115200);
  WiFi.softAP(ssid, password);
  WiFi.softAPConfig(local_ip, gateway, subnet);
  server.on("/", handle_OnConnect);
  server.on("/0", nope);
  server.on("/1", left);
  server.on("/2", right);
  server.on("/3", left_right);
  server.on("/4", shoot);
  server.on("/5", left_shoot);
  server.on("/6", right_shoot);
  server.on("/7", left_right_shoot);
  server.onNotFound(handle_NotFound);

  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}

void handle_OnConnect() {}

void nope()             {SUART.print(0); server.send(200, "text/html", " "); Serial.println(0);}
void left()             {SUART.print(1); server.send(200, "text/html", " "); Serial.println(1);}
void right()            {SUART.print(2); server.send(200, "text/html", " "); Serial.println(2);}
void left_right()       {SUART.print(3); server.send(200, "text/html", " "); Serial.println(3);}
void shoot()            {SUART.print(4); server.send(200, "text/html", " "); Serial.println(4);}
void left_shoot()       {SUART.print(5); server.send(200, "text/html", " "); Serial.println(5);}
void right_shoot()      {SUART.print(6); server.send(200, "text/html", " "); Serial.println(6);}
void left_right_shoot() {SUART.print(7); server.send(200, "text/html", " "); Serial.println(7);}

void handle_NotFound(){
  server.send(404, "text/plain", "Error: not found");
}

code for arduino (note: seems that stackexcange identifies this function as spam so i posted them here ):
#include<SoftwareSerial.h>
#include <TVout.h>
#include <fontALL.h>
SoftwareSerial SUART(2, 3); //SRX=Dpin-2; STX-DPin-3
TVout TV;
//#define debug 1
#define numberOfEnemies 15
#define maxEnemyMovement 20
#define playerDefaultY 75

int points = 0;
unsigned long int millisLastEnemyMovement = 0;
int enemyMovementDelay = 850;
int enemyMovement = 0;
bool directionIsRight = true;

struct b {
  int x;
  int y;
  bool shootable;
} bullet;

struct p {
  int x;
} player;

typedef struct {
  int x;
  int y;
  bool alive;
} Enemy;

Enemy enemyList[numberOfEnemies];

void renderEnemy(int x, int y){ //draws sprite of enemy

}

void renderPlayer(int x, int y){  //draws player sprite

}

void shoot(){
  if(bullet.shootable){
    bullet.shootable = false;
    bullet.x = player.x;
    bullet.y = 100;
  }
}

void left(){
  if(player.x > 0){
    player.x--;
  }
}

void right(){
  if(player.x < 105){
    player.x++;
  }
}

void spriteUpdate(){
  if(!bullet.shootable){
    bullet.x--;
    if(bullet.x < 0){
      bullet.x = 0;
      bullet.y = 0;
      bullet.shootable = true;
    }
    for(int i = 0; i < numberOfEnemies; i++){
      if(bullet.x > enemyList[i].x && bullet.x < enemyList[i].x + 11 && bullet.y > enemyList[i].y && bullet.y < enemyList[i].y + 8){
        bullet.shootable = true;
        enemyList[i].alive = false;
        points++;
      }
    }
  }
  if(millis() - millisLastEnemyMovement > enemyMovementDelay){
    millisLastEnemyMovement = millis();
    if(directionIsRight){
      enemyMovement++;
      for(int i = 0; i < numberOfEnemies; i++){
        enemyList[i].x++;
      }
    }else{
      enemyMovement--;
      for(int i = 0; i < numberOfEnemies; i++){
        enemyList[i].x--;
      }
    }
    if(enemyMovement == 0 || enemyMovement == maxEnemyMovement){
      directionIsRight = !directionIsRight;
    }
  }
}

void render(){
  TV.delay_frame(1);
  TV.clear_screen();
  renderPlayer(player.x, playerDefaultY);
  for(int i = 0; i < numberOfEnemies; i++){
    if(enemyList[i].alive){
      renderEnemy(enemyList[i].x, enemyList[i].y);
    }
  }

}
void setup()
{
  char x;
  Serial.begin(115200); //enable Serial Monitor
  SUART.begin(115200); //enable SUART Port
  bullet.x = 0;
  bullet.y = 0;
  bullet.shootable = true;
  for(int i = 0; i < 5; i++){
    enemyList[i] = {4+i*20, 3, true};
    enemyList[i+5] = {4+i*20, 18, true};
    enemyList[i+10] = {4+i*20, 33, true};
  }
  player.x = 50;
  TV.begin(PAL, 120, 96);
  while(true){

  }
}

void loop(){
    if (SUART.available() != 0){
      x = SUART.read();  //read char
      switch(x){
        case 'a':
          left();
          break;
        case 'b':
          right();
          break;
        case 'c':
          //left and right same time?
          break;
        case 'd':
          shoot();
          break;
        case 'e':
          left();
          shoot();
          break;
        case 'f':
          right();
          shoot();
          break;
        case 'g':
          //left and right at same time?
          shoot();
          break;
      }
    }
    spriteUpdate();
    render();
}

This is the schematic:

what is your question?

Software Serial is a pretty crummy library.  It disables interrupts while receiving for long periods of time.  That causes any other library that uses interrupts to have issues with timing.  There are a plethora of other soft serial libraries out there.  Try one of those instead.  AltSoftSerial comes to mind.

Both AltSoftwareSerial and TVout require pin 9 so i can't use them at the same time.

OK, like I said there are a large number of them.  They aren't hidden.  A quick google search should turn up several alternatives for software serial, each with it's own caveats and abilities.

It works good but every time the nodemcu sends something, the TV signal gets distorted.

That's correct. SoftwareSerial is terrible. Don't use it. When it's sending or receiving data nothing else at all can happen.
If you have to resort to SoftwareSerial then you are using the wrong hardware for your project. Maybe an ESP32 would be a better choice.

Basically you have two software hacks. Both require precise timing and neither is happy if that timing is messed with. To that end both will disable interrupts to stop things interfering. You can use one or the other, but not both.


text:
PROGMEM for IR command storage
I'm working on a code that is able to send raw data as IR signal to IR transmitter,
the memory of arduino Nano is not enough to store the array in SRAM storage,so i'm about to use PROGMEM to store arrays in flash memory.
these are arrays for IR signal raw command:
unsigned int irSignaloff[]={6060, 7420, 532, 1652, 544, 1668, 508, 1688, 508, 1688, 508, 1692, 532, 1664, 532, 1664, 532, 1664, 536, 604, 528, 588, 548, 580, 552, 580, 528, 636, 500, 600, 532, 588, 548, 580, 552, 1644, 552, 1644, 528, 1664, 532, 1668, 532, 1664, 532, 1668, 528, 1668, 528, 1668, 508, 624, 536, 600, 532, 600, 536, 576, 528, 600, 532, 604, 532, 604, 532, 580, 552, 1648, 548, 1648, 552, 1644, 552, 1648, 552, 1644, 552, 1640, 556, 1644, 528, 1668, 528, 600, 508, 624, 512, 620, 536, 600, 536, 604, 528, 576, 508, 624, 532, 604, 532, 1660, 536, 1660, 540, 596, 536, 1644, 552, 1648, 552, 1644, 552, 580, 524, 1672, 524, 604, 508, 624, 536, 1660, 536, 632, 504, 580, 552, 608, 500, 1668, 528, 600, 508, 1688, 512, 1684, 560, 1668, 504, 660, 500, 1660, 536, 604, 532, 1656, 540, 1660, 540, 584, 548, 580, 528, 596, 512, 1688, 508, 660, 500, 1660, 536, 596, 540, 584, 548, 604, 500, 1672, 528, 600, 512, 1684, 512, 620, 540, 1656, 540, 600, 536, 580, 552, 1644, 552, 576, 528, 1668, 532, 600, 508, 1688, 536, 596, 536, 1660, 540, 1660, 536, 7420, 536};

unsigned int irSignalon[]={6156, 7336, 592, 1588, 612, 1584, 612, 1588, 608, 1588, 608, 1588, 604, 1592, 604, 1592, 604, 1592, 604, 528, 504, 628, 588, 548, 588, 552, 580, 524, 608, 524, 572, 560, 592, 540, 588, 1608, 592, 1604, 592, 1604, 592, 1608, 592, 1604, 592, 1604, 592, 1604, 596, 1600, 596, 524, 608, 520, 584, 544, 596, 540, 596, 536, 596, 524, 608, 520, 604, 524, 588, 1608, 588, 1608, 588, 1608, 588, 1608, 588, 1612, 536, 1660, 572, 1624, 572, 1628, 564, 600, 504, 628, 504, 580, 528, 600, 636, 528, 540, 564, 532, 588, 548, 604, 504, 1664, 532, 604, 504, 624, 536, 1660, 532, 1664, 532, 1664, 532, 604, 532, 1660, 536, 584, 548, 1652, 548, 1644, 552, 580, 556, 572, 532, 604, 532, 1664, 532, 600, 532, 1668, 532, 1660, 536, 1688, 532, 600, 536, 1664, 532, 584, 620, 1576, 552, 1644, 552, 576, 532, 604, 608, 524, 532, 1664, 608, 512, 620, 1576, 548, 580, 556, 572, 600, 536, 604, 1588, 608, 528, 536, 1660, 536, 584, 620, 1580, 620, 508, 596, 532, 508, 1688, 512, 620, 536, 1660, 604, 532, 608, 1588, 604, 516, 620, 1576, 620, 1576, 624, 7308, 552};

and this is sending command uses IRemote.h library:
 irSend.sendRaw(irSignalon, sizeon, FREQ_KHZ, false);

so how can i use PROGMEM to store and read this int array in order to send them?
thanks

Unless the IR library supports reading from PROGMEM you can't use PROGMEM.

You are using 788 bytes there. Yes, that's a lot for a Nano, but way below the limit. Maybe you should be pruning your other RAM usage which must total more than just these two arrays if you are running out of memory.

Understanding/decoding the IR signals and not using the raw timings would be also more space efficient.

do not use raw .... convert the time intervals to actual data ... the first line is unsigned int irSignaloff[]={start, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, end} ..... that is same as hexadecimal 00ff 00ff 00ff 22dd 14eb ab54

what is the make and model of the device that you are controlling?

the device is an Air Conditioner and signal is not decodable with usual libraries because it contains dynamic info about temperature,mode,etc.

you did not answer my question ... what is the manufacturer name?

If your IR library does not support sending signals stored in PROGMEM,
then you will have to provide the data in RAM. However, you do not have
to keep both signals in RAM permanently: only the one you are about to
send needs to be there.
I suggest you keep all the IR signal data in PROGMEM while not sending
them. Whenever you want to send a signal, you copy it to a RAM-based
buffer and give the address of that buffer to the library. The same
buffer will be reused for any signal you are sending. This will cost
you some CPU time for the copy, and save 394 bytes of RAM. The savings
will scale up if you add more signals to your sketch.
const size_t signal_size = 197;

static PROGMEM const uint16_t irSignaloff[signal_size] = { ... };

static PROGMEM const uint16_t irSignalon[signal_size] = { ... };

/* Send an IR signal from PROGMEM. */
void send_signal(const uint16_t *signal) {
    static uint16_t signal_buffer[signal_size];
    memcpy_P(signal_buffer, signal, signal_size * sizeof *signal);
    irSend.sendRaw(signal_buffer, signal_size, FREQ_KHZ, false);
}

//...
send_signal(irSignalon);
send_signal(irSignaloff);

Here I am assuming that all your signals have the same length, which is
true for the example you show, but may be false if you add more signals
later. You may then need to size the buffer as the longest of all your
signals, and provide the signal length as an extra parameter to
send_signal().
Note that the RAM buffer does not need to be static. I chose to make it
static here only in order for avr-size to give you a good estimate of
the memory requirement of the program.

thank you so much, i just added the size of array as input of send_signal function to cover multiple commands and worked fine.
void send_signal(const uint16_t *signal,const size_t size) {
unsigned int signal_buffer[size];
memcpy_P(signal_buffer, signal, size * sizeof *signal);
irsend.sendRaw(signal_buffer, size, khz);
}


text:
Calculate sensor unique address with a 8 position DIP Switch
I have a large amount of sensor boards that I need to be able to configure setting unique addresses. Each sensor is attached to it's own arduino, I'm using a 8 position DIP switch for setting the address.
I have tried diferent approaches. When I switch On and OFF I get random values. I understood that I would be able to get up to 255 possible positions, but without being able to get the proper byte data I would have to manually code each possibility, which seems wrong.
Schematic :

Code
#include "DipSwitchI2C.h"

DipSwitchI2C::DipSwitchI2C(int address)
{
    _address = address;
}

void DipSwitchI2C::begin()
{
    Wire.begin();
}

int DipSwitchI2C::read()
{
    unsigned int address = 0;
    unsigned int value = 0;

    Wire.requestFrom(_address, 1);
    if (Wire.available())
    {
        value = Wire.read();
    }
    Wire.endTransmission();

    for (int i = 0; i < 8; i++)
    {
        address += (value & (1<<i)) > 0;
    }

    return address;
}

A 8 position DIP switch can have 256 positions. And you are just calculating the sum of bits.

First of all, you must be sure that the _address has the right i2c address of the pcf8574, then you can do a Wire.requestFrom(_address,1) and a return(Wire.read()). That's all, two lines, nothing else.

it is unclear what this means .... without being able to get the proper byte data

since you have only one sensor board on any given Arduino, why do you need a unique address on the sensor board?

determine what is the value of  Wire.read() at this line value = Wire.read(); .... you may be surprised

@jsotola I have network of sensors connected by rs485. I need to be able to ask the sensor reading for every arduino from a master

As @jsotola noted the solution was simple:
int DipSwitchI2C::read()
{
    unsigned int address = 1;

    Wire.requestFrom(_address, 1);
    if (Wire.available())
    {
        address = Wire.read();
    }
    Wire.endTransmission();

    return address;
 }

Assuming that your switches are on pins 2-9 on an UNO.  Change pins to match what you actually have.
byte addressVal = 0;
for(int i = 2: i<10; i++){
    addressVal <<= 1;
    addressVal += digitalRead(i);
}

This will check each switch and add a 1 to the end of the byte.  On each iteration it shifts the contents of that byte 1 place to the left.  After it reads all the pins you have a byte with a value 0 to 255 depending on the states of the pins.

The switches are connected to the arduino by a PCF8574 multiplexer not directly to the pins.

Well then replace the digitalRead command with whatever command you use to read a pin from the multiplexer.