IR receiver transmitter High frequency I build photo gate, to detect throwing ball.
It works fine when delay time in main loop for max 40 milliseconds.
Problems start when I delay every loop only for 20 milliseconds, now my LED which indicates if something broke path between IR led and IR receiver, blinks occasionally, if I set delay for 10 milliseconds and turn on, then LED is off for 2 seconds, then start blinking very fast and is ON for rest time, until I break IR path. I think some physics is going on here which I don't understand.

I also would like to ask if it is possible to narrow IR wave path to be more like laser (going strait into one direction) and how I can control sensitivity of IR detection

This is schematic

IR transmiter
IR reciever

Code:

//define pins. I used pins 4 and 5
#define irLedPin 4          // IR Led on this pin
#define irSensorPin 5       // IR sensor on this pin
#define buzzerPin 2       // buzzer on this pin

int irRead(int readPin, int triggerPin); //function prototype

void setup()
{
  pinMode(irSensorPin, INPUT);
  pinMode(irLedPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  Serial.begin(9600);
  // prints title with ending line break
  Serial.println("Program Starting");
  // wait for the long string to be sent
  delay(100);
}

void loop()
{

  bool isOn = irRead(irSensorPin, irLedPin);
  //Serial.println(isOn); //display the results
  if(isOn == true)
  {
    digitalWrite(buzzerPin, HIGH);
  }
  else
  {
     digitalWrite(buzzerPin, LOW);
  }
  delay(10);
}

int irRead(int readPin, int triggerPin)
{
  int halfPeriod = 13; //one period at 38.5khZ is aproximately 26 microseconds
  int cycles = 23; //26 microseconds * 23 is more or less 600 us
  int i;
  for (i=0; i <=cycles; i++)
  {
    digitalWrite(triggerPin, HIGH);
    delayMicroseconds(halfPeriod);
    digitalWrite(triggerPin, LOW);
    delayMicroseconds(halfPeriod - 1);     // - 1 to make up for digitaWrite overhead
  }
  return digitalRead(readPin);
}

While you are doing a delay() you can't be doing anything else - that includes looking to see if the beam has been broken by the ball.

You must not use delay() in your sketch, instead use millis() as in the BlinkWithoutDelay example sketch in the IDE's File -> Examples menu.

Also how you are dealing with your IR system is incorrect.  You are first generating a brief square wave and then afterwards you are looking to see what was received.  Instead you need to be generating the square wave and at the same time see if that square wave is being received.  Normally that is achieved by using one of the PWM outputs of the Arduino set to the right frequency to generate a constant waveform which the receiver then senses all the time.


Arduino powered car not running when touching ground I hacked a cheap car I connected both motors to L298N Dual H-Bridge Motor Controller and all things are working good. Motors are running fast. But when I put the car on the ground to run. It runs so slow. I am using 4.5V for L298N.
What can I do to run it fast on ground?

I have tried PWM but it does not work.

What can be the causes of this?

It cannot draw enough current I suppose. When wheels are free-spinning, the load on motor is very small. When you put it on ground, the load increases, and it is slow because there is not enough current to drive the load


Arduino serial communication synchronisation i am trying to send data via Labview to my arduino board using serial communication.My problem is that the arduino reads only the first byte of sent data then when i change it ,it doesn't react.
For example when i start the communication i send '0' to arduino.I sees it.but while it is running i send '1' but it doesn't behave accordingly to it.
I noticed also that the board 'sees' sometime the new value after a random period of time.

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

char data = 'F';

void loop()
{
    data = Serial.read();
    delay(50);

    if (data == '0')
    {
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
        delay(1000);
    }
    if (data == '1')
    {
        digitalWrite(13, HIGH);
        delay(4000);
        digitalWrite(13, LOW);
        delay(4000);
    }

    data = '4';
}

I suspect you problem stems from the use of delay's in your code. for example,

if (data=='1')
 {
  digitalWrite(13,HIGH);
  delay(4000);
  digitalWrite(13,LOW);
  delay(4000);
 }

Those delays prevent any computations from happening for 4 seconds each. Your arduino will not read another character after it sees a '1' for 8 seconds. If you send too much data in that 8 seconds to fit in the serial buffer, the extra characters are lost.

The behavior you seem to want will require separating the code that reads serial from the code that runs the output, and making sure neither section ever stops execution with delays. Your blinks will need to be timed with something else, like frequent comparisons against the current time with millis()


Analog input voltage rises when motor is working I'm making automatic water plant system. I'm using:
Arduino Uno
3.3-6V water pump -https://www.amazon.com/Vipe-Micro-Submersible-Motor-Water/dp/B01N0X3CW4
Capacitive soil moisture sensor - https://www.amazon.com/Gikfun-Capacitive-Corrosion-Resistant-Detection/dp/B07H3P1NRM
I've noticed that when motor turns on sensor readings are much higher. First I thought that the problem is in sensor, but when I measured sensor output in both cases (when motor is on and when motor is off) there was no difference, voltage was the same. Then I measured voltage in analog pin A0 that I used, and I saw there is increase in voltage when pump is on (+0.4V), so my guess is that this voltage is added to  sensor output voltage which is giving me higher values in my serial monitor.
For powering my pump I'm using same circuit as in this example:
https://www.devacron.com/arduino-tip120-control-dc-motor/
Just except potentiometer there is my sensor, powered via 3.3V Arduino pin (its GND is connected to Arduino GND). I also tried connecting all grounds together in one point, didn't help. I powered Arduino with usb and with 9V supply, in both cases same problem. Tried powering pump and Arduino with same and with different power supplies, no luck either.
I should also add that there is no change in AREF and 5V pin when pump is working. 4.97V in both cases.
Does anyone have any idea what can be the problem and how to solve it?
Here is how I wired everything:
https://imgur.com/a/I70lRVZ
I also tried with 0.1uF ceramic and 10nF electrolytic capacitors. as suggested, wiring it like this: https://imgur.com/a/jWfkbJG
Didn't make much difference, problem is still there.

Try adding some bypass capacitors at the two points I've added arrows to:

I suggest two in each spot, one a 0.1uF (or similar) ceramic dipped or disc and the other a 1 or 10uF electrolytic.  Keep the polarity in mind for the electrolytic.
Oh, and another thing.  Be sure your motor is not pulling your power supply voltage down.  It's possible your phone charger supply is inadequate to supply the power needs of the motor.  Use a voltmeter across the input to the Arduino and check the voltage when the motor runs.  If it's dropping much below 5V you need a better power supply.  Well, I see now that you are only powering the motor from that 5V supply.  So that's probably not it.


How to connect Android phone to Arduino? Is it possible to connect an Arduino to an Android Phone and use it for input/output?
Are connections possible over USB? Or do I need to have a wifi or Bluetooth shield?

You bet it's possible. I used a pretty cheap bluetooth module that I got from Amazon, and wrote an app using the information on the official Android Developers page to connect to the Arduino. There are many guides online telling you how to hook up a module to the pins of the duino.

You can probably get a cheaper module if you look on eBay and don't care how long it takes to arrive, and I think there's at least one app on the Play store for controlling an Arduino if you can make it work for your purpose.

USB connections are probably possible, though I haven't done any of that.


How to Compile Different Sketches in Different Visual Studio Code Workspaces I'm using Visual Studio Code with the Arduino extension. I have two workspaces each with a different sketch file loaded - Sketch_1 and Sketch_2. Sketch_1 will verify and upload properly. When I click on the Verify to compile or Upload buttons for Sketch_2 in its workspace, VS Code verifies and uploads Sketch_1, not Sketch_2. Am I doing something wrong, or is it not possible to separately Verify and Upload different sketches in different workspaces?

The first time you verify your sketch you are confronted with a list of available sketches (INO's). As soon as you select one of these it gets stored under "sketch" in .vscode/arduino.json.
If you zero this, "", you'll once again be asked which sketch to set as "main sketch".

This "device context" is stored per workspace so you might consider narrowing your scope when opening a folder. I know this is no fun when exploring, and the will to switch and try different examples is big, but currently there are nothing that facilitates a smoother alternative.


Detect 2 wire thermostat output I have a 2 wire thermostat. R is +24VAC, W is Heater. I have no Ground wire (C), and I cannot open the thermostat.
When the heater goes on, the thermostat internal relay gets powered and connects R and W together.
How can I detect when the heater is on from those two wires?

With checking the temperature in the room. When the contact is closed store the current temperature. Check after a minute the temperature again. If it is higher, the heater is on.


Few questions related to programming microcontrollers I'm learning "Arduino" (I don't have previous knowledge of microcontrollers). I have few questions:

What is the difference between programming a microcontroller in C and programming in "Arduino?"
Is it a good idea for beginners to start programming microcontrollers in Arduino and then start learning to program in C?
I have Arduino Uno with an Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board? What are differences between various microcontrollers which can be used with this board?
If a microcontroller is already programmed, can we download the program from it to a PC and edit it in Arduino IDE? Or it is like a .exe on a PC, once compiled we can't get source, all we can do is reverse engineer?

That's it :)

The Arduino IDE uses C++ primarily, which it preprocesses in order to make compilable. But you can still for the most part use C in the Arduino IDE and it will just work as normal; there's nothing requiring you to use C++ or the Arduino libraries (or even the Arduino IDE) for most tasks.
Not touching this one. And in the end it doesn't matter terribly since they're very close.
Any of the ATmegaXX8 or ATmega8 chips will fit the socket. Note that they will require separate cores if you're using the IDE. And you can use any chip without the board in the IDE as long as you can find a core for it.
Not if you use a traditional compiled language to program it. If you use a VM then you conceivably could, but you'd have the source on your system regardless.


Arduino Pro Mini Avrdude stk500_getsync() not in sync I'm new to arduino and I have a project to make a gesture sensor controller but now I'm about to test the APD9960 gesture sensor; when I program the Arduino Pro mini it keeps sending me an error  (avrdude stk500_getsync() not in sync).
This is the connection that I use. I just copied the diagram from Circuito.io:

These are my tools settings:

I just change the processor to 5V even if i have 3.3V and it works!!


Attiny85 not able to understand data from 433Mhz using VirtualWire.h The basic plan is to have a Attiny85 pass information from a 433Mhz RF module to another chip/Arduino via I2C using VirtualWire and Wire libraries. I have been able to make this system work on their own using Arudino Nano's to debug, but the Attiny85 (A85) seems unable to grab the data from the RF 433 Mhz.

So have spent a few days doing some more research, and basically putting each component separate, to make sure what is being sent is correct.

433 Mhz transmitter is working by sending a 9 digit number, using VirtualWire.h.
Nano with a 433 Mhz receiver is receiving 9 digit
number, VirtualWire.h.
Attiny85 is sending either a no data, or the 9 digit number, to another Nano using Wire.h.
The Nano is getting only No Data, so the I2C is working between A85 and Nano.

Attiny85, on Pin 1 (pin 6 on chip) is not getting any data from the 433 Mhz, which works on (2). I connect the GND of the 433 RX to the chip.

Here is the Receiver code:

#include <VirtualWire.h>
#include <Wire.h>
void setup() {
  pinMode(A3, OUTPUT);
  Wire.begin(); // join i2c bus (address optional for master)
  vw_set_ptt_inverted(true); // Required for DR3100
  vw_setup(4000);   // Bits per sec
  vw_set_rx_pin(1);
  vw_rx_start();       // Start the receiver PLL running
}
void loop() {
  uint8_t buf[15];
  uint8_t buflen = 15;
  if (vw_get_message(buf, &buflen)) // Non-blocking
    {
      digitalWrite(A3, LOW);
      Wire.beginTransmission(8); // transmit to device #8
      for (int i = 0; i < buflen; i++) {
        Wire.write(buf[i]);
      }
      Wire.endTransmission();    // stop transmitting
    } else {
      digitalWrite(A3, HIGH);
      Wire.beginTransmission(8); // transmit to device #8
      Wire.write("no DATA");
      Wire.endTransmission();    // stop transmitting
     }
}

Here is the Transmitter code:

#include <VirtualWire.h>
int xPin = A7;
int yPin = A6;
int buttonPin = 2;

int xPosition = 0;
int yPosition = 0;
int buttonState = 0;
const char *controller;
void setup() {
  Serial.begin(9600);
  pinMode(12,OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(yPin, INPUT);
  pinMode(xPin, INPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  vw_set_ptt_inverted(true); //
  vw_set_tx_pin(12);
  vw_setup(4000);// speed of data transfer Kbps
}

void loop(){
   xPosition = analogRead(xPin);
   yPosition = analogRead(yPin);
   buttonState = digitalRead(buttonPin);
if(xPosition > 0 || yPosition > 0) {
  String Data = (xPosition + yPosition);
  controller = Data;
  vw_send((uint8_t *)controller, strlen(controller));
  vw_wait_tx(); // Wait until the whole message is gone

} else {
  digitalWrite(13, 0);
  digitalWrite(4, 1);
  controller = "#s0_0";
  vw_send((uint8_t *)controller, strlen(controller));
  vw_wait_tx(); // Wait until the whole message is gone
}

Serial.println(controller);

}

So basically the A85 is not getting past if (vw_get_message(buf, &buflen)) { on pin 1. But does when using the Nano on pin D2, from the same transmitter, but not at the same-time of-course.

Am I using the wrong Pin on the A85? Chip pin 5 and 7 are used for the I2C so it only leaves analog pins so not sure they would work either. I also tried 8 Mhz and 1 Mhz when loading the A85.

I  have tried different Cores as suggested from Google, different versions of VirtualWire and clocked the Attiny 1Mhz, 8Mhz and 16Mhz. None of have worked.

Not sure what else I am missing?

Have you tried using the Radiohead  library? I know you said you tried different versions of Virtual Wire. The RH_ASK class works on a 328p and a nano for sure and they claim a simple Rx program can run on a ATTiny85. They have documentation under RH_ASK regarding the changes you need make to the library.
Another possible fix is to edit the Virtual Wire library files, they might have variables like "Max_payload" (Radiohead does) whose size can be decreased.
I haven't actually read the Virtual wire library, but I am sure Radiohead should fix your problems.

If this doesn't work, do you have an oscilloscope? Maybe we can try debugging it like that.

Edit: Maybe try commenting out the vw_set_ptt_inverted line first. I don't think you are using the DR3100. Might not make a difference because you haven't actually set a pin for ptt.
Next thing you can try is just connecting the data pin of the Tx to the Rx. You should be able to check if the module is actually connected to the ATTiny with this.


Arduino Uno Multiple Modules I have an Arduino Uno and I want to connect;

RFID Reader (RC522)
WiFi Module (ESP8266 ESP-01)
SD Card Module
RTC (Real Time Clock - DS1307)

Same time but pinouts are not enough. Is there a way to doing this with Uno or I have to buy an Arduino Mega ? I saw "Expansion Sensor Shield"s but I do not know what is the logic of using this ?

Regards

Let's see which device uses which communication protocol:

WiFi Module (ESP8266 ESP-01) uses Serial communication.
RTC (Real Time Clock - DS1307) uses I²C communication.
RFID Reader (RC522) uses SPI communication.
SD Card Module also uses SPI communication.

Now, the Arduino UNO supports One I²C, One SPI and One Serial (by default) communication port.

So, you can easily connect your Wifi and RTC modules.

Now, actual problem is: "How to access multiple SPI interfaces on Arduino" (and that is a solved problem).

Hope it helps and you don't have to buy an Arduino MEGA.


ESP8266 as WiFi for Arduino I have a pretty simple project, where some data has to be read from a mySQL server. My idea is to do this with an ESP8266, and then provide that data to the Arduino Mega.

Is this possible or am I going to have to use the ESP8266 itself? I highly doubt that I would have enough pins then.

I read something about AT-commands. But I have no idea how to send those commands to the ESP.

Thanks in advance,

Michidez

Check out ESP-LINK You can find it here
ESP-LINK is a esp8266 wifi-serial bridge, outbound TCP, and arduino/AVR/LPC/NXP programmer. It has several configuration, one of them allowes uploading new firware ower wifi, or to act as a serial link just like if usb cable is pluged in and serialport viewer is active. The website has great documentation and has one of the slickest configuration interfaces seen on ESP.


Arduino 10bit ADC is not accurate? I'm reading the voltage with voltage divider:

simulate this circuit – Schematic created using CircuitLab
 | Arduino is connected to both USB and a 9V adapter.

float r1 = 100000;
float r2 = 9980;
float adc, voltage, analog;
void setup() {
  Serial.begin(9600);
  analogReference(EXTERNAL);
  pinMode(A0, INPUT);
}

void loop() {
  for (int i = 0; i < 256; ++i) {
    analog += analogRead(A0);
  }
  analog = analog / 256;
  adc = analog * 1.228 / 1023;
  voltage = adc / (r2 / (r1 + r2));
  Serial.print(analogRead(A0));
  Serial.print(", ");
  Serial.print(analog);
  Serial.print(", ");
  Serial.print(adc);
  Serial.print(", ");
  Serial.print(voltage);
  Serial.println(" ");
  delay(100);
}

Here's the accuracy test result:

Input | Arduino | Difference
 1V      0.89V     -110mV
 2V      1.90V     -100mV
 3V      2.92V     -80mV
 4V      3.93V     -70mV
 5V      4.95V     -50mV
 6V      5.97V     -30mV
 7V      6.98V     -20mV
 8V      8.00      0
 9V      9.01      +10mV
 10V     10.02     +20mV
 11V     11.04     +40mV
 12V     12.06     +60mV

The input voltages measured by DMM and was spot on voltage, like 1.000V.

I didn't test voltages above 12V but it seems the difference is gonna increase by 20mV with each 1V increase, that means at 50V voltage reading is gonna be off by ~1V!

Even with 10bit resolution of Arduino I should have had steady accuracy with some percentage of difference(right?), but as you can see the result shows that the reading is not steady at all!

Why the voltage difference decrease/increase when voltage changes at the input?

As stated by Majenko, the ADC can in principle have all sorts of
errors. However, if you look at your data, you should notice that the
error is essentially linear with the voltage. This means that the
non-linearity error is quite small, and you are mainly seeing the offset
and gain errors. This is fortunate, because these errors are easy to
remove, given good calibration data.

The table you wrote in in your question happens to be a perfectly good
calibration table. By fitting a straight line to it you can get a
calibration function, and then correct the readings simply by adding
this to your code:

voltage = 0.9848815 * voltage + 0.125354;

Or you could instead figure out the correction at the ADC level and
replace

adc = analog * 1.228 / 1023;

by

adc = (analog + offset) / scale;

where offset and scale are computed from the calibration.

Edit: Here is how I extracted the calibration coefficients from the
data.

First, I saved the data in a text file calibration.tsv and cleaned it up
to remove the units and add a comment marker (#) in front of the column
labels:

#Input | Arduino | Difference
 1      0.89     -110e-3
 2      1.90     -100e-3
...

Then I looked at the data with gnuplot. Since I want to know how to
correct the readings, I plot the amount I have to add (minus column 3)
v.s. the Arduino reading (column 2):

plot 'calibration.tsv' using 2:(-$3)

At this point it appears it's linear with what looks like mostly
quantization noise. I model this as a line of equation a*x+b, and
compare the line with the data:

a = -1e-2
b = 0.12
plot 'calibration.tsv' using 2:(-$3), a*x+b

The line is quite off the data, but it's a reasonable first
approximation. Now I ask gnuplot to perform a least squares fit, then
take another look:

fit a*x+b 'calibration.tsv' using 2:(-$3) via a, b
replot

Now the fit looks quite good. When it completed the fit, gnuplot
displayed:

Final set of parameters            Asymptotic Standard Error
=======================            ==========================
a               = -0.0151185       +/- 0.0002953    (1.953%)
b               = 0.125354         +/- 0.002173     (1.734%)

so now I know I can correct the data with:

voltage += -0.0151185 * volatage + 0.125354;

which is equivalent to what I wrote above.


A sensor to recognize my pet near me Need a specific sensor that will detect when a pet comes close in a range of distance. As it comes close a beep intimates that the pet has reached. What sensor will work here. Can it work with an Arduino. ?
cat has a habit of going down 2 floors to poop. Problem is when she comes back the door is closed and neighbours don't like it. So a system by which moment she comes within a certain distance of a gadget it then beeps. May be a product already in market. Or if need be to put things together to work. Bell is a good idea but won't be loud.

Off topic for Arduino, but you could put a collar with an Apple iBeacon on your pet and implement an iOS app that would wake up and display a local notification (optionally including a sound) when your pet comes near.

You could probably do something similar using BLE, but Apple's iBeacon has the concept of geofences based on proximity to one of their iBeacons, including distance ranges from "immediate" (about a meter) to far (30+ meters, if memory serves). That's actually somewhat tricky to do using vanilla BLE.

I think in order for this to be practical you will need to put some sort of transmitter on your pet. The RFID chips that vets put into pets require that the sensor be within a few mm of the chip, so that probably wouldn't work. (From what I've seen you have to wave a wand directly over the chip on the pet's skin in order for it to be detected.) There are other RFID technologies that should work. I found this link from a Google search, for example:

https://skyrfid.com/RFID_Range.php


How to connect naked camera from mobile phone to Arduino Uno Okay, guys. I have this 3 cameras(middle from the iPhone 6s, 2 at the side I found, and I think there are from modern phone). I need some information how to connect Arduino Uno to them. I know c/c++, assembler, but noob in microcontrollers, if this knowledge can come useful.

You need either a memory extension for your UNO - projects like Arducam did this way back 2016 and then used an OV2640 module. If you want to develop something yourself these are the steps (hurdles) to take:

Get a datasheet of the camera
Design a circuit including

plug for Camera and a
memory module (min 512Kb)

Attach it to the UNO
Write a library/function module (see datasheet for details) and
bring it to life

My tip save ca. two years of your life and get for 6-8$ an ESP32cam
This will cost you enough of your time, but be much more rewarding


Arduino Due ADC negative voltage I’m trying to sample an AC signal on the Arduino Due. The AC signal will never exceed +-80mv across a frequency range of 6-833Hz. Current is negligible.

I believe there are clamping diodes to protect from this but cannot find any datasheets for the Due.

I understand that the Due cannot read negative voltage but can a negative voltage damage the ADC or it’s accuracy?

The best thing you can do is to simply add a DC offset to your signal.  Instead of having it be 0V ±80mV, have it 1.65V ±80mv.  All you need is a capacitor and two resistors:

simulate this circuit – Schematic created using CircuitLab

However, 80mV is not going to have much resolution unless you reduce your reference voltage considerably, and in that case you'd need to reduce the 3.3 down to the same (or around) the reference voltage you use.

But, just feeding your signal directly into the ADC will give you the positive 80mV signal which you can use a smaller reference voltage with directly with no problem - after all, the datasheet shows:

  Voltage on Input Pins
  with Respect to Ground (except VBUS)...............-0.3V to +4.0V

So you can provide down to -300mV on an analog input before it potentially becomes a problem.

This is because all the IO pins have ESD protection diodes, which look like this:

simulate this circuit

Those diodes have a forward voltage of about 300mV, and so anything below -300mV will cause the lower diode to start conducting. When that happens too much current can flow and the diode risks burning out.  But you can add further protection by simply adding a small resistor (1kΩ is good) in series with the IO pin to limit the current in the case that the voltage goes below -300mV and protect the internal circuitry.


Finding arduino bootloader version? I have problem with WDT reset. After reset the device goes on for a boot loop. from the following link https://code.google.com/p/arduino/issues/detail?id=181
It has been mentioned that there is problem with Bootloader because some of them does not support wdt properly.How can i find which version of bootloader is running in my arduino mega 2560 . Which version of bootloader support wdt properly? where these bootloaders can be found?

In all practicality; put a known boot loader on it. Because if it is a problem version you will need to replace it anyways.

The Mega uses STK500 protocol. Which only shows a command to read its type (or signature) and not its version of firmware.

It is a good exercise, but not really worth the time to go deeper into it, as programmers are cheap and or you can use another Arduino as the programmer.


Using 555 as an external Watchdog I would like to use a 555 circuit as an external watchdog for my Arduino project. The project is a cellular tracker that goes to sleep for an hour, wakes up and does some measurements, uploads them and then goes to sleep again. The 555 should take care that the active period does not take too long because the systems hangs, and in that case trigger a reset. My first thought was to power the 555 circuit with a PIN of the Arduino so that it only goes on when the system is awake and is turned off while sleeping.
But this does not work as the reset line has to stay high even while sleeping and if i turn the 555 off reset would also go low. Could a Mosfet help? Any other ideas?

ok guys - found the answer: this post here at electronics-stackexchange gave the right hint: Watch-Dog Timer. And my gut feeling was right as well - i simply use a NPN-Mosfet that is being triggered by an Arduino-PIN (which easily can be done while sleeping as well as sleeping means waking up every 8seconds anyway) that connects the capacitor to ground and therefore discharges the guy. Awesome.
This solution can be used as a real fallback in case of whatever happens, while operating the system with built in watchdog-functions while everything is ok.


Limitations of connecting to many Arduinos via Ethernet? I'm planning a project where I need to control a lot of Arduino Unos from a single PC. I'll need to send commands to the Arduinos and receive responses, as well as have the ability to update each Arduino from the PC, preferably without Arduino IDE at some point. Connecting via USB is out of the question, as I have already tried this and got miserable results, in part because of the number of Arduinos I need to control. So now I'm considering connecting the PC to an ethernet switch and then from there connect each Arduino with an ethernet shield.

Which brings me to my questions. Are there any limitations I should be aware of, if I want to pursue this setup? Will controllings tens, or even a hundred, Arduinos at the same time be a problem? How about stuff like updating a specific Arduino on the network?

My current working prototype uses a Windows PC that connects to one of multiple Raspberry Pis, which then in turn communicates with a number of Arduinos via I2C, and updates them via USB. But if I'm able to do all this directly from the main PC to the Arduinos via Ethernet, that would be fantastic.

Thanks for reading, looking forward to any answers.

With a lot of devices on the ethernet, you may want to consider a private wire that is dedicated to those devices.  That is, a second ethernet port or a VLAN off a capable switch.

As the number of devices increases, and the number of simultaneous talkers increases, you will start getting contention.  Chances are a modern switch can handle this to some extent, but you were not clear on how much traffic you are planning on sending, or how often each device talks, or if it is centrally coordinated (aka "polled") or just speaking whenever.


arduino weather shield and wind speed I have Arduino Mega and Weather Shield. I want to calculate wind speed.

float get_wind_speed()
{

float deltaTime = millis() - lastWindCheck; //750ms

deltaTime /= 1000.0;

  float windSpeed = (float)windClicks / deltaTime; //3 / 0.750s = 4

  windClicks = 0; //Sıfırla ve yeni oluşan rüzgarı izle
  lastWindCheck = millis();

  windSpeed *= 1.492; //4 * 1.492 = 5.968MPH

 Serial.println();
 Serial.print("Windspeed :");
 Serial.println(windSpeed);

 return(windSpeed);
}

But when I run my code I see two windspeed value. First one is windspeed=0.0 or any value. Second one is windspeed=nan.

How can I make it better?

When debugging a problem like this one, print out values of the variables that the calculation depends on.

In this case, you may find that both windClicks and deltaTime are 0 or 0.0.  The IEEE 754 floating-point-operations specification dictates a result of NaN (not-a-number) for various zero over zero calculations.  It dictates a result of +Inf or -Inf for calculations like 7/0.0 or -13/0.0.  [See, for example, the stackoverflow question, Why does division by zero with floating point (or double precision) numbers not throw an exception.]

If arithmetic generates a NaN or +Inf result, subsequent arithmetic using that result will also produce NaN or +Inf results.

To deal with the problem, you could use deltaTime > 0 as a required pre-condition for calculation of windSpeed.  That is, have an if-statement protecting the calculation block.


Best way of storing extra data for Arduino project I am an arduino beginner and I am trying to make a speed camera alert system, it would start beeping if I am above the speed limit and getting close to the speed camera. There is this website where I can get all the data I need, coordinates, direction and speed limit of every 36000 speed cams in my country.

I would need some extra memory space to be able to store all this data, would an eeprom chip do the job? and would it be able to keep up with a for loop going through all those 36000 speed cam locations to check if i am close to it and above the speed limit?

Edit: since going through all those locations on a loop would be a lot for the processor to handle, someone recommended the creation of a temp file that would narrow that list down by direction, and when that direction changed it would recalculate that temp file. This is what I came up with:

void setup() {
  int tempDirection = gpsDirection;
  writeTempFile();
}

void loop() {
  //this will recalculate the temp file when the gpsDirection changes
  if(gpsDirection > tempDirection +5 || gpsDirection < tempDirection -5){
    tempDirection = gpsDirection;
    writeTempFile();
  }

  for(temp file){
    if(distance <= 100 && speed > speedlimit){
      //start beeping
    }
  }
}

void writeTempFile(){
  //this will write a temp file with every cam with a direction that's similar the gps direction
  for(each line of the file){
    if(gpsDirection + 10 > camDirection || gpsDirection - 10 < camDirection ){
      add cam to temp file;
    }
  }
}

EEPROM writes are limited to about 100k cycles.  They are for permanent or semi-permanent data (like your absolute speed threshhold - 120kmh, for example).

You should not store your speed camera base here.

Get a MicroSD adapter and save your data there.  Looping thru 36000 speed trap locations is going to put a toll on your processor and memory.  I recommend that you determine a binding box (+/- 2 degrees, for example) and save a temp file with only those traps inside the box.  recheck every time your position changes a full degree (N/S or E/W).

Notice: in some countries, Brazil for example, distributing information regarding speed trap locations is illegal (obstruction of justice).


I cannot get my code to play music in a or manner. I have to open one switch then the other. Music should play with either door open Problem is if I open the necklaceDoor first, nothing happens. I have to open the ringDoor first. That turns everything on. Then with the necklaceDoor open, the stepper motor will turn off and the lights and music will continue to play. But I want to be able to open the necklaceDoor first and play the music with the lights. I do not want it to matter which one is opened first. I also realized that if I can get an or statement to work within an and statement I could do away with the fourth if statement completely. Both ringDoor open and necklaceDoor open, as well as ringDoor closed and necklaceDoor open have the same outcome. Now if I switch the door states in the third if statement, I get necklaceDoor only plays audio after closed(original problem) but if both doors are open and then ringDoor is closed, the music will shut off after the stepper timer is done and then start again after necklaceDoor is closed?!?!?!?
#include <SD.h>
#include <TMRpcm.h>
#include <Stepper.h>
TMRpcm tmrpcm;

const int stepsPerRevolution = 2048;   //Number of pulses per revolution
const int ringDoor=2;                  //Ring door
const int necklaceDoor=7;              //Necklace door
const int relayPower=22;               //Turn relay on

Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {
  Serial.begin(9600);                         //Start connection with computer

  if (!SD.begin(53))                         //Chip pin on card
  {
    Serial.println("failed!");                //SD card did not read
    return;
  }

  tmrpcm.speakerPin = 46;                      //Speaker output pin
  myStepper.setSpeed(5);                       //Stepper speed
  pinMode(ringDoor,INPUT);                     //Check state of ring door magnetic switch, NO
  pinMode(necklaceDoor,INPUT);                 //Check state of necklace door magnetic switch, NO
  pinMode(relayPower,OUTPUT);                  //Relay enable for 12V LED
  digitalWrite(ringDoor,HIGH);                 //Make door closed read high on start up
  digitalWrite(necklaceDoor,HIGH);             //Make door closed read high on start up
  digitalWrite(relayPower,LOW);                //Make relay off on start up
}

void loop() {

  if ((digitalRead(ringDoor)==HIGH)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door and necklace door is closed, everything is off
    digitalWrite(relayPower,LOW);
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door is open and necklace door is closed, lights on, stepper motor spinning, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
    myStepper.step(stepsPerRevolution);
    delay(500);
    myStepper.step(-stepsPerRevolution);
    delay(500);
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door closed and necklace door open, lights on, stepper motor off, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==LOW))
  {                                                                                //ring door and necklace door open, lights on, stepper motor off, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
  }
}

Please and thank you to any and all who help. It is greatly appreciated.
Yes, I asked the the original question and the answer I received not only did not work, somehow neither latch worked anymore.

First of all, you have to find out how your magnetic switches work. Are they opened or closed if you attach a magnet to them? Do they behave the same or is one closed and the other opened if you attach a magnet?
Your code above is written for active LOW switches i.e. if the respective door is closed the switch is opened and therefore the logic level of the pin is HIGH. The level is LOW if the door is opened (activated; hence active LOW).
In order your code had a chance to work, the switches must be connect the right way: on one side connect them to GND and on the other side to the respective Arduino pin. If this is not the case, the code must be changed or the switches must be conneted the right way. You did not show us your schematic, so I can not check it for you.
Here is some code to try: But first find out if the switches you use are LOW or HIGH active. I also have no access to an IDE at the moment, so I can not try out the code. Take it as a hint on how to do it.
And one tip from a guy that does the job for 30 years now: Don't comment variables if their names say it all:
//  this sort of comments makes the code unreadable --V
const int ringDoor=2;                          //Ring door

I know it is a common behavior in the Arduino community, but don't write comments after a statement. In your code above I did realize that there are comment for the if statements only when I copied the code in my answer. Comments are only usefull if they say something new and can be read without problems.
#include <SD.h>
#include <TMRpcm.h>
#include <Stepper.h>
TMRpcm tmrpcm;

const int stepsPerRevolution = 2048;
const int ringDoor = 2;
const int necklaceDoor = 7;
const int relayPower = 22;

Stepper myStepper = Stepper( stepsPerRevolution, 8, 10, 9, 11 );

void setup()
{
  Serial.begin( 9600 );
  if ( ! SD.begin( 53 ) )
  {
    Serial.println( "failed!" );
    return;
  }

  tmrpcm.speakerPin = 46;
  myStepper.setSpeed( 5 );
  pinMode( ringDoor, INPUT );
  pinMode( necklaceDoor, INPUT );
  pinMode( relayPower, OUTPUT );

  digitalWrite( ringDoor, HIGH );
  digitalWrite( necklaceDoor, HIGH );

  digitalWrite( relayPower, LOW );
}

void loop() {

  // the following code works if both switches are LOW active
  // (i.e. LOW if the door is open)
  // if the "ringDoor-switch is HIGH active change
  // digitalRead( ringDoor ) == LOW to
  // digitalRead( ringDoor ) == HIGH
  // if the "necklaceDoor-switch is HIGH active change
  // digitalRead( necklaceDoor ) == LOW to
  // digitalRead( necklaceDoor ) == HIGH
  // and
  // digitalRead( necklaceDoor ) == HIGH to
  // digitalRead( necklaceDoor ) == LOW

  if ( ( digitalRead( ringDoor )     == LOW ) ||
       ( digitalRead( necklaceDoor ) == LOW ) )
  {
    // one of the doors is open
    digitalWrite( relayPower, HIGH );
    tmrpcm.play( "music.wav" );
    if ( digitalRead( necklaceDoor ) == HIGH )
    {
      // only the ring door is opend
      myStepper.step( stepsPerRevolution );
      delay( 500 );
      myStepper.step( -stepsPerRevolution );
      delay( 500 );
    }
  }
  else
  {
    digitalWrite( relayPower, LOW );
  }
}


Arduino IDE and subfolders I have a sketch with multiple source files and folders arranged like so. I've divided up the project like this to keep things clean.

|
\---project
    |   project.ino
    |   types.h
    |
    +---sub1
    |       gadget1.c
    |       gadget1.h
    |       gadget2.c
    |       gadget2.h
    |
    \---blarg
            foobar.c
            foobar.h

The sketch file includes the headers via quoted include directives (rather than the lib alternative with angled brackets). This seems to work for compilation.

However, when the IDE tries to link, all references to implementations (c source files) in the subfolders generate "undefined reference" errors. Almost as if the IDE is completely ignoring the C source files.

In trying to resolve this I've discovered that apparently the handling of subfolders by the IDE seems to be all over the place. Some versions only acknowledge headers in subfolders, others work if you put everything in a "src" folder (I've also seen mention of a "utility" folder), some people suggest modifying environment variables, etc. I've even tried manually adding source files via the "sketch/add file" option which makes the files visible in the IDE but does not solve the linking problems. All these methods seem to depend on IDE version, and I couldn't distill what was the correct way vs a hack or work-around.

So my question is what is the correct/current way of organizing the above project so that it can be compiled/linked using the IDE? I am using IDE version 1.8.5 which I believe is either the latest version, or close too it.

From Arduino IDE 1.6.10 onward the Arduino IDE compiles all source files in the src subfolder of the sketch and recursively through all folders under the src folder.

Support for compilation of sketch subfolders was added one or two IDE versions before 1.6.10 and was originally not limited to the src folder but a lot of problems were reported by people who had stored separate programs in subfolders of their sketch that caused compilation errors so this feature was restricted to the src subfolder only.

So if you structure a sketch like this:

foo
|_foo.ino
|_src
   |_bar.cpp
   |_bar.h

And use this #include directive in your sketch:

#include "src/bar.h"

it will work fine.

  Almost as if the IDE is completely ignoring the C source files.

Arduino sketches are converted to C++ before being compiled. They are not C. If you want to use C in C++ code you need to wrap it in extern "C" {}

extern "C" {
#include "src/sub1/gadget1.h"
}

  what is the correct/current way of organizing the above project

project
|_project.ino
|_types.h
|_src
   |_sub1
   |  |_gadget1.c
   |  |_gadget1.h
   |  |_gadget2.c
   |  |_gadget2.h
   |_blarg
      |_foobar.c
      |_foobar.h


How to debug MIDI input? I'm trying to receive MIDI messages on a Leonardo. To do that I used the circuit in the diagram below (only the top half for receiving). The only thing I did differently was using an 1N4148 diode instead of the 1N914. I connected GND to pin GND, 5V to pin 5V and RX to pin 0 (RX), and I used code below to see whether I do get any inputs or not. (I first started with some more complex code but it seems this is the minimal thing I can do.) As a MIDI source I used an Arturia Keystep which I tested on a midi instrument.

Unfortunately I don't get any input, and I don't know why. What I tried so far:

Verified the polarity of all cables, and made sure all connections work.
Swapped the Leonardo with a different one (both new).
Swapped out the 6N137 optocoupler with another one (both new).
Addded above the if-statement a Serial.println("test"); which then resulted in an endless avalanche of "test" in the serial monitor - just to check if the USB connection works.
Measured the voltage between pin 5 and 8 on the 6N137 and it is indeed 5V.

Is there anything obvious I'm doing wrong? What things do you suggest doing to try to find the bug? (I do have a multimeter but no oscilloscope.)

 (from this answer).

byte b;
void setup() {
  Serial.begin(9600); //USB
  Serial1.begin(31250); //MIDI
}

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

The solution:
On the image is stated plugs are solder-side. So swapping pin 2/3 does the trick


Connecting to WiFi on ESP32 using credentials from SD card I'd like to use an SD card to provide the login credentials to an ESP32. I've already got the ESP32 reading the relative data from the SD card and storing it as a char array on the ESP, but when I use those arrays in the WiFi.begin function it never connects.

Is this something to do with the way arrays work or am I doing something else wrong?

Respective code:

if (dataFile) {
Serial.println("File is available");
while (dataFile.available()) {
  byte currbyte = dataFile.read();
  if (currbyte == 58) {
    reading = 1;    //Begin reading data
    i = 0;
  }
  while (reading == 1 and s == 0) {
    byte currbyte = dataFile.read();
    //Serial.print(currbyte);
    //Serial.println(char(currbyte));
    if (currbyte == 13) {
      s = 1;
      reading = 0 ;
    }
    ssid[i] = char(currbyte);
    i++;
    //Serial.println(ssid);
  }
  while (reading == 1 and s == 1) {
    byte currbyte = dataFile.read();
    //Serial.print(currbyte);
    //Serial.println(char(currbyte));
    if (currbyte == 13) {
      s = 2;
      reading = 0 ;
    }
    password[i] = char(currbyte);
    i++;
    //Serial.println(password);
  }
}
dataFile.close();
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED and count < 20) {
Serial.println("Connecting to WiFi..");
delay(1000);
count++;}

you add the '\13' to the SSID and password string instead of the terminating zero, because ssid[i] = char(currbyte); runs for 13 too

use readBytesUntil()

  char ssid[33];
  int l = file.readBytesUntil('\n', ssid, sizeof(ssid));
  if (l > 0 && ssid[l-1] == '\r') {
    l--;
  }
  ssid[l] = 0;


Reading RFID tags with Arduino IDE, not using Arduino I am completely new to this technology, but I'm hoping to build a fairly simple program through the Arduino IDE that takes the serial numbers of RFID cards read through my ID-20LA Innovations RFID reader and send those serial numbers to an API endpoint all through the IDE (as in without using a physical Arduino).

Is this possible? Are there any tutorials out there that walk through a stripped down version of this? I don't know where to start code wise, and all tutorials I've found use physical Arduinos to accomplish this.

Short answer:
NO

Long Answer:

Option 1:
 Use a USB RFID reader and create a basic processing/python/ app to read from the USB RFID reader and post it where ever you want it to

Option 2:
Use the arduino to read from the ID-20LA and send the data via UART to your computer and then create a windows app using processing/python/ to send it to your API endpoint

Option 3:
Use the arduino YUN to read from the ID-20LA and then create a basic python program to run on the YUN itself. Such that it will read data from the atmel microcontroller (on the YUN) and post it to your API endpoint. This is a much cleaner yet slightly more expensive way of doing this.


SoftwareSerial Write to return Read in Serial Monitor? Hoping someone can help me out in my conundrum here...

I currently am testing the SoftwareSerial library out to understand how I may use it in my project.

I have a wire running from pin 6 to pin 9, so that the TX talks straight to the RX.

I have written the following:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(6,9); //RX = 6 TX = 9

void setup() {

  Serial.begin(1200);
  mySerial.begin(1200);
}

void loop() {

  mySerial.write('F');
  delay(100); // attempting to allow time between write and read commands

  while (mySerial.available()>0) {
  Serial.println(mySerial.read());
  }
}

The whole point is just to see 'F' return in the Serial Monitor.

The output, unfortunately, is absolutely nothing! If I omit the while(mySerial.available>0) I just get -1 's down the lines of the Serial Monitor.

Thank you in advance!

SoftwareSerial cannot talk to itself. Since it is implemented in software and not hardware it can either send or receive at one time, but not both.

Look at the code for write in SoftwareSerial:

size_t SoftwareSerial::write(uint8_t b)
{

...

  cli();  // turn off interrupts for a clean txmit

...

  // Write each of the 8 bits
  for (uint8_t i = 8; i > 0; --i)
  {
    if (b & 1) // choose bit
      *reg |= reg_mask; // send 1
    else
      *reg &= inv_mask; // send 0

    tunedDelay(delay);
    b >>= 1;
  }

...

  SREG = oldSREG; // turn interrupts back on

...

}

Since it turns interrupts off, and interrupts are needed for it to detect incoming data, therefore it cannot detect incoming data while it is sending.


Arduino EEPROM retains old data after flashing with a new program I have a custom 5V 16Mhz Arduino Uno (a breadboard Uno of sorts) that runs the grbl firmware. After the initial flashing I can see all the settings (through the serial monitor) and everything works. However, if I make any changes to the firmware files and re-flash it, I can see that the old settings values have not been replaced with the new ones. I can only assume that these values are in the EEPROM and are not being erased on every re-flash cycle. I then tried the eeprom_clear program from Examples in the Arduino IDE and then re-flashed with the new firmware settings, after which I can see the new settings values.

I did some digging and found that the EESAVE fuse is responsible for this. However the Uno does have this fuse bit unprogrammed (set to 1). Why then am I able to see the old EEPROM settings and have to explicitly run an eeprom clear program before re-flashing with the updated firmware?

Flash isn't EEPROM. When you reprogram the flash it doesn't touch the EEPROM.

It's controlled by the -U... flag to avrdude:

avrdude ... -Uflash:w:<hex file>

If you want to set the EEPROM to something specific you can use avrdude to program an EEPROM file if the bootloader supports it (not sure it does, so you may need a programmer for it):

avrdude ... -Ueeprom:w:<hex file>


question about progmem I have a problem understanding the following code:

PROGMEM  prog_uint16_t x={1232,3232,43343};
rawlen = pgm_read_word_near(x);
memcpy_P(uSendBuff, pfSendBuff+1, rawlen * sizeof(uint16_t));

Why do we need this? -

rawlen * sizeof(uint16_t));

Why not this? -

memcpy_P(uSendBuff, pfSendBuff+1, sizeof(rawlen));

Probably because x is an array of integers (although in the code you posted you miss the '[]'), thus memcpy_p should run over rawlen integers, each integer occupies sizeof(uint16_t) bytes, hence rawlen * sizeof(uint16_t) bytes in program memory space.


Casting custom shared_ptr object I am using custom shared_ptr class for some program on Arduino, and I need to do something like this:

shared_ptr<Base_class> b_ptr;
shared_ptr<Child_class> ptr((shared_ptr<Child_class>) b_ptr);

In my shared_ptr class I have three constructors:

shared_ptr() : pData(0), reference(0){...}
shared_ptr(T* pValue) : pData(pValue), reference(0){...}
shared_ptr(const shared_ptr<T>& sp) : pData(sp.pData), reference(sp.reference){...}

and some other stuff...
For casting I tried to write the following:

    template< typename T2 >
operator T2 * () const
{
   return (T2 *)pData;
}

and:

    template< typename T2 >
operator shared_ptr<T2> () const
{
    shared_ptr<T2> temp((T2 *)pData);
    return temp;
}

but can't get it to work.

For doing:

shared_ptr<Base_class> b_ptr;
shared_ptr<Child_class> ptr(b_ptr);

you have to use another constructor. If you take a look on this Example of shared_ptr implementation, you can see:

template<class U> shared_ptr(const shared_ptr<U>& s) ...

That's exactly the constructor, that takes shared_ptr of different type .

And similarly for assigment operator.


The ESP8266 connects to open WiFi hotspots, even If I supply a password This question is more out of curiosity, then out of a need to solve something.

I was trying out some experiments with the ESP8266 Arduino core when I realized that I had programmed an SSID and password for the ESP8266, but the WiFi that I had set up was an open network.

I tried going through the documentation and then the Arduino core source code, but couldn't find if WiFi.begin(ssid,passphrase) a function does this on purposes, as in it was designed that way, or did it just happen to work this way.

Also, I would like to know if there is a way to stop the ESP from connecting to an open network when the passphrase is provided.

It's probably by chance - however it's impossible to know.

Connecting is done by wifi_station_connect(), which is a function provided by the (closed source) ESP8266 SDK. So we can never know what it's actually doing.

However, the sequence is probably something like:

-> Connect
<- Ok, give me a password
-> Here it is
<- Right, you're connected

Or, with no PSK:

-> Connect
<- Right, you're connected

Although you specify the password (which just gets stored in the configuration) if it never asks for it then it just doesn't use it.

Can you force it? Not without knowing what's going on in the mystery wifi_station_connect() function.  There is nothing much in the documentation for the SDK that even hints at a clue.


Compatibility between Particle Photon and Arduino Is it possible to run Arduino on a Particle Photon?

I want complete software control over the device so I can connect it to the internet and do stuff without going through Particle's cloud, logins, etc.

You can use the new particle dev platform to do this https://www.particle.io/dev


SIM800L not registering to network I am using SIM800L module. I am new to GSM modules. I have searched in many web sites about SIM800L, every where they mentioned baud rate 9600 for SoftwareSerial but it is not working at all in my case. So I started a trail and error method to match baud rate. Finally I found that its baud rate is 38400. With baud rate of 9600 for Arduino and 38400 I am able to communicate with SIM800L.

The problem is that I am unable to register to network. AT+COPS=? shows all available networks. Using AT+COPS="value" I am able to select network. But after that the SIM800L module still blinks every second.

In loop() I am continuously reading software serial and it's printing the following:

RDY
+CFUN: 1
+CPIN: READY
Call Ready
SMS Ready
RDY
+CFUN: 1
+CPIN: READY
Call Ready
SMS Ready

The above data is continuously printing on console.

I am 90% sure it's a power issue. Not sure on what board/module you're using but the SIM800L/SIM900 needs a burst of current of 2 A during 577 µS (See the manual).

Try using 4700 µF and a 10 µF capacitor in parallel with the module. Powering it with a proper power source instead of the Arduino wouldn't hurt too.


Arduino Mega 2560 - TFT 3.5 Display is not working with libraries suggested I attached two images of the shield.

I bought an Arduino Mega 2560 R3 with a TFT 3.5 Display shield in China.

What I know from my research is:

There are no data sheets available in the Internet.
The factory's web site, in China, is in Chinese, and there is no information in English.
I achieved to know the factory is www.mcufriend.com, because it is the only reference in the shield.
Apparently the drive to use is R61581.
Using suggested libraries from Henning Karlsen (http://www.henningkarlsen.com/electronics/library.php)
(UTFT, UTFT Geometry, tiny Fat, UTFT Tiny Fat, UTouch and UTFT buttons) . These libraries don't work with this shield.
Some people say that this shield requires 3.3 [Volts] to work, but the Vcc pin connected goes to 5V and it contains a Voltage regulator. I suppose it drops the voltage from 5[V] to 3.3[V] in the middle of the back side of the screen shield (see the upper photo - U1).
The specs that I found, say that this is a 262,144 Color 320x480 Dot Graphic LCD screen using a LCD driver a Si TFT Panel.
This screen includes a touch pad and a Micro SD memory reader.
After using the geometry test included in the library folder UTF Geometry mentioned on #5, and using all the drivers found in the documentation included by Henning Karlsen in a .pdf doc, I couldn't get this shield to work.

Does anyone know how to make this screen work?

I know is too much technology involved to be a fake shield, but it should be very useful to have this working. Do you agree with me?

I have the same display. It has ILI9137 chip using 8-bit mode, so original Henning Karlsen UTF library doesn't work. You can find this library patched to support this display using Arduino MEGA at https://github.com/dgolda/UTFT

If display wouldn't work it is probably broken. I've received first piece broken - only backlight was working, but second and third was OK.


Using arduino Due for camera control Could the arduino Due take and send image data from 5MP camera module to PC in the following condition?

frame rate = 1fps
resolution = 2592 x 1944
format = 10 bit bayer raw RGB
interface : parallel ports (DVP) between camera and Due
           spi between Due and PC(or SD card)
FIFO(frame buffer): would not be used
SDRAM: would not be used
(But if it is needed, I would SDRAM via spi. Also I can use a frame buffer like AL422B. But if it is possible I would avoid using them.)

The camera would send 50Mbit image data per second and they will be transferred via 8 parallel lines(D0~D7) to the Due. And then they would go to PC directly or after passing SDRAM. But how can one evaluate if the 84Mhz is enough to do this job by calculation?

Arduino Due specs
https://www.arduino.cc/en/Main/arduinoBoardDue

camera module example (OV5642)
http://www.uctronics.com/cmos-camera-adapter-board-for-omnivision-image-sensor-p-248l.html
But this is not what I want to use. In my project I need to build a camera module and it would not include FIFO unless it's highly recommended.

So a quick feasability assessment:

2592 W * 1944 H * 10 bit = 50388480 bits

50388480 bits / 8 bit data bus = 6298560 packets

84000000 clocks per second / 6298560 packets = ~13 clock cycles per packet

I think that by itself, from a purely data perspective, without looking too deep into datasheets, you could feasibly read data from a port and push it out the USB port, and clock the data in less than 13 cycles. But what this means is you'd have to get into the nitty gritty of the processor and figure out how to do that as low level as possible because DigitalRead() and Serial.print() aren't going to cut it as they won't be fast enough.

The real challenge is that the above totally depends on being able to clock the data from the sensor yourself, which if I recall correctly, these sensors can actually be pretty picky about their clock.

I would highly recommend a FIFO, that way the sensor data can be clocked to it as fast as it wants to be clocked, and then you could read from the FIFO at your own pace as it will clock data out at exactly the rate you want it. Also 1 FPS is a pretty lofty goal if you are only a beginner. Like I said, it is probably possible, but it requires a lot of optimizations and planning that are not very straightforward to implement, especially if you are just starting out.


I have three pushbuttons where only one can be pushed at a time and want to set a variable for this. How? Basically I have three push buttons that correspond to pins 1 to 3 and want to set an efficient code that sets a certain variable into the index whose digitalRead is equal to one. Let us assume that only one button can be pressed at a time.
void loop()
    {
    if(digitalRead(1) == 1)
        {
        Variable = 1;
        }
    if(digitalRead(2) == 1)
        {
        Variable = 2;
        }
    if(digitalRead(3) == 1)
        {
        Variable = 3;
        }
    }

Is there are more efficient way to do this, like for example using other loops?
I can't wrap around my head with doing this concept using the other loops such as for, do while, while and switch because the nature of the idea feels so unconventional for their uses.

If you can only have one button pushed at a time, you can only end up with at most one of the if statements evaluate to true. In your code, you check button 2 and 3, even if button 1 is pressed. Your code can be a bit faster if you do this:
if(digitalRead(1) == 1)
{
  Variable = 1;
}
else if(digitalRead(2) == 1)
{
  Variable = 2;
}
else if(digitalRead(3) == 1)
{
  Variable = 3;
}


How to connect more than 10 sensors to Arduino uno r3 How I can connect more than 10 sensors to Arduino Uno R3? I calculated it and I can connect just 4 fire flame sensors (sensors which can find a fire (a candle, for example)) and maybe 1 ultrasonic sensor. I need more for my project. I need an IR Sensor, a fire flame sensor on every side, and 1 ultrasonic sensor in front. Additionally, I need to connect 2 DC motors, 1 fan, and 1 servo-motor for ultrasonic sensor. How can I solve this? I must buy Arduino Mega?

You can easily increase number of I/O pins using an expander, e.g. PCF8574.
The expander can be connect using your SCL/SDA pins located next to GND/AREF pins. (Here you can find detailed photo: http://forum.arduino.cc/index.php?topic=84190.0) You can connect up to 8 such expanders to extend the number of your digital pins to 64. Once you connect it, here is a code snippet of how to use it:

#include <PCF8574.h> //library available at: https://github.com/skywodd/pcf8574_arduino_library

void setup() {
  PCF8574 sensors;
  sensors.begin(0x20); //0x20 means that you connected A0, A1, A2 pins of PCF8574 to the ground
  sensors.pinMode(0, INPUT_PULLUP);
  sensors.pinMode(1, INPUT_PULLUP);
/*...*/
}
void loop() {

  byte sensorValue = sensors.digitalRead(0); //reads digital value of 1st sensor connected to pin 0 of PCF8574 expander
  /*...*/
}

You can read more with this tutorial (note: they are using wire interface, so the code will differ. Choose the one you prefer).


How to use Atmega328p-PU from an Uno, on a breadboard without a crystal How do you use Atmega328p-PU from an Uno, on a breadboard without a crystal?

You can use another IC like the 555 timers as an external oscillator.


Changing parameters of pulseIn() to sense different materials I have a ultrasonic sensor and in order to get the distance I use the pulseIn() function included in the arduino library, and then change it to distance. As the ultrasounds does not work equally in different materials as i have seen in Performance comparison of Infrared and Ultrasonic sensors for
obstacles of different materials in vehicle/ robot navigation
applications. My question is if there is a way of changing the pulseIn() to have different materials, function:

unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
{
    // cache the port and bit of the pin in order to speed up the
    // pulse width measuring loop and achieve finer resolution.  calling
    // digitalRead() instead yields much coarser resolution.
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    uint8_t stateMask = (state ? bit : 0);

    // convert the timeout from microseconds to a number of times through
    // the initial loop; it takes approximately 16 clock cycles per iteration
    unsigned long maxloops = microsecondsToClockCycles(timeout)/16;

    unsigned long width = countPulseASM(portInputRegister(port), bit, stateMask, maxloops);

    // prevent clockCyclesToMicroseconds to return bogus values if countPulseASM timed out
    if (width)
        return clockCyclesToMicroseconds(width * 16 + 16);
    else
        return 0;
}

or the countPulseASM, which I translate from the asembled code, which can have some errors) as:

// wait for any previous pulse to end
while ((*port & bit) == stateMask)
{
        if (--maxloops == 0)
        {
           return 0;
        }
}

// wait for the pulse to start
 while ((*port & bit) != stateMask)
{
    if (--maxloops == 0)
    {
       return 0;
    }
}

// wait for the pulse to stop
 while ((*port & bit) == stateMask)
 {
    if (++width == maxloops)
    {
        return 0;
    }
 }
return width;

Another way of doing that is having a correction factor while changing the time into the distance, but for that I shold have the differences of all the materials.

pulseIn just returns the length of a pulse on a pin. That has nothing to do with materials and can have no concept of materials. It is just time. You cannot change time just to suit different materials.

Instead if you want to calculate the distance depending on different materials you need the actual time of the pulse to then calculate the distance in different ways.

That is down to your sketch to do that calculation using the time provided by pulseIn and your own adjustment values.


Send sensor information to processing I am currently working on an Arduino project where the Arduino will send data to a processing program via bluetooth and processing will draw the data. However, my code doesn't seem to work.

Here is my Arduino code:

#include <SoftwareSerial.h>

int bluetoothTx = 1;
int bluetoothRx = 0;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

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

void loop() {
  Serial.println("Hello");
}

And here is my Processing code:

import processing.serial.*;
Serial myPort;

void setup() {
  myPort = new Serial(this, "COM42", 9600);
  myPort.bufferUntil('\n');
}

void serialEvent( Serial myPort) {
  String data = myPort.readStringUntil('\n');
  println(data);
}

I identified that the incoming port from the HC-05 module is "COM42" from my Bluetooth settings. I am expecting to see several "Hello" lines being printed on the processing console but this does not happen

Your whole sending program is a complete mess, sorry to say:

First you create a SoftwareSerial port using the HardwareSerial pins. (Why on earth would you do that?)

Then you "begin" that SoftwareSerial port.

Finally you try and print Hello through the HardwareSerial port!

Either use SoftwareSerial OR use the hardware UART. You can't mix and match both. And since you are using the hardware UART pins, why even consider using SoftwareSerial?

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

void loop() {
    Serial.println("Hello");
}

OR, to use other pins than 0 and 1:

#include <SoftwareSerial.h>

const int bluetoothTx = 2;
const int bluetoothRx = 3;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

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

void loop() {
    bluetooth.println("Hello");
}


How can I automatically get the time from the computer into an alarm clock (starts at 00:00 when plugged in)? Okay so I did this project from Fritzing first in my circuits.io project then on the arduino itself, it all works fine just how I wanted it.

But here is what I wanted to add, as you can see when you plug the arduino in it will set the time to 00:00 and you can adjust it yourself to the time right now, let's say 12:57. Then you put in the alarm so let's say you want to sleep an hour u put the alarm on 13:57.

Is there a way to automatically get the time from the computer? So you don't have to adjust it yourself everytime and start from 00:00.

Thanks for all the help!

There are several ways, and they are covered in the comments above.

The answer to your question. Via Arduino USB to serial interface. and a simple batch file on a windows computer example:

@echo off

set datetimef=%time:~0,2%.%time:~3,2%:%time:~6,2%

echo %datetimef% > COM5

COM5 is used as a example, your serial port can be another number.

The format in the example is hour.minute:second


Update Variable via Arduino to Arduino I2C I am attempting to send a simple 1 byte value from one arduino to another using I2C with the Wire library. From reading I see that this is typically done using the event monitor supplied by the Wire library, but this has caused problems for me because the handler function may only have one argument and it must be a void function or else the library throws errors during compilation. So I have a couple of questions about what is or is not possible with the Wire library short of modifying the source:

Should the Wire.available() function respond to attempted transmissions if the event handler referenced above does not exist? My first idea was to simply write my own function that would be called whenever this value is not 0, but it appears that this value never changes - unless the event handler is used.
Can you update variables which reside outside of a function from inside of the function WITHOUT passing those variables as pointer arguments? Because recall from above that I cannot pass any arguments besides the one specified for the number of bytes received.

I cannot understand how this library could be useful for Arduino to Arduino communication if it is literally not possible to use the transmitted values anywhere other than inside of the event handler. My next step is start modifying the source to suit my needs, but I would imagine what I'm describing is a basic thing and would be shocked to find out that it's not possible without modification.

I see now what the issue was. But to answer my questions:

Wire.available(); will not work if called outside of an event handler. I confirmed this while reading through the Wire.cpp source code and it explicitly states that the function should only be called from an event handler.
It is as simple as only a matter of updating global variables. I feel quite silly for not realizing that simply declaring variables outside of a function gives ANY function access to it rather than only the main function.

I see that the other answer mentions applying the volatile modification to the variables, but this is only necessary when the function in question is attached to an interrupt handler.


How to document a custom library in Arduino I have created my own library and it is working flawlessly. Now I want to add some documentation to it that the Arduino IDE can understand.

For the functions from the Arduino IDE itself like delay(ms) you can right click them and then select Find in Reference. How can I add this feature to my own library?

Arduino uses the keyword.txt file to highlight words and to define a reference page to keywords. But the reference page must be in reference folder of IDE installation and the keyword.txt contains only a filename, not the path.

  REFERENCE_LINK This field specifies the Arduino Language Reference page to open via Right Click > Find in Reference or Help > Find in Reference when the cursor is on that keyword. Generally it does not make sense to define the REFERENCE_LINK field for 3rd party library keywords since they are not likely to be in the Arduino Language Reference.

I have a library which implements WiFiClient and WiFiServer like the Arduino WiFi library, so I can link in keywords.txt to Arduino reference like this:

WiFiClient  KEYWORD2    WiFiClient
WiFiServer  KEYWORD2    WiFiServer
WiFiUDP     KEYWORD2    WiFiUDPConstructor

The names used are names of html files in Arduino\reference\www.arduino.cc\en\Reference.


Connecting LEDs and push buttons 12 feet away from Arduino UNO I have a PCB (let's call it remote PCB) on which I have 4 LEDs and 4 buttons mounted. The remote PCB is far away from my desk (about 12 feet away). The LEDs are used to indicate the status and the buttons are for various state inputs.
All of them are connected to UNO directly.

I am planning to use a 10 pin IDC connector and IDC ribbon cable for the same.
THe LEDs' current is about 2 mA each (white LEDs)
The push buttons will make a ground connection when pressed, else the internal pull-up of the UNO will keep the GPIO at a high level.
I have put a capacitor of 10 nF across the switch to address denounce.
I have a series resistor of 1-kilo ohm for all four Switches on the remote PCB

I would like to know if this is okay? Will there be any problem due to the length. The LEDs are for indication and won't blink faster than 200 ms at any point in time. They will be used to indicate status which is very slow signals.
Thanks in Advance!

That is a big no-no. You are adding extremely long antennas to the Arduino asking for problems. At a minimum on the inputs add a 10K series resistor at the Arduino pins.  My preference would be to put the capacitors at the arduino pins to help decouple noise etc as well as the pull up resistors on the wire side of the 10K resistors. Use a buffer of some type for the LEDs, a transistor would work. This may work but for how long and how many processors can you destroy over time.


Serial communication between PC and Arduino via RS232 using C++ I am trying to communicate with my Arduino Duemilanove via an RS232 cord. I simply want to be able to send a byte (or char) to my Arduino from a desktop application.  The Arduino is plugging into USB COM5 on my computer.  I have the RS232 plugged into COM1, and then I have pins 2, 3 and 5 on the other end of the RS232 connected to Arduino pins TX, RX, and GND, respectively.

I found a serial comm class for C++ at the following link: Arduino and C++ (for Windows)

I have added the .h and .cpp files from the above example as Serial.h and Serial.cpp (I think the example uses SerialClass.h and SerialClass.cpp, I just changes the names).

On my Arduino, I have the following code running:

// ARDUINO
char incomingByte = 0;

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

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, HEX);
        }
}

And my C++ program is the following:

// C++
#include <iostream>
#include <Windows.h>
#include "Serial.h"

using namespace std;

int main(void)
{
    Serial port("COM1");

    char* msg = "Hello Arduino!";
    int msgLen = strlen(msg);
    bool writeSuccess = port.WriteData(msg, msgLen);

    cout << "\n\n";
    system("PAUSE");
}

When I use the Arduino's serial port viewer to see what is bring printed, I'm getting very strange values that don't match what I'm sending (as far as I can tell).

When I send "Hello Arduino!", the arduino prints the following:

I received: FFFFFFAB
I received: 3A
I received: 3A
I received: A
I received: FFFFFFFA
I received: FFFFFFEB
I received: 6D
I received: 37
I received: 15
I received: 2D
I received: 23
I received: 21
I received: FFFFFFBD
I received: 0

This does not appear to be the correct hex for "Hello Arduino!", but I have no idea why it's not correct.  Does anyone have any clue what I'm doing wrong?

It because that in your c++ application you haven't explicitly mentioned serial port speed.
Mention the same baudrate which you have used in arduino here(c++).

Assuming that you have used rs232 to ttl converter, as you are getting some output,
Which in other case wouldn't as you would have already burned your mcu.


minIMU 9 and Arduino reading Gyro angle I'm using minIMU-9 https://www.pololu.com/product/1268 and I want to read pitch, roll and yaw angles. I applied this library https://github.com/pololu/minimu-9-ahrs-arduino but there is a slope when sensor is not moving or vibrating. How can i fix or compensate this. The y axis is angle in degree and x axis is time in seconds

Pitch

Roll

Yaw

I suppose "at desktop readings" means you have your sensor resting on the desktop so you where looking for a constant output value over the time. Well, there are some mechanical limitations about gyroscope's accuracy, resolution and external factor like temperature that make noisy or non-sense readings.

What you are obtaining from this library is a calculated orientation that carries or accumulate an error over time. Basically there is not a perfect algorithm to calculate orientation as at MEM's scale electrons still moving due to temperature and other radiations.

Solution depends on your application scenario: if your sensor will be most the time quite, maybe just mathematical compensate with inverted slope (about 4-5 degrees per minute) and look for more rapid changes to determine movement. If your application will be on constant move maybe it is not required any compensation. Trade off must be considered if both scenarios will take place on your application. Anyway, reading measures on your actual application will give you more clue on how to handle this.

Below the L3GD20's mechanical characteristics


Using multiple sensors on ESP8266 Wifi module I have an ESP8266 ESP-01 WiFi module.
I have a project where I need to use the following and send their data to a firebase database.

2x Force Sensitive Resistors(Sensor)

1x GPS module

My question is what GPS module can I use to send GPS location thru the ESP8266 Wifi module. My ESP-01 has only 2 GPIO. What should I do so I can use 2 FSR and GPS module at the same time send all 3 data to firebase realtime database.

Thanks

You really need something external to both provide the analog inputs for the force sensors and the serial communication for the GPS module.

The simplest "something" is another microcontroller.  Ideally one with two UART ports.

You can then:

Communicate between the microcontroller and the GPS with one UART
Sample the FSRs with the microcontroller
Format and send the data to the ESP-01 through the other UART

Using SoftwareSerial you chould just about do it with an Arduino Uno (though you'd have to disconnect whatever was on the hardware UART every time you wanted to program it), but ideally something with more UARTs would be better, such as a Mega2560.

A halfway house between the two would be a board based around the ATMega32U2 which uses a direct USB connection for programming leaving the hardware UART free to be used permanently. However you'd still need to use SoftwareSerial to emulate the second UART (maybe best for the GPS since it's then only used for receiving).


How can I know how far a button is pressed? I want to make a system that can count coins. The problem that I know have is that I need a way to detect the size of the coin.

The idea that I have is a beam that becomes smaller if you a inject a coin. The size of the beam depends than on the size coin. See it as a button that you can press a little bit or very deep.

But how can I know far the button (beam) is pressed?

Following on from Mark's comment, I'm not convinced that you can measure the size of the beam, using a single optical (analogue) device - generally optical switches, like other switches, are binary, either on or off, and as such would use one of the Arduino's digital inputs.

The type of (hypothetical) button that you describe, taking a mechanical analogue (rather than your optical beam example), would require the use of an analogue input pin, and your "switch" would actually be a linear potentiometer, i.e. a slider, or lever, and the analogue input could then measure the input voltage, which would be proportional to the amount that the button (or lever) has been pressed (or moved). However, the usual linear potentiometer is not spring loaded, so the button would not really have the usual expected push button behaviour, unless, of course, you rigged up some sort of spring loaded button, with a long throw, mechanically connected to a linear potentiometer.

An analogue version of this sort of set up, as far as I am aware, does not exist for a optical solution.

What you could use is a series of optical digital (not analogue) switches (or a single light source and a series of receivers), arranged in a line (perpendicular to the base along which the coin is rolled along) in such a way that they can detect the size of the coin*. If the light is broken for a particular detector, then you know that the radius/size/width of the coin is at least the same as that detector's distance from the base.

These optical detectors are then connected to a series of digital inputs, i.e. D5, D6, D7 and D8, and a series of if statements would enable your code to determine the size of the coin.

Assuming that the broken light beam results in a low, then the pseudo code would be something like this:

if D5 = low & D6 = high
 then coin is a cent
if D5 = low & D6 = low & D7 is high
 then coin is a nickle
if D5 = low & D6 = low & D7 = low & D8 = high
 then coin is a dime
if D5 = low & D6 = low & D7 = low & D8 = low
 then coin is a quarter

Obviously you would need a trigger when to take the "snapshot" of the coin passing the detector at the correct time, when it is fully blocking the lights, and not just partially blocking the light beams (which could result in a false reading).

* I have just realised that this is exactly what Jot described in his comment.


How can I reference an object from another file? I am trying to write some code to make it easy to add different buttons to a touch screen. I need each object to be a different object of class 'touchButton'. I'd like to be able to run a touchButton.Draw function, which in turn will run LCD library commands. Is there a way I could do that? Here is my source code:

TouchScreen.ino:

#include "touchButton.h"
#include <UTFT.h>
#include <UTouch.h>
#include <avr/pgmspace.h>
UTFT    myGLCD(ITDB32S, 38, 39, 40, 41);
UTouch  myTouch( 6, 5, 4, 3, 2);
extern uint8_t SmallFont[];

void setup() {
  myGLCD.InitLCD();
  myGLCD.setFont(SmallFont);
  myGLCD.clrScr();
  myTouch.InitTouch();
  myTouch.setPrecision(PREC_MEDIUM);
  myGLCD.fillScr(51, 51, 51);
  //what I want to be able to do:
  //touchButton Button1 (10, 10, 20, 20, 'p');
  //Button1.Draw();
}

void loop() {
}

touchButton.h

#ifndef touchButton_h
#define touchButton_h
#include "Arduino.h"
class touchButton {
  public:
    touchButton(int x, int y, int xs, int ys, char use);
    void Draw();
    int x1;
    int y1;
    int xsize;
    int ysize;
    char use;
    boolean toggle = false;
};
#endif

touchButton.cpp

  #include "Arduino.h"
  #include "touchButton.h"
  touchButton::touchButton(int x, int y, int xs, int ys, char myuse) {
    x1 = x;
    y1 = y;
    xsize = xs;
    ysize = ys;
    use = myuse;
  }

  void touchButton::Draw() {
    switch (use) {
      case 'p':
      //this is what I would like to have called from the main file.
      //myGLCD.drawRoundRect(x1, y1, x1+xsize, y1+ysize);
        break;

       default:
        break;
    }
  }

The best way is to provide the myGLCD object as a parameter to the constructor:

touchButton::touchButton(UTFT &glcddev, int x, int y, int xs, int ys, char myuse) {
  x1 = x;
  y1 = y;
  xsize = xs;
  ysize = ys;
  use = myuse;
  glcd = &glcddev;
}

Then in your header you provide a:

private:
  UTFT *glcd;

Your library code then uses the glcd pointer to the object:

glcd->drawRoundedRectangle(...);

Note the use of -> since glcd is a pointer to the object (as created by the & operator when it was assigned in the constructor).

Of course, as Miagma mentions, you need to ensure that anywhere that references any UTFT functions or objects has the UTFT.h header included or it won't know what you're talking about.

You can also do the same with the UTouch class - pass that object as a parameter, then each widget can have its own routine to deal with the touch events.

You can see all this kind of thing in action in the same context in the Widget class of my DisplayCore system for chipKIT boards:

https://github.com/MajenkoLibraries/DisplayCore/blob/master/DisplayCore/DisplayCore.h#L464
https://github.com/MajenkoLibraries/DisplayCore/blob/master/DisplayCore/DisplayCore.cpp#L1587


check string for specific characters? I am just wondering if it is possible to check a string for specific characters.  For example if my string is String mystr = "test"; and I wanted to check for the letter t at the beginning and if it is NOT there do something how would I go about this?

I have read about string.startsWith(string2); however it returns true or false, I want to be able to do "XYZ" if "ABC" isn't satisfied, and it would seem that string.contains isn't a thing.

To paraphrase, I am trying to create an if statement that will evaluate if a string starts with a certain character(s) and will do something if this condition is NOT met.

Have you tried the following?

if(!actualString.startsWith(expectedString)) {
  // do whatever you have to
}

BTW, that is what actually suggested in @EdgarBonet's comment.


FastLED not performing as expected I'm fairly new to working and programming with arduinos. The project I am working on is a digital clock which uses a string of WS2812 leds to light up the correct numbers. Each digit consists of 7 leds and there are two 'colon' leds between the second and third digits. I am using the FastLED library to try to program the code. I am able to make the leds light up such that all four digits are the same number (four consecutive 5's). However, the second I try to have it display multiple different numbers, everything goes south quickly. Here are some pictures of my current results:

55:55. I can create this with any number 0-9.

Should be 12:34.
Here is the code that I'm working with so far:
#include <RTClib.h>

RTC_DS3231 rtc;
DateTime now;

#define NUM_LEDS 30
#define LED_PIN 6

CRGB leds[NUM_LEDS];

void setup() {
  // put your setup code here, to run once:

  Serial.begin(57600);

  FastLED.addLeds<WS2812, LED_PIN>(leds, NUM_LEDS);

  FastLED.clear();
}

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

  const int ZERO[]={0,1,2,4,5,6};
  const int ONE[]={2,6};
  const int TWO[]={0,1,3,5,6};
  const int THREE[]={1,2,3,5,6};
  const int FOUR[]={2,3,4,6};
  const int FIVE[]={1,2,3,4,5};
  const int SIX[]={0,1,2,3,4,5};
  const int SEVEN[]={2,5,6};
  const int EIGHT[]={0,1,2,3,4,5,6};
  const int NINE[]={2,3,4,5,6};

  for(int i=0; i<sizeof(ONE);i++){
        leds[ONE[i]]=CRGB::Red;
        FastLED.show();
      }

  for(int i=0; i<sizeof(TWO);i++){
        leds[TWO[i]+7]=CRGB::Red;
        FastLED.show();
     }

  for(int i=0; i<sizeof(THREE);i++){
        leds[THREE[i]+16]=CRGB::Red;
        FastLED.show();
      }

  for(int i=0; i<sizeof(FOUR);i++){
        leds[FOUR[i]+23]=CRGB::Red;
        FastLED.show();
      }

Can anyone explain what's going wrong? Any help would be greatly appreciated. Let me know if you need clarification!

Your problem is your usage of sizeof(). It doesn't do what you think it does.
sizeof() gives you the amount of memory a variable takes up. It does not give you the number of elements in an array.
For example:
const int ONE[]={2,6};

sizeof(ONE) will not give you 2. It will give you 4. An int is two bytes in size (16 bits). An array of 2 ints is, therefore, 2x2 = 4 bytes.
So when you're iterating over a 2 byte array but counting 0-3 you're overflowing your array and reading from the next bits of memory - which happen to be the first two entries of the TWO array in this case.
To get the number of entries in an array you must divide the sizeof() by the size of the variable type the array is made up of.  The most common way of doing that is:
sizeof(ONE) / sizeof(ONE[0])

It's common to set up some macros at the time of array creation so you can easily refer to it later:
const int ONE[]={2,6};
#define ONE_SIZE (sizeof(ONE) / sizeof(ONE[0]))

You should also consider using an array of byte (or better, the standard uint8_t) where the size of one element will be 1 not 2, since you don't need to store any number > 255. It's still good to do the division of the sizeof() even with a 1 byte size in case you should ever need to change the variable type in the future. It's also a good habit to get into.


2 stepper drivers speed control I'm using two tb6600 to control two step motors. It's for letter writing cnc machine.
Moving single axis works fine.
I want to push 2 steppers in the same time along a diagonal.
I tried to calculate ratio x:y, so if x is making more steps than y for 1 y do n x steps. This worked, but machine was shaking no mater how i adjusted delays between step high and low. When i use PWM there is no shaking, but i can't figure out how to make it follow diagonal.
Second try was to use PWM with analogWrite.
if(delayX > delayY){
      analogWrite(stepPinX, 128);
      analogWrite(stepPinY, 128);

      delay(delayY);
      analogWrite(stepPinY, 0);
      delay(delayX - delayY);
      analogWrite(stepPinX, 0);

    }else if(delayX <= delayY){
      analogWrite(stepPinX, 128);
      analogWrite(stepPinY, 128);

      delay(delayX);
      analogWrite(stepPinX, 0);
      delay(delayY - delayX);
      analogWrite(stepPinY, 0);
    }

This doesn't works obviously. It reaches end point, but it doesn't follow diagonal.
If i set duty cycle to 2 or 128 it doesn't matter.
Isn't duty cycle supposed to change speed of stepper motor?
What am i missing here and how can this be done?

Changing the duty cycle does not change the frequency of the PWM signal.
The tb6000 needs a pulse to trigger a step of the motor. If the frequency does not change the pulses per second do not change too and thus the speed is constant.
If you control just one motor the method of using delays to control the frequency works.
But in the case of two motors with different speed you need counter variables to immetate two frequencies (speeds) you need to control each speed of the motors.
First you caculate the ration of the speeds (you said y=1 and x=n steps. Then, the ratio is n:1, i.e the X Motor is faster then the Y Motor by factor n).
The following is just an incomplete example to explain my idea.
int cntX = 0;
int cntY = 0;

// I don't know you value n
// Let's say n=5
int ratioX = 5;
int ratioY = 1;

// One step per second at max speeed
// choose whatever fits your needs
int delayForMaxSpeed = 1000;

const int stepPinX = 5;
const int dirPinX = 2;
const int stepPinY = 6;
const int dirPinY = 3;
const int enPin = 8;

void setup()
{

  pinMode(stepPinX,OUTPUT);
  pinMode(dirPinX,OUTPUT);
  pinMode( stepPinY, OUTPUT );
  pinMode( dirPinY, OUTPUT );

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

}

void loop()
{
  // Enables the motor to move in a particular direction
  digitalWrite( dirPin, HIGH );

  countx++;
  county++;

  if ( countX >= ratioX )
  {
     countX = 0;
     digitalWrite( stepPinX, HIGH );
  }

  if ( countY >= ratioY )
  {
    countY = 0;
    digitalWrite( stepPinY, HIGH );
  }

  delayMicroseconds( 500 );

  digitalWrite( stepPinX, LOW );
  digitalWrite( stepPinY, LOW );

  delay( delayForMaxSpeed );
}


Creating an array, assigning a value to each indices, and assessing the array I am trying to create an unassigned array of size 512 and then assigning a reading to each indices. I want to get the start time before and after the loop and only run it once. Then I want to know how to retrieve the readings and serialprint the values after the loop. So far this is what I have but I don't think it is running as I want it to. I was able to get the start time but I'm not sure if it is running afterwards. Any help is greatly appreciated. Thanks!

void setup() {
int Vs[512] = {};
int analogPin = A0; // turn pin A0 on
pinMode(9, INPUT);
Serial.begin(9600); // setup serial
analogWrite(9, pow(2, 7)); //LED power 0
int time = micros();
Serial.println(time);
}

void loop() {
int i;
for (int i = 0; i <= 511; i++); { //loop setup for 512
int c = analogRead(A0) * (5.000/1024.000);
int Vs[i] = {c};
Serial.println(Vs[i]);
}
int stoptime = micros();
Serial.println(stoptime);
}

void stop() {
while(1);
}

There are multiple issues with your program. The most obvious is that,
if you define a variable multiple times, you end up with mutliple
different variables that share the same name. For example:

void setup() {
    int Vs[512] = {};  // this Vs is local to setup()
}

void loop() {
    int i;  // this i is local to loop()
    for (int i = 0;  // this other i is visible within the for loop only
            i <= 511;
            i++)
        ;  // this is the body of the for loop
    {
        ...
        int Vs[i] = {c};  // this Vs is local to loop()
    }
}

Another issue I pointed out in the snippet above is that a semicolon by
itself is an empty (i.e. do-nothing) statement. Thus you for loop is
empty.

There is no point in defining a constant such as analogPin = A0 if you
don't use it.

The value returned by micros() is not an int, it's an
unsigned log.

If you store a voltage in volts in an int, you get a very poor
resolution of one volt. You could store in a float, but that would
fill up the memory of your Arduino. I would rather store the raw
readings, and convert to volts only for printing.

Serial.println() takes time, and you are doing this during the timed
part of your code, which is probably unintended.

Here is a version of your program that may better reflect your
intentions. It takes 512 analog readings, stores them in an array, then
prints them and reports the time taken to do the readings. Then it waits
for one second and repeats the whole thing again.

const uint8_t analogPin = A0;
const int readings_count = 512;
int Vs[readings_count];

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

void loop() {
    // Take a run of analog readings.
    unsigned long start_time = micros();
    for (int i = 0; i < readings_count; i++) {
        Vs[i] = analogRead(analogPin);
    }
    unsigned long stop_time = micros();

    // Print the readings.
    Serial.println("Voltage readings:");
    for (int i = 0; i < readings_count; i++) {
        Serial.println(5.0/1024 * Vs[i]);
    }
    Serial.print("Data recorded in ");
    Serial.print(stop_time - start_time);
    Serial.println(" µs");
    Serial.println();

    // Wait before the next run.
    delay(1000);
}

If you really want to run only one iteration of the process, then you
can just replace delay(1000); by exit(0);. Alternatively, move the
body of loop() to the end of setup(), and keep an empty loop().


i need help my coding for my fyp how my coding works = 1 rfid card detect on first rfid reader and 2 rfid card detect on second rfid reader after that servo go to 90
my second rfid not detect
this is my coding
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
Servo  myservo;
int pos = 0;
int angle = 0;
int angle11 = 0;

#define RST_PIN2           8          // Configurable, see typical pin layout above
#define SS_PIN           9          // Configurable, see typical pin layout above
#define SS_PIN2          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN2 );   // Create MFRC522 instance.
MFRC522 mfrc522_2(SS_PIN2, RST_PIN2);   // Create MFRC522 instance.

void setup()
{
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin();        // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  mfrc522_2.PCD_Init(); // Init MFRC522 card
  Serial.println("Approximate your card to the reader...");
  Serial.println();
   myservo.attach(5);

}
void loop()
 {

// Look for new cards

if ( ! mfrc522.PICC_IsNewCardPresent()) {

return;

}

 // Select one of the cards

if ( ! mfrc522.PICC_ReadCardSerial()) {

return;

}

// Dump debug info about the card; PICC_HaltA() is automatically called

mfrc522.PICC_DumpToSerial(&(mfrc522.uid));

  delay(1000);
  // Look for new cards

  if ( ! mfrc522_2.PICC_IsNewCardPresent()) {

    return;

  }
  // Select one of the cards

  if ( ! mfrc522_2.PICC_ReadCardSerial()) {

    return;

    mfrc522_2.PICC_DumpToSerial(&(mfrc522.uid));

  }

  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "09 99 55 B2") //change here the UID of the card/cards that you want to give access
 {
String content= "1";
  byte letter;
  for (byte ii = 0; ii < mfrc522_2.uid.size; ii++)
  {
     Serial.print(mfrc522_2.uid.uidByte[ii] < 0x10 ? " 0" : "1 ");
     Serial.print(mfrc522_2.uid.uidByte[ii], HEX);
     content.concat(String (mfrc522_2.uid.uidByte[ii] < 0x10 ? " 0" : "1 "));
     content.concat(String (mfrc522_2.uid.uidByte[ii], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "09 99 55 B3") //change here the UID of the card/cards that you want to give access

      myservo.write(angle); delay(3000);
   for(angle = 0; angle > 90; angle11)
    myservo.write(angle11);
    delay(3000);

    myservo.write(angle11); delay(3000);
   for(angle = 90; angle11 > 0; angle)
    myservo.write(angle);
    delay(3000);
    }

 else
 {
    Serial.println(" Access denied");
    delay(3000);

    }
  }

Right at the start of your loop you have this (and other similar constructs):
if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
}

That means that if no new card is present on reader 1 then the rest of the loop is ignored. Nothing else can happen.
You need to restructure your whole program so that it works in the complete opposite way - instead of saying "If there's no card do nothing" you should say "If there is a card then do something".


What to do with Arduino floating pins? I have some unused pins, should I connect them together and to the ground or leave them floating?

The simplest thing to do is set them to INPUT_PULLUP.  If you want a purely hardware solution then you could connect them to GND through some resistors (10kΩ or whatever you have in that kind of order of magnitude will do).

You don't want to just tie them directly to ground, and you don't want to link them directly together - that could lead to short circuits and dead IO ports if any of the pins happened to get set as output and HIGH in software.


are 3 connections necessary for a push button? I'm referring to the 5th circuit (see below screenshot) of the sparkfun manual came with the arduino uno. Instead of connecting all three of the (+) (-) and the digital pin to each push button, can I just connect the (-) through the resistor and the digital pin?

Also a side question, in terms of physics, you need two ends to be connected in order to create pressure for the flow of electrons, but the digital wire for each push button that goes out to the arduino board doesn't have its own ground wiring that suppose to create the pressure as a couple. How to cope with that in terms of electron flow?

You can use the internal pullup e.g.

pinMode(inPin, INPUT_PULLUP);

Then wire your switch between pin and Gnd.