How to program thresholds? Hello guys (and gals)!

I'm trying to figure out how to program thresholds using my arduino board.

Essentially, to make this as simple as possible, this is what I have going on.

I am sampling a value every one second, I am taking the value and trying to make certain actions occur based on when this value crosses certain thresholds.

The value read every second will be a value between 0-150.

The thresholds will work something like this:

If value crosses over 20 and becomes 20 or higher, do an action.

If value crosses over 20 and becomes 19.9 or less, do a different action.

And then do the same for a threshold at 30, 40, 50, and 65.

I would need to have it so that if it reads a value of 15, and then a second later, reads a value of 23, it does an action. But if it reads 23, and then reads 24 a next, it needs to not do anything because it hasn't crossed over from one threshold to another. I only want an action to perform if a threshold is crossed either by increasing or decreasing past it.

So again, to reiterate;

If first value read is 34, and second is 42, do an action.

If first value is read at 57, and second at 44, do an action.

If first value is 24, and second value is 26, do nothing. (no threshold was crossed)

The next part would be figured out if a threshold was crossed twice, or more, to do that action twice or more times.

Any advice on how to code this?

Thanks in advance.

Thanks again for your contributions.

I've gone ahead and decided to go with the following code. Its purpose is to turn vol up or down based on current car MPH. I choose to define brackets that cover a range of values. When one bracket ends, another begins. I've also set the previous bracket to current bracket at the end of each loop so that the application knows where it was previously, so that if it hops above or goes under a defined bracket, it does the desired action.

I've used a random generator to supply the MPH for testing purposes for now and commented out a few things that disturbed the testing process. If you'd like to critique this code to make is better, please let me know.

Note: I've also borrowed some of this code from another individual (Matthew McMillan, http://matthewcmcmillan.blogspot.com) who wanted to figure out how to convert a vehicle speed sensor wire info into MPH. I needed this code in order to make use of the vehicle's speed.

#include <SPI.h>
#include <Wire.h>

const int lightPin = 0;
const int hardwareCounterPin = 5;
const int samplePeriod = 1000; //in milliseconds
const float pulsesPerMile = 4000; // this is pulses per mile for Toyota. Other cars are different.
const float convertMph = pulsesPerMile/3600;
unsigned int count;
float mph;
unsigned int imph;
int roundedMph;
int previousMph;
int prevCount;

// Declare brackets
const int BracketA = 1;
const int BracketB = 2;
const int BracketC = 3;
const int BracketD = 4;
const int BracketE = 5;
const int BracketF = 6;

// Initialize Previous and Current Brackets
int PreviousBracket = 1;
int CurrentBracket = 1;

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

  TCCR1A = 0; //Configure hardware counter
  TCNT1 = 0;  // Reset hardware counter to zero
}

void loop() {

  /////////////////////////////////////////////////////////////
  // This uses the hardware pulse counter on the Arduino.
  // Currently it collects samples for one second.
  //
  bitSet(TCCR1B, CS12); // start counting pulses
  bitSet(TCCR1B, CS11); // Clock on rising edge
  delay(samplePeriod); // Allow pulse counter to collect for samplePeriod
  TCCR1B = 0; // stop counting
  count = TCNT1; // Store the hardware counter in a variable
  TCNT1 = 0;     // Reset hardware counter to zero
  mph = (count/convertMph)*10; // Convert pulse count into mph.
  imph = (unsigned int) mph; // Cast to integer. 10x allows retaining 10th of mph resolution.

  int x = imph / 10;
  int y = imph % 10;

  // Round to whole mile per hour
  //if(y >= 5){
  //  roundedMph = x + 1;
  //}else{
  //  roundedMph = x;
 // }

  //Code to write your own MPH for testing purposes.
  //if (Serial.available() > 0) {
                // read the incoming byte:
               // roundedMph = Serial.read();
               //}

  //If mph is less than 1mph just show 0mph.
  //Readings of 0.9mph or lower are some what erratic and can
  //occasionally be triggered by electrical noise.
  //if(x == 0){
  //  roundedMph = 0;
 // }

  roundedMph = random(1,80);

  // Don't display mph readings that are more than 50 mph higher than the
  // previous reading because it is probably a spurious reading.
  // Accelerating 50mph in one second is rocketship fast so it is probably
  // not real.
  if((roundedMph - previousMph) > 50){
    roundedMph = previousMph;
  }

  //Place the gatherered MPH value into a bracket
  //---------------------------------------------
  if(roundedMph >= 0 && roundedMph < 20) {
   CurrentBracket = BracketA;  //Value1
   Serial.println("I Choose Bracket A");
    }

  if(roundedMph >= 20 && roundedMph < 30) {
   CurrentBracket = BracketB;  //Value2
   Serial.println("I Choose Bracket B");
    }

  if(roundedMph >= 30 && roundedMph < 40) {
   CurrentBracket = BracketC;  //Value3
   Serial.println("I Choose Bracket C");
    }

  if(roundedMph >= 40 && roundedMph < 50) {
   CurrentBracket = BracketD;  //Value4
   Serial.println("I Choose Bracket D");
    }

  if(roundedMph >= 50 && roundedMph < 65) {
   CurrentBracket = BracketE;  //Value5
   Serial.println("I Choose Bracket E");
    }

  if(roundedMph >= 65) {
   CurrentBracket = BracketF;  //Value6
   Serial.println("I Choose Bracket F");
    }

 //Decide if bracket stayed the same, went up, or down.
 //---------------------------------------------------
 if(CurrentBracket == PreviousBracket) {
 //Do Nothing
 Serial.println("Nothing Changed");
 }

if(CurrentBracket > PreviousBracket) {
 //Command for Vol Up
 int VolUp;
 VolUp = CurrentBracket - PreviousBracket;
Serial.println("Volume Went Up One by ");
Serial.println(VolUp);
delay(2000); // Delay to not change Vol to fast if near threshold
}

if(CurrentBracket < PreviousBracket) {
  //Command for Vol Down
  int VolDown;
  VolDown = PreviousBracket - CurrentBracket;
 Serial.println("Volume Went Down One by ");
 Serial.println(VolDown);
 delay(2000); // Delay to not change Vol to fast if near threshold
 }
  previousMph = roundedMph; // Set previousMph for use in next loop.
  PreviousBracket = CurrentBracket; //Set PreviousBracket for use in next loop.
}


Which motors to choose? I don't know if this is the right place to ask, but I'm an arduino newbie and I'm seeking some suggestions.
For my Robotics subject at University, I'm going to build a robot that should be able to move some objects (dragging them on the ground, not lifting them) from one place to another. I was looking around the web for the necessary components when I stumbled on a doubt: are 3-6V motors powerful enough for the wheels? Or do I need something more powerful like the 12V motors?
I'm not sure of what to choose between step motors or servo motors either, what do you suggest?
Oh and last thing, I opted for a L293D bridge driver for the motors, is this a good idea?

Thanks in advance!

A 12 volt DC motor is good for dragging items, but then again it depends on the items weight. Stepper is used for millimeter precision, like 3D printing. Servo is an DC motor with precision for 180 degree movement, like robot arms. If the moving object is over 1kg you should look into geared DC motors or even the stronger brushed motors, or geared brushed motors. Whats the max weight?


How do I connect this string of LEDs to my Arduino Uno? I'm an electronics noob. I have this string of LEDs but don't know how to connect them to my Arduino Uno. As they are wired in parallel, there are two wires / four ends. What do I plug where?

Connect the negative ( or cathode ) to ground ( 0V )
and the postive ( anode ) to the output pin of the controller.

Firstly connecting that many LEDS directly to a single micro pin is not a good idea. Usually you would need to go through a buffer/driver first which can deliver the correct power to the LEDS.

I'm not that familiar with the UNO but unless that board has a driver circuit on it you might need a few extra components.

What are the specs of the LEDS?


Are there any pressure sensor for 22 kg (~50lbs) and more? I'm looking for pressure sensors up to 22 kg and more. So far the highest capacity I could found was 25 lbs. Do higher ones not exist?

Your problem may be that you are using sub-optimal search terms.
The kilogram is not a unit of pressure, but instead of mass.
Scales technically do not sense mass, but instead sense force.
This is assumed to be the force exerted by a resting body under earth gravity.
Pressure is force over an area, such as pounds-per-square-inch (PSI) or the Pascal which is a newton per square meter.

Anyway, the sensor you want is called a force cell.
The nice ones are rated in newtons or kilonewtons, with a kg being equivalent to
9.8 newtons.

Here is a load cell that take up to 50 kg.
http://www.phidgets.com/products.php?product_id=3135

Sources:
http://en.wikipedia.org/wiki/Force


Max current of Vin and 5V pin on Arduino Nano What is the max current of the Arduino Nano's Vin (30) and 5V (27) pins?

It's hard to say. The maximum the on-board regulator can provide is 800mA. However the actual amount it can provide at any time depends on other external factors - most notably:

The voltage of your supply
The ambient temperature around the board
The thermal mass of the copper the tab is soldered to

The higher your input voltage the more excess voltage has to be converted to heat. When it gets too hot it overheats and (theoretically) shuts down.

Also the board itself will take some of the maximum 800mA quota, say 50mA (guestimate), so that leaves 750mA theoretical maximum for the 5V pin - but only when powered from not much more than 6.2V (5V + 1.2V regulator dropout voltage).

However, if you are powering from the USB port then it is limited to whatever the USB port can provide (100mA for a passive hub, 500mA for a normal USB port, 2A for a CDP).

The VIN current will be the same as the 5V pin current + the board current.


Firmware update for remote situations We are currently deploying units with the ATMEGA328 chip. Currently, all ICs have been flashed using the Arduino IDE. Upon release, we would like to offer updating of firmware in some cases, but obviously we would not want to send them the source code and let them download the arduino IDE.

We would like to send a firmware file, and an .exe file like a firmware upgrader, as most companies do. How would I start to go about this?

Send them avrdude (including the config file) and the hex file. Look at the commands the IDE runs to see the right command format. You can then put that into a batch file if you like.


How to not wait for USB to become active? EDIT: My original question was a bit "off" since the Arduino Nano I was using appeared to be faulty. This edited question is based on my other Arduino Nano which is working.

When I plug my Arduino into the PC, it keeps blinking it's LED until I open the Serial Monitor.

After opening the serial monitor the Arduino will start to execute my code.

How can I get my Arduino to "not wait on a connection", or simply put, start whenever it receives power.

I believe it's the bootloader which somehow doesn't time-out (I'm not sure if that's how the bootloader works).

The code below (though I don't see why this would make it hang until a connection):

void setup() {
  // put your setup code here, to run once:
  Serial.begin(256000);
  Serial.write("Restart");
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0) {
    incomingByte = Serial.read();

    // say what you got:
    startSend();
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
    stopSend();
  }else{
    startSend();
    Serial.println("I'm still standing");
    stopSend();
    delay(400);
  }
}

(Code is only for testing purposes)

After you post your code this answer may not apply.  But, guessing, you may benefit from changing your code from:

loop()
{
 data = Serial.read();
 // Do other sutff
}

To something like this:

loop()
{
 if(Serial.available() > 1)
 {
  data = Serial.read();
 }
 // Do other stuff
}


Multiple I2C slave devices on Arduino - Pull-up values This question is asked a lot and I've found many usable details on different forums regarding adding pull-up resistors on SDA/SCL lines. I know that only one resistor should be added on these lines regardless of how many devices are attached.

One thing that is not clear for me is that what if I2C devices are powered on from different sources, at different timing?
In following schematic, I have used pull up resistors for both I2C devices. Considering devices might be turned on and off at different timing, or even one device might be absent, is it fine to remove the second pull up resistors (second I2C device) and connect them directly to SDA/SCL pins on uC? In this case (removing pull-up resistors from second device), what happens if device 1 is not available and only second device is connected?

---edit:

Schematic was updated to include only one pair of pull up resistors connected to master side.
I will not how swap or hot plug I2C devices.
I2C devices are sensors (BME280 here, and Chirp capacitive soil moisture, here), not on breakout boards with preset pull up resistors.
Is it possible to just connect resistors on master side and not slave side? In this case, would it be fine for both sensors?

simulate this circuit – Schematic created using CircuitLab

You should consider adding some bus isolation between each slave and the master. The reason being is that the ESD diodes in the SCL/SDA pins of a slave that is powered down could be interfering with the I2C bus as they leech power from the bus to feed through the internals of the slave.  Given the low current imposed by the pullup resistors being the only power source this shouldn't cause any damage to the slave, but it may well cause the I2C bus to be seen as LOW when it shouldn't, causing communication to fail.

You should add a buffer with an "enable" pin of its own between each slave and the bus.  My device of choice is the PCA9306 from Texas Instruments.  It also means that the slave has its own separate pullup resistors powered by its own 3.3V rail, keeping all the power separate.

You would then have sequences such as:

Power up slave
Give short powerup delay (if needed)
Enable PCA9306
Do I2C transactions
Disable PCA9306
Power off slave

The PCA9306 can also be used to connect 3.3V slaves to a 5V MCU if needed.

simulate this circuit – Schematic created using CircuitLab


LCD Shield and Arduino I am trying to use a load cell (https://www.sparkfun.com/products/13331?_ga=1.55586472.2060096590.1479826091) and an HX711 chip with an arduino and LCD shield to display weight values on the LCD shield  when weight is added to the load cell. Does anyone know how I can connect all of these together?

Mainly, how do I connect the HX711 to the arduino while the LCD shield is already on the arduino?

Any help is welcomed , thanks.

Here is the LCD shield I am using I am using:

LCD Shield- https://www.dfrobot.com/index.php?route=product/product&product_id=51

Arduino- not sure which type of arduino to use.

Note: While looking at specifications can infer compatibility, there is no substitute for prototyping.  It is always better to try something then ask for suggestions if it does not work as expected.

That said, I would suggest to look at the LCD you specified.  The LCD's physical shape appears to lock you into a legacy Arduino Uno layout.

On the LCD's web page is a list of pins used.

On the HX711 sparkfun.com web page is a diagram of pins used when using their HX711 software.

Check if there are any conflicts.  Even if there are none, it does not mean there will be no conflicts within the software you will need to run the LCD and the HX711.  You will have to either find someone who has successfully done exactly what you want to do or examine all the software involved your self.  Of course you could simply prototype the project to see if it works.


Properly escaping very large strings On an esp8266 I want to create a little webserver that shows me a dashboard with charts and stuff. For this I wanna include the echarts-library as it works offline. To access it the only way I can see this working is that I write `
const char libData[784674] PROGMEM = "the entire 700 KB library goes here";

And then deliver it on request with server.on('./echarts.min.js', handleLibRequest) or something like that.
Now my problem is that in this 700KB of text there are ' and " characters all scattered arround. The C++11 way of R("hard escapable '"'''" string") isn't working in my environment. How would one go about this to include this file in my code?
Is there mybe some way utilize the preprocessor for this? Or maybe an online tool that converts "str" to ['s','t','r']?

You could write a simple program that escapes all the offending characters and use the output of that in your const char libData[]; see here for a list of escape sequences;
You could serve the library directly from a (pseudo) file system on the ESP8266, without having to copy it "manually" into a variable; you just copy the file to the filesystem;
You could Base64-encode the library and manually copy the result into const char libData[], then Base64-decode before sending;
What I like to do, if there is no file system but enough memory:

Gzip the library;
Base64-encode the .gz file;
Copy the Base-64 encoded result by hand into your const char libData[].

Despite the Base64 encoding, the gzipping makes the end result smaller than the original, which helps with memory usage and transfer speed, and it will have no "quote problems".
When the libData needs to be served, Base64-decode it, and send the resulting (gzipped) data to the client; all browsers I know will accept that if you add the Content-Encoding: gzip header.
Example code on a raw client without a webserver library: unsigned int sendBase64Page() (mind the content type).


Using Arduino and XBee at the same time I have 2 Arduino Unos, 2 XBees and 2 Wireless Proto Shields. The first setup has a humidity/temperature sensor (SHT21P) and it writes data to serial and it works (I've tested it).

Now, the other Arduino with shield and XBee is plugged in my PC to get data from the sensor. So here's the problem: as far as I understand, I can't use XBee and Arduino at the same time, because USB and Arduino both use TX/RX pins to communicate to PC/XBee. I've tested both of the XBees when they are powered with DC jack and they both work. So can anyone confirm that it's true that they're not made for being used by PC and Arduino at the same time? If so, how can I get the data to my computer?

If I understand correctly your goal is to receive data on your computer from an arduino connected with xbee? You could use a USB > Xbee board similar to Sparkfun's Xbee USB explorer board. I am not familiar with the shield that you are using, but some xbee shields allow you to select the pins that the xbee is connected to. It sounds like yours is defaulting to Pin 0 and Pin 1, hardware serial on the Uno. If you can switch it to Pin 2 and Pin 3 (or any two digital pins) you could use software serial with the xbee, leaving hardware serial free for your USB connection.


How do I find names of components I don't know? I recently started with Arduino and I have my starter kit. However, there are some strange looking components I can't recognize. Is there some way to find out the names of these components?

The Arduino webpage has a section about their Starter Kits, including pictures (and technical specs if you scroll down the page). Particularly, if you go to the Arduino store, there is a sub-menu for components - for example, for actuators (there are more categories to the left of the image).

There is a blog by Aaron Eiche, Arduino Starter Rundown, that if you scroll down, there is a chart that labels the main components.

There are several websites that have pages that identify components by image - an example is the uCHobby webpage Identifying Electronic Components, with pictorial menus of the main types of components.

In Google images, searching "arduino starter kit components" yields a considerable amount of labelled component charts.


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

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

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

#include <AFMotor.h>

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

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

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

int i;

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

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

https://imgur.com/a/lzXDQmO

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

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


Make one Arduino fire interrupt on another Problem

I have an Arduino Duemilanove which needs to communicate with an Ardiuno Mega.  The only pin available on the Duemilanove is D13.  The Duemilanove is in charge of driving state on my robot, and the Mega is in charge of sensor readings and navigation.  The Mega needs to send drive state updates to the Duemilanove.  I2C, PWM, Serial, anything requiring different pins on the Duemilanove is out of the question at this point.

Idea
I plan to have the Duemilanove send the "pipe" pin high, triggering an interrupt on the Mega.  The ISR will send the current drive state to the Duemilanove which will change pinmode and read a digital pulse.  The length of the pulse is the drive state.

Roadblock
I am having trouble finding an example of how to set this up.  I can't get the ISR to fire, and I'm not sure why.

Mega Code

int pipe = 18;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(pipe, INPUT);
  attachInterrupt(digitalPinToInterrupt(pipe), driveStateISR, CHANGE);
}

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

}

void driveStateISR(){

  Serial.println("ISR fired");
  pinMode(pipe, OUTPUT);

  digitalWrite(pipe, HIGH);
  delay(50);
  digitalWrite(pipe, LOW);

  Serial.println("Pulse sent!");

  pinMode(pipe, INPUT);

}

Duemilanove Code

int pipe = 13;

void setup() {
  // put your setup code here, to run once:
  pinMode(pipe, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(pipe, HIGH);
  delay(30);
  pinMode(pipe, INPUT);

  unsigned long duration = pulseIn(pipe, HIGH);

  Serial.println(duration);

  delay(3000);
}

Nothing happens at all.  I'm thinking the main framework is here, but since there aren't many examples of this out there I'd love to get some other eyes on the issue.  Thanks!

You should not do delay() or Serial.print() inside an ISR. That would cause it to hang. For more information see my page about interrupts and also How do interrupts work on the Arduino Uno and similar boards?


How can I make my Arduino code work? I am trying to make an automatic lock which stays open during different times and on different days. I want the door open Monday through Friday 8am to 5pm. On Saturdays and Sundays I want the door locked. I will be using an electric lock strike the + wire to pin 9 and - to ground on arduino. I am using an LED for development purposes for now because I don't have the lock yet. The code I have now works (stays open) for 8am to 5pm through the whole week but i want the door locked for Saturdays and Sundays. This is my code so far:

#include <Time.h>
#define doorPin 9
void setup() {
  // put your setup code here, to run once:
  pinMode(doorPin, OUTPUT); // Connected to relay to activate the door lock
  setTime(10,1,1,6,7,2014);
}

void loop() {
if (hour()>=8 && hour()<=17){
  digitalWrite(doorPin, HIGH);
}
else if (weekday()==1 || weekday()==7){
  digitalWrite(doorPin, LOW);
}

This is what's happening: it's still between 8 AM and 5 PM on the weekend, so it unlocks it. Since you use an else if, it terminates the if statement and never checks the day between 8 and 5. I'm almost positive that if you checked it another time in the day, it'd be "locked."

Fixed code:

#include <Time.h>
#define doorPin 9
void setup() {
  // put your setup code here, to run once:
  pinMode(doorPin, OUTPUT); // Connected to relay to activate the door lock
  setTime(10,1,1,6,7,2014);
}

void loop() {
if ((hour()>=8 && hour()<=17) && !(weekday()==1 || weekday()==7)){
  digitalWrite(doorPin, HIGH);
}
else {
  digitalWrite(doorPin, LOW);
}

Note: ! means "not." Thus, the door is locked only if it's not a weekend and it's between 8 and 5.

Additionally, you might want to get a lock that is the other way around: unlocked only with power applied so someone can't unplug the Arduino to get access. EDIT: miscommunication, ignore this part paragraph...


Can I connect a camera to an arduino mini? I was wondering if it was possible to connect a camera like this onto an Arduino mini and have the Arduino save video and audio to a micro SD card.

Not really (at least, not with any appreciable quality). Basically, the bandwidth involved is simply too much for the Arduino's relatively slow 16MHz core speed. You might be able to periodically capture greyscale lowres frames, but capturing the full 1280x960 resolution at any decent framerate is basically impossible.

If you want to find Arduino projects that involve capturing video like this, the search term is arduino composite video input. There are many projects out there that interface the Arduino with a composite input, but none that I know of that can capture full video. Consider the following: your Arduino runs at 16 MHz. If you were to handle 640x480 greyscale video (1 byte per pixel), that would be a data bandwidth (disregarding signal bandwidth) of 640*480*30 = 9216000 bytes/second. That's a pretty tall order: even if you could process each pixel in two (single cycle) instructions with no overhead, you still wouldn't have enough processor bandwidth.

If all you want to do is record composite video to an SD card, there are far easier options out there, search composite video recorder sd.


Arduino direction sensor I am working on a school project for next week
And I need my Arduino to 'sense' at which direction it is moved is it possible? Are there any direction sensors that 'sense' at which direction the Arduino is moving?

As Juraj wrote, you need an MPU, which is a module, that consists of an 3-dimensional accelerometer and a 3-dimensional gyroscope. With the first you can sense acceleration in each of the 3 dimensions (up-down, left-right, forwards-backwards), with the seconds you can sense rotation around these three directions. Sometimes (depending on the module) there is also an magnetometer included, which can be used as a compass.

Note, that you cannot sense the actual speed of a device directly, without using some external reference. With an accelerometer you have to do some maths on the data to get the speed (basically integrating). But since you just want to sense the direction, without bothering about the exact speed, you don't have to think about this.

How exactly you have to program this is out of scope for this side, since it is a rather big topic. Also it depends on the module and library you use. The link, that was provided by Juraj, is a good starting point for reading about this. There are also some further links, for example to a library for controlling the MPU-6050 (if you have one of these) at this github site.

Basically you will have to regularly measure the acceleration in all three dimensions with the MPU. If for an axis the acceleration gets greater than a threshold value, you can count this as direction. To get a more precise direction (not only directly along the axis) you will have to combine the values of the dimensions as a vector. How this is to be solved depends greatly on what you want to achieve.


Load cell weight distribution on rectangular shape instead of square I have built a simple scale using 4 so called 50kg load cells.

They are connected in a bridge and mounted on wooden feet of a square shaped box. All as a proof of concept which worked quite ok. The readings are all OK and deviation of +/- 2kg is totally acceptable for my project. I followed this discussion which also explains how the connection should be made properly using 4 cells.
How to get weight data from glass electronic bathroom scale sensors?
Now I want to keep the load cells on the feet but change the shape of the scale and instead of a square use a rectangle with the following sides.

In such a form a weight distribution will not be centered all the time. The object to be weighed can shift to the right or to the left.

Will this affect the measurements in a negative way or will the HX711 controller still take care of it and show the correct results?
Will the measurements still be correct using 4 cells? If not what would be the proper way of weighing a rectangular shaped load?
Would it more appropriate to measure the load with 2 cells on the right and two cells on the left and then sum it up?

Newton's second law says that if a force acts on a mass, that mass will accelerate at a rate proportional to the force and inversely proportional to the mass.
All that means for your scale is that if you are not being accelerated up or down, the net vertical force on your body must be 0. Since your body has weight, and the net vertical force on your body is 0 (you aren't accelerating, are you? :) then the downward force must be balanced by an exactly equal upward force. That upward force is the sum of the upward forces exerted by each load cell. Their contributions may individually change depending on where you stand, but their sum must exactly equal your weight.
Note that we have said nothing about the placement of the cells! If your platform allows it, you could move one of the cells 6 (or 60 or 600) feet away from the the others, for instance. The total upward force must still be the same.
So the bottom line is:
F_lc1 + F_lc2 + F_lc3 + F_lc4 == your weight
no matter where you place the cells.


Register writing by compound assignment and pointer in Arduino due I'm confused with register wrting method by compound assignment and/or pointer because I don't know where are some of the values come from.
Example 1
REG_PMC_PCER1 |= PMC_PCER1_PID36;  // Enable PWM - Peripheral Identifiers 36

This works the same as REG_PMC_PCER1 = (1<<4)
REG_PMC_PCER1 is not readable, so |= operator shouldn't work.
What is PMC_PCER1_PID36 ? Is the some sort of bit mask defined in the IDE ?

Example 2
PMC->PMC_PCER0 |= PMC_PCER0_PID13;   // PWM controller power ON

This works the same as REG_PMC_PCER0 = (1<<13)
This is similar to Example 1 but there is pointer PMC. Why it's needed ? If PMC_PCER0_PID13 is a bit mask then REG_PMC_PCER0 need not indexing.

So my questions are:

Why compound assignment works on write-only registers ?
Where are those constants (PMC_PCER1_PID36,PMC,etc.) defined ?

Thanks in advance !

Why compound assignment works on write-only registers ?

Probably out of force of habit more than anything.  People are used to having to set bits in registers where the other bits can be read and they want them to stay the same, in which case |= makes sense.
I'd considered that |= might be generating a more efficient instruction, but at least with your REG_PMC_PCER1 |= PMC_PCER1_PID36 example objdump indicates that this is not the case.

Where are those constants (PMC_PCER1_PID36,PMC,etc.) defined ?

Code-wise, they're defined in the ATMEL's (now Microchip's) CMSIS files.  These are header files whose existence is somewhat standardized by ARM for these ARM Cortex processors.  Much of their content isn't however.  E.g., you may see a few things related Cortex M3 that are the same between this ATMEL device in an STM32 counterpart, but GPIO registers may be completely different.
My broadly, they're defined by ATMEL in their datasheets.


How do I download a sketch to an Arduino semi-permanently? I will be working with Arduino(s), and I would like to find a way to download the sketches to the board semi permanently, in a way that I can remove the USB from the board, apply power, and still have the Arduino execute the code

I am planning to use Mega2960, Uno, and Nano. If there are any differences between the uploading process,
please let me know.

P.S., I am using boards produced by Elegoo, not by Arduino, if that makes a difference.

Download the Arduino software (IDE, or Integrated Development Environment).

In our case, we only need to download and run Windows Installer and follow the pop up instructions.  When asked if you want to install the Arduino driver, just press Yes.

Connect your Arduino Nano board to your computer.

In this step, Windows should automatically find the proper Arduino driver and install it, and your Nano board should be ready to use.  If not, please refer to the above mentioned instruction for details on installing the drivers.  Some compatible Nano boards such as DCCduino manufactured by a Chinese company use different USB-to-Serial chips so they require to install different drivers, but the installation should be quite straight forward once you have downloaded the proper drivers from internet.

Launch the Arduino application.
Open the blink example.

Open the LED blink example sketch: File > Examples > 01.Basics > Blink.

For those who are not familiar with Arduino sketch, a sketch is simply a program with various instructions telling Arduino board what to do.

Select your board.

You’ll need to select what type of Arduino board you are using.  In our case, simply select Tools > Board > Arduino Nano w/Atmega328.

Select your serial port

You also need to select the serial device of the Arduino board: Tools > Serial Port.  Usually the port number will be COM3 or higher (COM1 and COM2 are usually reserved for hardware serial ports). To find out, you can disconnect your Arduino board and re-open the menu; the entry that disappears should be the Arduino board. Reconnect the board and select that serial port.

Upload the program to Nano board

Now, simply click the “Upload” button in the environment. Wait a few seconds – you should see the RX and TX leds on the board flashing. If the upload is successful, the message “Done uploading.” will appear in the status bar.

A few seconds after the upload finishes, you should see the pin 13 (L) LED on the board start to blink (in orange). If it does, congratulations! You’ve gotten Arduino up-and-running.

Disconnect from your computer and connect to a power supply to see the blinking light.


ESP8266-01 connected to Arduino Mega - Current output? I was thinking of powering my arduino with an external 9 V power source, but I am still trying to figure out the best way to get the right amount of current for the Wi-Fi module. Should I use an external power supply for the ESP8266-01 module that can output about 500mA or amplify the output from the arduino pins using a transistor?

If there is an easier way to do this I am all ears. I will be using Arduino Mega, not uno as shown in the picture.

EDIT: Voltage divider will be used on the RX pin and I might go for a logic level converter instead of the voltage regulator

Should I use an external power supply for the ESP8266-01 module that can output about 500mA or amplify the output from the arduino pins using a transistor?

Either way you're going to need a power supply that can supply the current. A transistor doesn't magically create more current, it merely allows a small current to control the flow of a larger current.

So you will need an external power source that can provide enough current.

  I might go for a logic level converter instead of the voltage regulator.

Incorrect. A logic leven converter cannot provide anywhere near enough current to power a device. It can barely provide enough to light an LED.

You are right to want to ditch the voltage regulator though.

As it stands you have a chain of regulators, each one wasting power. At 500mA that's lots of power.

9V -> [REG] -> 5V -> [REG] -> 3.3V

That's 4V dropped in the first regulator at ~500mA, and 1.7V dropped in the second regulator at ~500mA. Since P=VI, 4×0.5 = 2W, and 1.7×0.5 = 0.85W. Since you are providing 9×0.5 = 4.5W of power from the battery, you have 1-((2+0.85)÷4.5) = 0.366, or 36% efficiency. That's about two thirds of your battery power wasted just in heat.

Instead you want to use a switching voltage regulator. These are far more efficient and convert voltage into current rather than voltage into heat. This means that you draw less current from your battery, meaning you can use a battery with a higher internal resistance.

Ideally you would use two - one to convert the 9V into 5V to power the Arduino, and another to convert the 9V directly into 3.3V to power the ESP8266. That would be the most efficient arrangement.

There are plenty of breadboard friendly modules on eBay that can do that, or other small modules you can wire in to your circuit without a breadboard (I myself sell one on eBay that I designed).


ESP8266 failure to connect to router I'm trying to get a ESP8266 board with 2x4 pins to work. I'm connecting it to an Olimexino 32u4 (Leonardo-compatible), configured to use 3.3V. This simple snippet I use to transfer everything to the PC (CH_PD is connected to D8, /RST to D9):

void setup() {
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  delay(2000);
  // initialize both serial ports:
  Serial.begin(9600);
  Serial1.begin(115200);
  delay(10000);
  digitalWrite(9, HIGH);
  digitalWrite(8, HIGH);
}

void loop() {
  // read from port 1, send to port 0:
  if (Serial1.available()) {
    int inByte = Serial1.read();
    Serial.write(inByte);
  }

  // read from port 0, send to port 1:
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial1.write(inByte);
  }
}

When launching, I see following output:

<"random" bytes>
Ai-Thinker Technology Co. Ltd.

invalid

Performing a reset shows more:

AT+RST

OK

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 1396, room 16
tail 4
chksum 0x89
load 0x3ffe8000, len 776, room 4
tail 4
chksum 0xe8
load 0x3ffe8308, len 540, room 4
tail 8
chksum 0xc0
csum 0xc0

2nd boot version : 1.4(b1)
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

ŒÂÕ�MEM CHECK FAIL!!!
äsl�‚rô
Ai-Thinker Technology Co. Ltd.

invalid

The mode is set to station:

AT+CWMODE?

+CWMODE:1

OK

Listing the access points works fine:

AT+CWLAP

+CWLAP:(3,"ap-1",-91,"01:23:45:67:89:ab",1)
+CWLAP:(3,"ap-2",-88,"cd:ef:01:23:45:67",2)
+CWLAP:(3,"ap-3",-74,"89:ab:cd:ef:01:23",11)

OK

But logging in to my Fritzbox router fails (WPA2):

AT+CWJAP="ap-2","mypassword"
WIFI CONNECTED
+CWJAP:1

FAIL
WIFI DISCONNECT

First I thought the reason is the low signal, but even moving directly beside the Fritzbox shows the same result (though with higher signal value in AT+CWLAP).

I've tried nearly everything, e.g. AT+CWMODE=3, AT+RST, AT+RESTORE). Nothing changes. When using a wrong password, I'm getting no "WIFI CONNECTED" messages at all.

Could it be a power problem (that the Olimexino can't provide up to 200mA at the 3.3V line?

Connecting from my smartphone to the ESP8266 in one of its access point modes (2 or 3) works fine. If there were power problems, wouldn't then the access point mode fails as well?

In my case when I try to connect to my router, I get the following output:
AT+CWJAP="myssid","mypassword"
WIFI CONNECTED
+CWJAP:1

FAIL
WIFI DISCONNECT

The reason is that the ESP8266 I have is setup with DHCP disabled by default. To enable it you can try the following:
AT+CWDHCP=1,1

If that works, you will get this message:
OK
WIFI GOT IP


Including keypad library removes sound from my piezo element I am using the keypad library to include keypad and input numbers. when a specific number is entered a sound must be made.
However when I input using the serial monitor , sound is working. But when I include keypad , it only inputs numbers but not sound.
Help please , how can I make both work?
Thanks.

#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {12, 11, 10, 9}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8,7,6,5}; //connect to the column pinouts

Then I get the input from keypad and store as result

char guess = 'n';
 char keypressed = keypad.getKey();
  if (keypressed != NO_KEY) {
    char guess = keypressed;

in void loop, it get result(key from keypad) and must play it: Tried separate sketch it works. but with keypad only input is , not sound.

Serial.print("You guessed:");
      Serial.println(guess);
      result = checkYourself(guess);
      Serial.println(result);
      playSound(result);

check yourself takes in guess from keypad ,checks then returns as result.
play sound function works when tried in another sketch( sorry not posting too much code its very long)

I was able to solve it , piezo dissent work in pin 9 but works when connected to pin 13.


ATMega328P-PU not working I bought some material on the net to start working with Arduino. I didn't want to buy an Arduino, since it costs a bit too much IMHO, so I bought an ATMega328P-PU, and made an Arduino on a breadboard. However, when I use my USBasp to program it it says that he can't set sck period (settings are: Arduino Uno as Board, USBasp as Programmer). It says that it has loaded the bootloader/program anyway, so I tried to go on and ignore it. The blink program can be loaded via programmer, but it doesn't blink (I'm using a small lamp, connecting it directly to 5V and ground works). Here I describe the circuit:

First Atmega Pin, Arduino Reset -> 10 kOhm Resistor (Brown, Black, Black, Red, Brown) -> Ground (not GND pin);
1st pin, Arduino Reset -> also to USBasp RST;
7th pin, Arduino VCC -> directly to 5V (and USBasp VCC);
8th, GND -> directly to Ground (and USBasp GND);
9th, XTAL -> to one pin of the 16MHz Crystal Oscillator, and to 22 pF capacitor, which connects to ground (not the pin);
10th, XTAL -> exactly as above, but it's connected to the other pin of the same crystal;
17th, digital 11 -> USBasp MOSI;
18th, dig 12 -> USBasp MISO;
19th, dig 13 -> USBasp SCK, and to the lamp whose other pin goes to ground (neither pin nor direct works), but the lamp needs to be disconnected while loading programs to prevent errors (target not responding);
20th, AVCC, and 21st, AREF -> directly to 5V;
22nd -> directly to ground (not pin).

First Atmega Pin, Arduino Reset -> 10 kOhm Resistor (Brown, Black, Black, Red, Brown) -> Ground (not GND pin);

So it's permanently in RESET mode then? How can it ever do anything if you're holding it in RESET all the time?

RESET should be pulled UP by the resistor, not DOWN.


What's Wrong with this DHT22? I made a circuit that takes humidity and temperature from DHT22 sensor and displays it on Lcd Screen. Simple enough but i get this error "Failed to read from DHT". That happens because i have this code

 if (isnan(t) || isnan(h)) {
  delay(100);
    Serial.println("Failed to read from DHT");
  } else {
    delay(100);
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C");
    //lcd.print("Temp: ") ;
    //lcd.print(t);
    //lcd.setCursor(0, 1);
    //lcd.print("Hum: ") ;
    //lcd.print(h);
  }

So the values are NaN . But 1 minute before it worked fine, and now again it doesnt. Everything is soldered the right way and nothing is false. Lcd is wired ok and it works but i dont get values from DHT22.

Here are some pics to help you out.

In the third Image we see its working. And now its not!
is the DHT sensor broken?

  #include "DHT.h"
#include <LiquidCrystal.h>`

#define DHTPIN 2
#define DHTTYPE DHT22   // DHT 22  (AM2302)

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHT22 test!");
  lcd.begin(16, 2)
  dht.begin();
}

void loop() {

  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(t) || isnan(h)) {
    Serial.println("Failed to read from DHT");
  } else {

    lcd.print("Hum: ");
    lcd.print(h);
    lcd.setCursor(0, 1);

    lcd.print("Temp: ");
    lcd.print(t);

  }
}

Thats my code by the way

Two things:

You need to put a delay in between your read requests. Currently you're reading way too fast, every few milliseconds you're hitting the DHT. Max interval should be every two seconds or so.
Add a 10k resistor between pin 1 and 2 of the DHT.

I'd bet adding a delay, or using the simpleTimer library to control how frequently you read from the DHT will clear this up.


Touch Sensor - Determining Pressing/Hold Length and Modifying Program Flow Accordingly The code below is used for controlling a relay with an Arduino. Pressing the touch sensor connects and disconnects the relay.

If the user presses/touches/holds their finger on the touch sensor for longer than two seconds, how do I adjust the program to do something other than connecting or disconnecting the relay?

#define TouchSensor 9 // Pin for capactitive touch sensor

int relay = 2;

boolean currentState = LOW;
boolean lastState = LOW;
boolean RelayState = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(relay, OUTPUT);
  pinMode(TouchSensor, INPUT);
}

void loop() {
  currentState = digitalRead(TouchSensor);
    if (currentState == HIGH && lastState == LOW){
    Serial.println("pressed");
    delay(1);

    if (RelayState == HIGH){
      digitalWrite(relay, LOW);
      RelayState = LOW;
    } else {
      digitalWrite(relay, HIGH);
      RelayState = HIGH;
    }
  }
  lastState = currentState;
}

You have to determine, how long a the sensor was pressed until released. When it is released you can take the corresponding steps. If the press was shorter than say 1.5s, you can switch the relay. Else you can do something else.

There are many ways to achieve this. You can program it yourself by using the millis() function. You would have to set a timestamp, when the state of the sensor changes to high, then wait for it to go low and substract the timestamp from the current value of millis(). This would give you the duration of press, which you can use in a corresponding if-statement.

Or you can use the Debounce library for it, which makes it a bit simpler (not a lot, but you should consider debouncing depending on the type of sensor you use). Look at the answer from VE7JRO to this question. The debouncer.update() function checks, if the state of the button changed. If so and the value was LOW (in your case this would has to be changed to HIGH), a timestamp is set with the value of millis(). When an update with LOW occurs, the time difference between the two events is calculated and the corresponding action are taken. I will add the code from the answer for reference here:

// Connect one end of a N.O. push button switch to GND and the other
// end to pin 4 of the Arduino.
// NOTE: If the button is held down for less than the debounce delay
//       time, the elapsed time will display the debounce delay time.
#include <Debounce.h>
const byte SWITCH = 4;
unsigned long startTime = 0;
unsigned long endTime = 0;
unsigned long elapsedTime = 0;
const byte debounceDelayTime = 50;

Debounce debouncer = Debounce(debounceDelayTime, SWITCH);

void setup(){
  Serial.begin(9600);
  pinMode(SWITCH, INPUT_PULLUP);
}

void loop(){
  if(debouncer.update()){
    if(debouncer.read() == 0){
      startTime = millis();
      Serial.println("Button Pressed");
    }
    else if(debouncer.read() == 1){
      endTime = millis();
      Serial.println("Button Released");
      elapsedTime = endTime - startTime;
      Serial.print("Button Held Down For ");
      Serial.print(elapsedTime);
      Serial.println(" ms.");
    }
  }
}


How to get read user input from DAQ for a given time interval? I'm using a built-in DAQ simulator. When it opens, it shows 3 different LEDs with 3 pushbuttons,  one corresponding to each LED.

I'm trying to read the user input from 3 pushbuttons for a time interval of 5 seconds. However when I use digitalRead() (from <DAQ.lib>) it only reads input at that instant in time, not continuously for the entire time interval.

As well, I can't figure out how to get the program to wait for entire button press - right now it only reacts when the button is pushed down, but it should react after the button is pushed down then released.

It sounds like you are trying to register when a push button has been pressed for 5 seconds. In other words, you want your flag to turn on after the button has been held for at least 5 seconds, and then turn off once the user releases the button.

I would suggest looking at the example programs to do with button debounce. In particular, the debounce example/tutorial from the Arduino website.

My version of the program would look like this:

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int buttonOutput;            // the current reading from the input pin
int lastReading = LOW;       // the previous reading from the input pin

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 5000;  // the debounce time; 5000ms = 5 seconds

void setup() {
    pinMode(buttonPin, INPUT);
    pinMode(ledPin, OUTPUT);

    // set initial LED state
    digitalWrite(ledPin, LOW);
}

void loop() {
    // read the state of the switch into a local variable:
    int reading = digitalRead(buttonPin);

    // check to see if you just pressed the button
    // (i.e. the input went from LOW to HIGH), and you've waited long enough
    // since the last press to ignore any noise:

    // If the switch changed, from off to on (LOW to HIGH)
    // ie, reading == HIGH and lastReading == LOW
    if (reading && !lastReading) {
    // reset the debouncing timer
    lastDebounceTime = millis();
    }

    // If the button is still pressed
    if (reading) {
        // and has been pressed for longer than the debounce delay
        if ((millis() - lastDebounceTime) > debounceDelay) {
            // Then turn on the button output
            buttonOutput = HIGH;
        }
    }
    else {
        // However if the button is not pressed, then turn off the button output
        buttonOutput = HIGH;
    }

    // set the LED:
    digitalWrite(ledPin, buttonOutput);

    // save the reading. Next time through the loop, it'll be the lastReading:
    lastReading = reading;
}

The second part of your question asks how you can register a button press after a complete button press cycle. In other words; the button is pressed, the button is released - only after this cycle has completed recognise it as a button push.

You don't have to detect the whole cycle, all you have to detect is the button being released. After all, the button cannot be released if it hasn't been pressed first.

You could adapt the State Change Detection example/tutorial from the Arduino website so that it is looking for the falling edge of the button input.

You could simplify the edge detection statements to the following:

if (!buttonState  && buttonStateLast) {

Basically it requires the last reading of the button to be HIGH and the current reading of the button state to be a LOW.


RFID RC522 reads the previous tag serial with different tag I hope someone can help me.

I'm using a Mega with RC522, and this happens:

I use a tag, it reads the right serial (e.g. AA:BB:CC:DD). Then I use a second tag and sometimes it gives me the correct value (e.g. 00:11:22:33), but often it gives me the previous tag serial (AA:BB:CC:DD). After a few attempts, it finally gives me the right one (00:11:22:33).

I really can't find what's wrong and i'd be grateful if someone could shed some light.

Here's the code:

if (RC522.PICC_IsNewCardPresent())  {
           RC522.PICC_ReadCardSerial();
          String strID = "";
        for (byte i = 0; i < 4; i++) {
          strID +=
            (RC522.uid.uidByte[i] < 0x10 ? "0" : "") +
            String(RC522.uid.uidByte[i], HEX) +
            (i != 3 ? ":" : "");
        }
        String seriale = strID;

        if (seriale != "0"){

          for(h=0; h<=numerogiocatori -1;h++){

            if (seriale == seriali[h]) {
              lcd.clear();
              lcd.print("Saldo Gioc. ") ;
              lcd.print(h + 1) ;
              Serial.print("tag ID: ");
              Serial.print(seriale);
              Serial.print(" .    ");
              lcd.setCursor(0, 1);
              lcd.print(totaledenaro[h]) ;
              delay(1500);
              lcd.clear();
              lcd.print("Importo");
              lcd.setCursor(0, 1);
            }
          }
        }}}

Thanks to anyone willing to help!

One rule for writing safety code is :

The return value of non-void functions must be checked by each calling function, and the validity of parameters must be checked inside each function.

You forgot to check if the tag has been readed i.e the return value of PICC_ReadCardSerial. If it fails the value is not updated, that is the reason why the value is still the old one.

Using the following code (from the ReadNUID example of the MFRC522 library https://github.com/miguelbalboa/rfid/blob/master/examples/ReadNUID/ReadNUID.ino)

// Init array that will store new NUID
byte nuidPICC[4];

void loop() {

  // Look for new cards
  if ( ! rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if ( ! rfid.PICC_ReadCardSerial())
    Serial.println(F("NUID has NOT been readed."));

  if (rfid.uid.uidByte[0] != nuidPICC[0] ||
    rfid.uid.uidByte[1] != nuidPICC[1] ||
    rfid.uid.uidByte[2] != nuidPICC[2] ||
    rfid.uid.uidByte[3] != nuidPICC[3] ) {
    Serial.println(F("A new card has been detected."));

    // Store NUID into nuidPICC array
    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }

    Serial.println(F("The NUID tag is:"));
    printHex(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
  }
  else Serial.println(F("Card read previously."));

  // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
}

void printHex(byte *buffer, byte bufferSize) {
      for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
  }
}

the result is

  A new card has been detected.
  The NUID tag is:
  97 C6 6E 09
  NUID has NOT been readed.
  Card read previously.
  A new card has been detected.
  The NUID tag is:
  CC 16 5D 83
  A new card has been detected.
  The NUID tag is:
  97 C6 6E 09
  NUID has NOT been readed.
  Card read previously.
  A new card has been detected.
  The NUID tag is:
  CC 16 5D 83

Sometimes when the second tag is used the tag is not read and the uid remains the same.


Sending digital signal from one arduino to another I have one arduino with two proximity sensors that send two digitalWrite signals if an object is detected. I checked to make sure the output of these is working properly and only sending high signals when they should. I have a second arduino that is wired directly from those two outputs as two digitalReads and printing whether or not they are high or low.

The problem is that even though the first arduino is not sending a high signal, the second arduino's digitalReads are seeing high. I tried putting a 1k or 10k resistor in between and that just seemed to decrease the rate of this happening, but it also decreased the rate of seeing the high signal when there actually was one.

Anybody know what I'm doing wrong?

Connections:

Arduino 2 (sensors) code:

/* Two ultrasonic sensors for collision detection
Angled on front sides

Checks for object and sends digital high if distance is less than set threshold
(ran out of pwm pins on main arduino)
*/

#define LEFT_INPUT 5
#define RIGHT_INPUT 6
#define LEFT_OUTPUT 8
#define RIGHT_OUTPUT 9

// distance to stop
int stopThreshold = 24;  // ~10cm

// vars
long ultraLeft, inchesLeft, cmLeft;
long ultraRight, inchesRight, cmRight;
int objectDetectedLeft, objectDetectedRight;

void Poll_Ultrasonic()
{
  // left
  ultraLeft = pulseIn(LEFT_INPUT, HIGH);
  inchesLeft = ultraLeft / 147;
  cmLeft = inchesLeft * 2.54;
  if (cmLeft < stopThreshold)
    objectDetectedLeft = 1;
  else
    objectDetectedLeft = 0;

  // right
  ultraRight = pulseIn(RIGHT_INPUT, HIGH);
  inchesRight = ultraRight / 147;
  cmRight = inchesRight * 2.54;
  if (cmRight < stopThreshold)
    objectDetectedRight = 1;
  else
    objectDetectedRight = 0;
}

void setup()
{
    // Serial monitor
  Serial.begin(9600);
  // pins
  pinMode(LEFT_INPUT, INPUT);
  pinMode(RIGHT_INPUT, INPUT);
  pinMode(LEFT_OUTPUT, OUTPUT);
  pinMode(RIGHT_OUTPUT, OUTPUT);
}

void loop()
{
  // check distances, set flags
  Poll_Ultrasonic();

  // set output pins high on detection, print detection messages
  if (objectDetectedLeft) {
    digitalWrite(LEFT_OUTPUT, HIGH);
    Serial.println("\n  LEFT object detected!\n");
  }
  else
    digitalWrite(LEFT_OUTPUT, LOW);

  if (objectDetectedRight) {
    digitalWrite(RIGHT_OUTPUT, HIGH);
    Serial.println("\n  RIGHT object detected!\n");
  }
  else
    digitalWrite(RIGHT_OUTPUT, LOW);

  // print distances
  Serial.print("Left ultrasonic distance: ");
  Serial.print(cmLeft);
  Serial.println("cm");
  Serial.print("Right ultrasonic distance: ");
  Serial.print(cmRight);
  Serial.println("cm");
}

Arduino 1 (main) code snippet:

// Ultrasonic pins
#define ULTRA_LEFT 7
#define ULTRA_RIGHT 11

// Ultrasonics
pinMode(ULTRA_LEFT, INPUT);
pinMode(ULTRA_RIGHT, INPUT);

void Poll_Ultrasonic()
{
  if(digitalRead(ULTRA_LEFT) && digitalRead(ULTRA_RIGHT))
    leftOrRight = 2;
  else if (digitalRead(ULTRA_LEFT))
    leftOrRight = -1;
  else if (digitalRead(ULTRA_RIGHT))
    leftOrRight = 1;
  else
    leftOrRight = 0;

  if (leftOrRight)
    objectDetected = 1;
  else
    objectDetected = 0;
}

...

void StopCar()
{
  esc.write(90);
  if (leftOrRight == -1)
    Serial.println("Object detected on LEFT! Stopping.");
  else if (leftOrRight == 1)
    Serial.println("Object detected on RIGHT! Stopping.");
  else if (leftOrRight == 2)
    Serial.println("Object detected on BOTH! Stopping.");
  else // should never reach this
    Serial.println("Ultrasonic debug statement: bad condition");
}

OK , start by connecting an LED at the Output of Arduino 2 pins .. ( hopefully it will glow )

Measure the current out of the output pins of Arduino 2 too


Getting a reset error on a WEMOS D1 As a learning effort, I am trying some sample code on my WEMOS D1, which is basically an Arduino compatible board with a built-in ESP8266 (Wi-Fi module).

This is the output of my Serial Monitor:

1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld
Initializing Wifi...
Start printMacAddress
 ets Jan  8 2013,rst cause:4, boot mode:(1,4)

wdt reset

It stops there and I see no more messages. Below is the code I am trying (from https://www.arduino.cc/en/Guide/ArduinoWiFiShield):

#include <SPI.h>
#include <WiFi.h>

void setup() {
  // initialize serial and wait for the port to open:
  Serial.begin(115200);
  // attempt to connect using WEP encryption:
  while(!Serial) ;
    Serial.println("Initializing Wifi...");
    printMacAddress();
    // scan for existing networks:
    Serial.println("Scanning available networks...");
    listNetworks();
}

void loop() {
  delay(10000);
  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

void printMacAddress() {
  Serial.print("Start printMacAddress");
  // the MAC address of your Wifi shield
  byte mac[6];
  // print your MAC address:
  WiFi.macAddress(mac);
  Serial.print("MAC: ");
  Serial.print(mac[5],HEX);
  Serial.print(":");
  Serial.print(mac[4],HEX);
  Serial.print(":");
  Serial.print(mac[3],HEX);
  Serial.print(":");
  Serial.print(mac[2],HEX);
  Serial.print(":");
  Serial.print(mac[1],HEX);
  Serial.print(":");
  Serial.println(mac[0],HEX);
}

void listNetworks() {
  // scan for nearby networks:
  Serial.println("** Scan Networks **");
  byte numSsid = WiFi.scanNetworks();
  // print the list of networks seen:
  Serial.print("number of available networks:");
  Serial.println(numSsid);
  // print the network number and name for each network found:
  for (int thisNet = 0; thisNet<numSsid; thisNet++) {
    Serial.print(thisNet);
    Serial.print(") ");
    Serial.print(WiFi.SSID(thisNet));
    Serial.print("\tSignal: ");
    Serial.print(WiFi.RSSI(thisNet));
    Serial.print(" dBm");
    Serial.print("\tEncryption: ");
    Serial.println(WiFi.encryptionType(thisNet));
  }
}

I am not a hundred percent sure, but I think this started happening when I connected D8 (Digital Pin 8) to a relay.  I later read that it has a specific use (to flash firmware I think). The error message appears to point to something called a "WatchDog Timer", but I am not even sure what to eat that with. :-)

There are no error messages in the IDE and it even uploads fine. So why is this happening and how do I fix it?

TIA!

If Watchdog timer is the cause of reset that means there is at least one place in your code that runs too long without allowing subsystems to do the background tasks. It might be possible the part of your code causing the problem is:

while(!Serial) ;

Instead that loop use:

while(!Serial)
  delay(100);

so the background tasks will get the chance to be exectuted during the while loop.

EDIT:
In fact you can completely remove that while loop as it is not necessary. There is a possibility !Serial is always true so the loop never ends. And I suggest you using 74880 instead of 115200 so you can see the debug messages sent automatically by ESP8266.
END OF EDIT

However, if that is not the part of the code that causes the problem (and I think it is not) then the problem might be for loop where you list networks. You can check if that is the problem by adding a small delay inside the loop as follows:

for (int thisNet = 0; thisNet<numSsid; thisNet++) {
  delay(1);
  Serial.print(thisNet);
  Serial.print(") ");
  Serial.print(WiFi.SSID(thisNet));
  Serial.print("\tSignal: ");
  Serial.print(WiFi.RSSI(thisNet));
  Serial.print(" dBm");
  Serial.print("\tEncryption: ");
  Serial.println(WiFi.encryptionType(thisNet));
}

If the problem will still exist then you can add a few more delay(1); statements through the code.

Instead of delay you may use yield(); which is the same as delay(0);.


How can configuration values be stored on an ESP8266? I have a project that uses an MQTT service, and I'm wondering how to best store the configuration settings (server, user, password, port) for the service as right now they are just hard-coded into some constants.

I saw that EEPROM can be used for this but I'm not sure it is the best way. I went to look at the code for WifiManager to see how it accomplishes this task for the SSID and password since it works so well and it removed its EEPROM dependency back in 2015: https://github.com/tzapu/WiFiManager/commit/659df9cb277c5f93946d9d8795e39a5ae5863ab1

I can't figure out how those settings are persisted.

If EEPROM is the best way for storing something like this, I'd like to write my values without overwriting/corrupting existing values, is that possible? How can I set the initial values of the EEPROM to the constants that I need?

Edit: well after digging into the esp8266/Arduino repository I found that the WiFi.SSID() and WiFi.psk() settings come from wifi_station_get_config and stored with wifi_station_set_config although I haven't found how those work so I think EEPROM might be the way to go here, I just need a bit of guidance and clarification on the right way to use it.

Thanks to Jaromanda X and Juraj for the SPIFFS recommendation. I was able to use this block of SPIFFS code as an example and safely store settings in my project outside of the compiled source.

To upload files to my ESP8266, I followed the installation and usage instructions for the ESP8266 filesystem plugin for the standard Arduino IDE.

First, I created a .gitignore file and added this so that none of the actual values would get added to the repository:

# MQTT config info
data/config.json

Then I created a data folder and added a config.json file that had all the configuration properties that I need to reference:

{
  "cloudmqtt_server": "***.cloudmqtt.com",
  "cloudmqtt_user": "********",
  "cloudmqtt_pass": "************",
  "cloudmqtt_port": 10000
}

Following the example above, I added #include <FS.h> at line #1 (as well as #include <ArduinoJson.h> for parsing the JSON) and have this block to instantiate the variables with dummy values that will be replaced by the actual values from the JSON file:

// MQTT pub/sub for the servo functions
#define CLOUDMQTT_CONFIG  "/config.json"
// these values are loaded from a config.json file in the data directory
char cloudmqtt_server[18] = "***.cloudmqtt.com";
int  cloudmqtt_port       = 0;
char cloudmqtt_user[9]    = "********";
char cloudmqtt_pass[13]   = "************";

Then in the setup I have this block to load the values from the config:

if (SPIFFS.begin()) {
  Serial.println("mounted file system");

  // parse json config file
  File jsonFile = GetFile(CLOUDMQTT_CONFIG);
  if (jsonFile) {
    // Allocate a buffer to store contents of the file.
    size_t size = jsonFile.size();
    std::unique_ptr<char[]> jsonBuf(new char[size]);
    jsonFile.readBytes(jsonBuf.get(), size);

    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.parseObject(jsonBuf.get());
    if (json.success()) {
      strcpy(cloudmqtt_server, json["cloudmqtt_server"]);
      cloudmqtt_port = json["cloudmqtt_port"];
      strcpy(cloudmqtt_user, json["cloudmqtt_user"]);
      strcpy(cloudmqtt_pass, json["cloudmqtt_pass"]);
    } else {
      Serial.println("failed to load json config");
    }
    jsonFile.close();
  }
}

I'm not sure if there's a better way, but this way works for me:
https://github.com/dieseltravis/esp8266-projects/tree/master/servo-demo


What is the baud rate for Wiegand? I am attempting to develop an Arduino project that can identify the bit format of a card (26-bit being the most common but not the only one).

This a library sets the serial to be 9600 baud.
https://github.com/paulo-raca/YetAnotherArduinoWiegandLibrary

This documentation says the data bit width is about 100us and the "inter pulse" or the time between the data bit is 20-100us.
https://docs.tibbo.com/taiko/ser_wiegand_mode

I don't understand how these match up? Also, Wiegand isn't even really serial. It uses two inputs - One input is for the on bits and another input is for the off bits.

Wiegand doesn't have a baud rate as such. It's an edge-based input protocol where it looks for HIGH to LOW transitions on two different input lines.

There are certain timing requirements, in that you can't send data faster than the receiver is capable of receiving and pulses have to be wide enough for the receiver to read, and there is a minimum time for the gap between messages, but other than that there is no defined baud rate.


ESP32 with Lolin 2.4 inch TFT Shield Power control I am running out of intelligence trying to control a Lolin 2.4 Inch TFT shield.
I connected the shield via the official TFT connector to a Lolin D32 Pro. I am using the ILI9341 libary from Adafruit. With the libary it is no porblem controlling the display.
Unfortunately, as soon as I put the esp32 into Deep Sleep, the display goes white but the background illumination stays on.
Does someone know, how I can trun off the background illumination?
As far as I understood, the background light is not controlled via the ILI9341. Instead I tried putting the GPIO32 on Low, since accoring to the schema of the Lolin TFT cable it is responsible for the TFT_Led
Unfortunately that does not work either

The backlight of this shield is ON as long as there's power on the 3.3V pin, unless you make GPIO 32 an output and pull it low.
In deep sleep, however, GPIO 32 will stop acting as a pulled down output pin but the esp32 keeps its 3.3V output pin powered, so the backlight will switch ON.
You could power the display over a mosfet, controlled by a GPIO.


Difference between these two relays (D1 Mini Relay Shield and Single 5V Relay) I've setup my NodeMCU v3 with this relay and I got this:

When using 3V to power the relay, I can hear coil when I turn on the board and I can only turn it on once. Then I can no longer hear the coil, but LED turns on and off.
When using VU pin (5V) to power the relay, I get the same coil sounds (when turning on board and on first toggle), then nothing. But the LED stays on, just slightly dims itself when turning on. Barely noticeable.

Alright, but I had a D1 Mini relay shield* laying around and I decided to give it a try. And it worked when powering the shield with VU pin (5V).

So my question is what is the difference? Does the D1 Mini Relay Shield have a transistor to pull up pin voltage from 3V to 5V and the other relay doesn't? If I had a logic level converter 3V-5V between the NodeMCU GPIO and the relay IN, would it work?

Thanks in advance.

*must say mine is a clone, but it works

Ok, so:

I've bought a logic level converter.
Bought another relay.

Now to the results:

With the first relay, no joy with 5v or 3v in any combination (3v on VCC / 3v on IN; 5v VCC / 5V IN; 3V VCC / 5V IN; 5v VCC / 3V IN)
With the second relay (the new one), funny enough.. Didn't work with 5V on VCC and 5V on input. But it did work with 3v on both of them.

I measured every output voltage to make sure everything was working fine and it wasn't a problem with power supply.

I guess it should work with 5v...? Right?

Anyway, it was indeed a faulty relay. And 3V on VCC and Input is what worked for me, even though it is a 5V relay. Thank you all for the assistance.


Mass Storage with Arduino Uno and LUFA guys ! I want to implement the mass storage example from the LUFA Library to my Arduino Uno, but I do not know where to start. Has anybody done this successfully and could give me a few pieces of advice ?

You start by taking the Uno and putting it aside, and picking up an AVR-based Arduino that has native USB device support such as a Leonardo or Esplora. You can then use the build scripts that come with LUFA to build the code for your device.


How to make a 5-volt relay work with NodeMCU? I have hooked up 2 channel 5-volt relays with NodeMCU v1.0 as shown in the fritzing below.

Relay are powered with a different power source than NodeMCU.

As of now, I am powering the NodeMCU from my laptop and the relay board from a 5-volt battery.

Below is the code I have written:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "said.";
const char* password = "secret";
ESP8266WebServer server ( 80 );
const int led = 13;
const int outputLed = 12;

void turnOnRelayOne(){
  digitalWrite (outputLed, 1);
  digitalWrite (5, HIGH); //GPIO 5 // Relay 1
  server.send (200, "text/html", "Relay 1 turned on.");
  digitalWrite (outputLed, 0);
}

void turnOnRelayTwo(){
  digitalWrite (outputLed, 1);
  digitalWrite (4, HIGH); //GPIO 4 // Relay 2
  server.send (200, "text/html", "Relay 2 turned on.");
  digitalWrite (outputLed, 0);
}

void handleRoot() {
  digitalWrite ( led, 1 );

  char temp[400];
  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  snprintf ( temp, 400,

             "\
  \
    <meta http-equiv='refresh' content='5'/>\
    <title>NodeMCU hooked to Relay Board</title>\
    \
  \
  \

Hello from NodeMCU!
\

Uptime: %02d:%02d:%02d
\
  \
",

          hr, min % 60, sec % 60
           );
  server.send ( 200, "text/html", temp );
  digitalWrite ( led, 0 );
}

void handleNotFound() {
  digitalWrite ( led, 1 );
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";

  for ( uint8_t i = 0; i < server.args(); i++ ) {
    message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
  }

  server.send ( 404, "text/plain", message );
  digitalWrite ( led, 0 );
}

void setup ( void ) {
  pinMode ( led, OUTPUT );
  pinMode(10, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(outputLed, OUTPUT);
  digitalWrite ( led, 0 );
  Serial.begin ( 9600 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );

  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( "esp8266" ) ) {
    Serial.println ( "MDNS responder started" );
  }

  server.on ( "/", handleRoot );

  server.on ( "/inline", []() {
    server.send ( 200, "text/plain", "this works as well" );
  } );

  server.on("/relay1", turnOnRelayOne);
  server.on("/relay2", turnOnRelayTwo);
  server.onNotFound ( handleNotFound );
  server.begin();
  Serial.println ( "HTTP server started" );
}

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

When I execute the URL: 192.168.1.8/relay1 the outputLed blinks as per the logic in turnOnRelayOne.

But neither of the relays turns on. Please help.

I have several of these modules. They have an optional opto-isolator built-in, but you have to remove the jumper to use it.

Connect your GPIO trigger as you have it
Run the relay's Vcc and Gnd pins to the MCU, not the power plug.
connect the power plug's +5v to the left-most pin, where the jumper once stood: JDVcc
connect the power plug ground to the MCU or the open common Gnd on the left-group of pins.

Now your relay coil(s) will be powered by the 5v plug, but the relay's logic and control are handled by the MCU.


How to power Arduino and shields with 4 rechargeable AA batteries? To start, I am a software guy, and I really want to ensure I not going to destroy any components. I previously looked at power through a USB power bank, but the issue with these is that they turn themselves off with low current pull.

My question is: I have a number of Arduino shields and would like to power them with 4 rechargeable AA batteries, and therefore would like some advice on what to use without frying any electronics.

The rechargeable batteries I have are these 1.2V AA (NiMH). Going on their rated value they should supply 4.8V. Testing the 4 batteries in serial gives me 5.3V overall, or around 1.325V per battery at full charge.

So if the batteries provide more than 5V, I cannot safely plug them into the 5V pin on the Arduino. But if the batteries could potentially provide around 4.8V to 5.5V plugging them into VIN means that the voltage regulator will take too much power, reducing the overall voltage to be too low for all of the shields (Which require 5V). What should I do in this situation?

This is a list of the current equipment that will require power:

Arduino Mega 2560
SIM900 GPRS/GSM Shield
Sparkfun GPS Logger Shield
Sparkfun Wifi Shield - ESP8266

The shields will be stacked on top of each other.

Most 5V devices will function fine at up to 5.5V - however, check the datasheets for the major components and modules on the boards.

The main thing to watch though is that a 3.3V device, which can normally communicate fine with a 5V one, may not be able to. The problem is that the logic HIGH signal from the 3.3V device may be below the threshold for a logic HIGH on the Arduino:

V_IH = 0.6Vcc = 0.6 x 5 = 3V

V_IH = 0.6Vcc = 0.6 x 5.5 = 3.3V

Thus a 3.3V device would have to output at the very minimum 3.3V as a logic HIGH in order for it to register as one on the Arduino, which may be a problem...

You can easily drop the battery voltage by 0.7V though by inserting a single silicon diode (such as the trusty 1N4001) in series with the batteries. That will take your voltage down from your measured 5.3V down to 4.6V which will improve matters somewhat.

However, it is important to note that you have so far measured the open circuit voltage of the batteries. That is, the voltage with no load on them. The voltage will most likely be lower once they are actively driving the Arduino etc.

The Arduino itself will be fine running off 5.3V, so I suggest you power just the Arduino direct into the 5V pin from the batteries and measure the actual voltage while powering the Arduino. That will give you a more accurate voltage reading. Then, if needed, you can add the diode to drop it by 0.7V.


2 if-else in one program Hey guys i have made an automatic plant watering system. Its really basic. the code is:-

char yo = 0;
void setup() {
  pinMode(2, INPUT);//moisture sensor
  pinMode(3, OUTPUT);// pump
  Serial.begin(9600);
}

void loop() {
  yo = digitalRead(2);
  if(yo == 1){
      digitalWrite(3,HIGH);
      Serial.println("Plant is Being Watered as the soil is dry");
      delay(5000);
    }
  else{
      digitalWrite(3,LOW);
      delay(5000);
      Serial.println("the plant has sufficient water");
    }
}

The thing that i want to add is.. i want to add a feature which can manually control it with bluetooth but the normal program should also be running. for eg. soil is wet but i want to add more water so i write 9 on the blueterm app which starts the pump for 2 seconds. I am using an HC-05 bluetooth module. can someone tell me how this can work on an arduino?

EDIT!

Sketch 2:

char ha;
void setup() {
  pinMode(3, OUTPUT); //pump
  Serial.begin(9600);
}

void loop() {
 ha = Serial.read();
 if(ha == 5){
    digitalWrite(3, HIGH);
    delay(2000);
  }
 else{
    digitalWrite(3,LOW);
  }
}

char ha;
void setup() {
  pinMode(3, OUTPUT); //pump
  Serial.begin(9600);
}

void loop()
{

  //.:.bluetooth control block
  if (Serial.available()) //check serial data availability
  {
    ha = Serial.read();
    if(ha == '9') //received data is char '9'
    {
      digitalWrite(3, HIGH); //turn on
      delay(2000);
      digitalWrite(3, LOW); //turn off
    }
  }
  else
  {
    //.:.manual control block
    if(digitalRead(2)){
      digitalWrite(3,HIGH);
      Serial.println("Plant is Being Watered as the soil is dry");
      delay(5000);
      digitalWrite(3,LOW);
    }
  }
}


program evaluating if clause incorrectly As the title says i'm having a problem with an if clause evaluating incorrectly in one particular function

uint16_t    getSleepTime()
{
    volatile uint8_t flag = EEPROM.read(3);

    uint8_t high    = EEPROM.read(0);
    uint8_t low     = EEPROM.read(1);

    if(flag != 0xaa);
    {
        Serial.println(flag);
        Serial.println("ERROR: SLEEP TIME NOT DEFINED, CANNOT CONTINUE.");
        while(true)
        {
            digitalWrite(PIN_LED, true);
            delay(250);
            digitalWrite(PIN_LED, false);
            delay(250);
            wdt_reset();
        }
    }

    return word(high, low);
}

the result is that the if function evaluates as true always
my first thought was, ok the eeprom wasn't written properly, hence i added the println, the returned value was 170 == 0xaa
then i thought well maybe the flag variable is optimized out, hence the volatile
and then, well maybe its a type comparison issue so i also defined a const uint8_t flagv with value 0xaa
same results in every case

13:21:00.991 -> 170
13:21:00.991 -> ERROR: SLEEP TIME NOT DEFINED, CANNOT CONTINUE.
and the corresponding blink

the thing is that being such a trivial code i'm out of ideas right now, as anyone here experienced something like this?

Do not put a ; after an if:

if(flag != 0xaa);

is the same as

if(flag != 0xaa)
{
}

Meaning that the code after the if statement is always executed.


Can the Arduino (Nano) bootloader be updated via itself and the Arduino IDE or is an ISP required? I ran into the following error with a recent Arduino IDE version (1.8.9) when trying to upload to an "Arduino Nano" clone (ATmega328P):

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x18
...
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x18
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

The problem could be resolved by choosing "ATmega328P (Old Bootloader)" as Processor in the Tool menu - as now suggested to me and solved in Arduino Nano uploading gives error: avrdude: stk500_recv(): programmer is not responding.

The change was made in August 2018 with the release of Arduino IDE 1.8.6: https://github.com/arduino/Arduino/releases/tag/1.8.6

Details about the different bootloaders are described in
Arduino Nano ATmega328P bootloader difference.

It seems the fuses have to be changed in order to make full use of the newer, smaller bootloader, so an ISP will have to be used anyway.

But is the bootloader able to update itself (via Tools > Burn bootloader) or is there an intermediate "bootloader update sketch" available?

On ATmega328p and similar ATmega MCUs with bootloader support, the application is not allowed to write to flash. Only code running in bootloader area of the flash memory is allowed to write to flash. Bootloader area is at the end of the flash and the beginning is set with the BOOTSZ fuses.

The write to flash page is done in two steps. First step is deleting the contents of the flash page, second step is write the new data to the flash page. In bootloader area* it is allowed to first prepare the data to temporary buffer page, then delete the flash and write the data in one step. So in theory the bootloader could overwrite itself with a function running in the last flash page. But I don't know about bootloader which would do it.

To write a bootloader an ISP programmer is necessary. Or other Arduino with the "Arduino as ISP" sketch.

*note: the read-while-write area at the end of flash has the size of the largest bootloader area possible and is not determined by BOOTSZ.


Serial.print skips or hangs inside a "if" statement. Trying to call a function VIA serial uart I have two microcontrollers talking to each other using serial UART pins.
Now for some reason which I can not figure out why... doing a Serial.print() does not work in an "if" statement. And also assigning/declaring/initializing variables and values inside the "if" statement does not work... this is really weird. I can turn on the GPIO pins in the "if" statement but other than that nothing else works.
Microcontrollers are: Arduino Nano and WeMos D1 Mini.
Just want to note that both of the microcontrollers are talking to each other fine and arduino can determine the serial input but it can not "Serial.print" in the "if" statement of "strcmp", it is being skipped.
EDIT: I just woke up this morning, and magically "Serial.print" is working properly inside the "if" statement of "strcmp"... I guess the microcontroller needed some rest, I was testing it for 13+ hours...
Please view the code below:
    void setup()
    {
      Serial.begin(9600);
    }

    void loop()
    {
      char a[5];
      delay(100);
      int i = 0;

      if (Serial.available() > 0)
      {
        while(Serial.available() > 0)
        {
            a[i]=Serial.read();
            i++;
        }

        a[i] = '\0';  //last character inserted with a "null char".
      }

     if(strcmp(a,"RGB_1") == 0)   //<----- "if" statement, comparing the string array buffer
     {
        int m = 1; //<---------------- declaring and initializing a variable
        //Serial.print(m); //<-------- Serial monitor will hang and skip the GPIO pins below to trigger.
        digitalWrite(12, HIGH);
        delay(1000);
        Serial.print(m); //<---------- "if" statement allows the GPIO pins to trigger but skips this serial print.
     }
   }

High likely you are exceeding your character array, see:
char a[5];

Which can hold 5 characters. However, you write:
if(strcmp(a,"RGB_1") == 0)

Which assumes you receive "RGB_1" which is 6 characters, because a string ends with a 0.
What also might happen is that you indeed receive only 5 characters without the ending newline, which means strcmp keeps searching until it finds a string end which may not happen.
So you can increase the array size a few just for testing purposes, and print i as jsotola proposes. Beyond that, also print each character you put into the array so you know how/if to handle a new line.
If you don't receive a string end, then use instead of the strcmp function, then use strncmp, which can search for exactly 5 characters, not checking until the end of the string.


Arduino Pro Mini (5V) Raw Pin and VCC Pin I am new to the microcontroller world and circuits, so bare with me. I recently bought some 5V arduino pro mini microcontrollers. I have been playing with them and they work fine, I have been powering it from an usb connection.
Now I want to power the board using a 9V battery, I connected the + to the RAW pin and the Ground to the Ground pin on the Arduino.
My question is if I can still use the VCC pins? I understand the board has a voltage regulator that from my understanding it brings down the 9V to 5V. I thought this 5 volts were available through the VCC pin but I connected an LED to it and nothing happens.

I have tried this method with an arduino Uno and it works so I dont know why it doesnt work with the Pro Mini.

As others have pointed out, without a current limiting resistor you may have fried the LED. Thus you might need another LED to test with. On a typical LED with a 1.2 forward voltage drop, a 220 ohm resistor will limit current to about 17 mA (i = v/r.)

forward voltage = supply voltage - LED voltage drop
forward voltage  = (5.0 - 1.2) = 3.8

current = 3.8V/220ohms = 17 mA.

Check the specs on your LEDs. 1.2 V forward voltage drop is common on little LEDs. Max current of 20 mA is common as well, but it doesn't pay to go all the way to the max. That's the "do not exceed or you may destroy it" level.


Public variable in class not incrementing I'm not sure what is wrong with my code, but whenever I call addNewLine, the linesInserted variable is not updating correctly. When I print the value of linesInserted inside of the addNewLine method, it shows as incrementing, but when I print the value inside of the draw method, it shows that it is 0.
I have tried different increment operators (linesInserted += 1 and linesInserted = linesInserted + 1). Oddly enough, when I do linesInserted = 99 instead of linesInserted++, it sets the value correctly. I'm wondering if I am possibly messing up a reference somewhere?
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1331.h>
#include <SPI.h>

class Character {
  public:
    char** lines; // using char for 8 bit integer
    int sizeOfLines;
    char symbol;
    Adafruit_SSD1331* display;
    int width;
    draw(int x, int y, int color);
    addNewLine(char startX, char startY, char endX, char endY);
    int linesInserted = 0;
};

Character::draw(int x, int y, int color) {
  if (linesInserted < sizeOfLines) {
    display->setCursor(0, 39);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "SYMBOL %c\nWASTED MEMORY", symbol);
    Serial.println(symbol);
    Serial.print(linesInserted);
    Serial.print(" ");
    Serial.println(sizeOfLines);
    display->print(buf);
  }
  for (int i = 0; i < sizeOfLines; i++) {
    char* line = lines[i];
    display->drawLine(line[0] + x, line[1] + y, line[2] + x, line[3] + y, color);
  }
};

Character::addNewLine(char startX, char startY, char endX, char endY)  {
  linesInserted++;
  if (linesInserted > sizeOfLines) {
    display->setCursor(0, 15);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "ERROR\nSYMBOL %c\nTOO MANY LINES", symbol);
    display->print(buf);
  } else {
    lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};
  }
};

EDIT: Git repo to the project is added - https://github.com/Pyrodron/charger-destination-board

It's difficult to pin down the exact details as to why the problem it's manifesting exactly the way it is. But, in short, it's fair to say you're running out of memory.
First, just a note:  The code I'm testing with (because it compiles) is the code out of your github repo, which used a char type variable for linesInserted and had a commented-out println(linesInserted);, so it kind of seems like at one point you'd been trying to print the count as character, specifically non-printable control characters.  So that might may have been confusing you.  I uncommented it and added a , DEC) parameter to it (rather than casting) to coerce println into treating it as an int.
I tested your code without the display library in a PC environment to allow me to run valgrind on it.  It didn't find anything; I wasn't necessarily expecting it to.  But, I did crudely instrument your code in this enviroment to see that you're calling malloc()/new 124 times, for a total of 500 bytes, but importantly this does not include the structure heap overhead, which is significant because you're new-ing tiny four-character chunks.
Then I ran your code as compiled for an AVR.  Because I don't have your display, and wanted to match your environment as closely as possible, I left the display code in but NOPed out a few function calls that would have screwed up my test rig.
The primary finding is that you're dangerously close to "running out" of memory:

000005e0 | 01 00 02 04  00 01 00 02 - 00 04 00 03  01 03 05 04 | ........ ........
000005f0 | 00 01 03 02  03 04 00 01 - 06 02 06 04  00 00 00 00 | ........ ........
00000600 | 00 04 00 02  00 02 00 04 - 00 01 01 01  01 04 00 00 | ........ ........
00000610 | 02 00 02 04  00 02 02 02 - 02 04 00 01  03 01 03 04 | ........ ........
00000620 | 00 00 04 00  04 04 00 02 - 04 02 04 04  00 01 05 01 | ........ ........
00000630 | 05 04 00 00  06 00 06 04 - 00 02 06 02  06 00 00 00 | ........ ........
                                                      ^^
                                                 [__brkval]

                          [SP]
                           VV
000006b0 | 00 00 00 00  00 00 b7 09 - 03 01 01 06  02 a5 02 00 | ........ ........
000006c0 | 00 00 00 01  00 57 05 06 - cc 00 03 8f  0f 01 00 00 | .....W.. ........
000006d0 | 00 01 00 00  03 00 03 00 - 00 00 07 02  a4 00 01 00 | ........ ........
000006e0 | 03 02 a4 00  05 f8 0d 06 - f6 00 03 00  00 08 c3 08 | ........ ........
000006f0 | de 00 01 00  01 80 1a ed - 02 04 00 41  a4 02 04 00 | ........ ...A....

There's 120 byte separation between the edge of the heap and the stack pointer.  The implementation of the malloc that I ran this under checks to see whether or the the stack pointer is within 128 (__malloc_margin) bytes.  As your code was building in my environment, without the counter-printing in, this managed to not-fail to allocate.  However adding a single additional call to addNewLine was enough to cause malloc() via new to fail.  So you are indeed right on the edge.  And you have no checks to see if malloc or new returning nullptr.
You're making one allocation after another without deallocation anything, which is resulting in a fairly simple pattern of the heap edge advancing by the requested size of your allocation plus 2 bytes each time.  So that's about 248 bytes waste in just heap structure.
I'm not sure on the exact cause of your counter being overwritten, assuming that's what's actually happening.  In fact I was having a hard time finding an case where it would overwrite anything in memory with the code as you have it, but here's a good candidate:
lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};

With generated code looking like:

0x24c6 [addNewLine+244] ldi    r25, 0x00       ; 0
0x24c8 [addNewLine+246] call   0x3830  ;  0x3830 [malloc]
0x24cc [addNewLine+250] movw   r30, r24
0x24ce [addNewLine+252] st     Z, r10
0x24d0 [addNewLine+254] std    Z+1, r11        ; 0x01
0x24d2 [addNewLine+256] std    Z+2, r17        ; 0x02
0x24d4 [addNewLine+258] std    Z+3, r16        ; 0x03

So, if malloc() fails, apparently the new statement will just assume that it didn't and goes ahead and writes into the memory at 0x0000 (nullptr) anyway, ugh.  I think this is because technically you're calling the normal new that is supposed to throw an exception on failure.  But there are no exceptions with the way avr-g++ is set up for Arduino.  As it exists in ArduinoCore-avr version 1.8.3, the new code just returns what malloc returns and the compiler thinks an exception will be in progress if it fails.  Normally you would call the std::nothrow version of new[] that returns nullptr on failure, as in:
lines[linesInserted - 1] = new(std::nothrow) char[4]{startX, startY, endX, endY};
// check lines[linesInserted - 1] against nullptr here

However, there's no facility to do that in 1.8.3.  The master as of writing appears to have addressed this, but that's not shipping yet.

The short answer to this is basically: Don't do that. That is:

Avoid dynamic allocation altogether where possible.

This was mentioned in the comments, but it's worth repeating, use flash where you can.  Besides getting your character data into PROGMEM, you also have some string literals that can be moved into flash by way of F().

To the extent that you're doing dynamic allocation requests:

Check to see that they're actually succeeding

Make as few requests as possible.

Do them up-front at the beginning of the code.  The "up-front" part you're more or less already doing, so that much is good.

It seems if you're going to dynamically allocate under core version 1.8.3 and you're at all in danger of having an allocation failure, it is important that you not use new, since doing so may cause it to overwrite memory for the initialization/construction part after the allocation proper has failed.  Alternately, seriously consider modifying your Arduino core's new.cpp file to do something like call abort() if malloc() returns nullptr, at a minimum, if not something more sensible.  Otherwise, this could drive you insane.


RFID tag "location identification" Can an RFID tag be used to identify a room? For example, I walk into a room, and the RFID receiver tells me that I am in say, the living room. Would it be possible for a tag to ping back the signal from a distance of 10ft? Or is there a similar technology like RFID that can extend to a much greater range?

There are newer long range RFID solutions. You can do a google search on "Ultra Long-Range UHF Wireless RFID Sensors" for more information, but almost all of these systems are still proprietary (i.e. I'm not aware of any hobbyist breakout-boards based around UHF tags yet).

The Disney MagicBands are an exact use-case of your question: Their magic bands use a combination of 13MHz RFID tags, and a new UHF active tag (it requires a small battery). They use them to collect data on how people flow through their Walt Disney World facility.  What bathrooms see the most activity, and when, for example.  There is actually a pretty decent amount of information available about the technology used in the Disney Magicbands if you're curious about the technology.