text:
how can i conect a lipo charger to a teensy 4.0?
I have the battery charger product https://www.adafruit.com/product/2124
and a teensy 4.0, that I would like to use to power it.
what, if any pin would I connect from bat, to the teensy?
Its my understanding that the Lion backpack is a voltage regulator, and thats it. it takes Vin, ground, and Vout.
I understand the 5v output goes to the 5volt pin of the teensy.
the gnd goes to gnd. should Vin go someplace? Or should I leave it off?
Please assist.

the charger does not have a Vin pin

The output voltage of the charger board is marked with BAT. You should connect it to the Vin pin of the Teensy, which then will convert the batteries 3.7-4.2V down to 3.3V.
Of course you need to connect the grounds of the charger board and the Teensy (on the charger board ground is marked with G).
The 5V pin on the charger board is no output. The board does not give you 5V. This is actually the pin for the charging voltage, which is 5V. Here it depends on how you want to charge the battery. If you use an external source, you can simply connect it's 5V to the board. If you want to use the USB jack of the Teensy, you can connect the boards 5V to the Teensys 5V. But: Be sure to cut the little trace between Vin and VUSB/5V at the back of the Teensy. You don't want to connect the battery voltage with an USB power source.

I was going back and forth on that. I didnt want to smoke my teensy experimenting, and I couldnt find clear statements on that. I hooked it up that way, and it totaly worked though. A side note, the teensy has a tutorial on cutting vin away from a pad connected to VUSB. VUSB has a through hole via though. I cut the trace between the via and the VUSB pad, giving me a larger pad to solder to. I would have preferred a via for VIN, but using 2 pads seems to make a pretty solid connection.


text:
How to multitask with interrupts on Arduino?
I am trying to build a cashless RFID based water dispensing unit. I am using Arduino mega 2560, PN532, relay, flow sensor. Here is the flow of the program in I2C mode; I have two functions, one to scan the card and the other for the flow sensor. As soon as the RFID card is placed on the NFC module, data stored in the card (i.e, date of expiry and balance amount) is obtained and is checked for validity. If the card is valid, then the relay is turned on. A flow sensor measures the quantity of water dispensed. As soon as the limit of 1000 ml is reached, the relay is turned off. The whole process happens serially, when the card scanning is complete, it waits for the entire 1000 ml of water to be dispensed. What I want to achieve is after one card is scanned, 1st relay with the flow sensor has to be turned on and simultaneously the scanning of the second card has to begin. If the first relay is busy, second relay has to be assigned to it. Can I achieve this using Arduino Mega? How do I manipulate the atmega to perform all these tasks at once?

BlinkWithoutDelay from the Arduino IDE samples is your friend.

Here's a really thorough write-up I did on how to do bare metal (like Arduino usually is) cooperative multi-tasking: https://stackoverflow.com/a/50032992/4561887

You do not necessarily need a build a "multitask with interrupts on Arduino".  Instead consider using a state machine.  First define the problem by drawing a state diagram:

Consider all state you wish to be in.  Including your example "...after one card is scanned, 1st relay with the flow sensor has to be turned on and simultaneously the scanning of the second card has to begin...".  Once you have defined all states and the rules that need to be tested for before jumping to a new state you can start programming your state machine.
There are plenty of tutorials including this one on the web specifically for people who want to implement a state machine on an Arduino.  But, briefly, you will want to create a loop that will execute with out stopping over and over again as fast as possible.  This loop will (1) know what the current state is and (2) will repeatedly test to find out if the program can change to any of the possible next states. When you change states is when, if you need to, you perform tasks such at turning the water on or off.
If you forsake the state machine and only use interrupts, testing the code tends to be very difficult.  As controlling exactly when an interrupt occurs relative to other interrupts and the state of the processor becomes problematic and nearly impossible to reliably repeat.  This is why the state machine is suggested. Interrupts can still detect external events. But by using a state machine the program is in control of what happens next. Instead of leaving it up to luck.

I tried implementing the state machine for my program. It helped me get to the solution. Thanks a lot. Cheers!

You are welcome.  Please choose the best answer to your question so that others with a similar problem can find your question and an appropriate solution.  Comment if nether solution is the best answer - telling us how to edit the answer to make the overall question & answer better.

As you mentioned, I designed a state diagram. Hence, it was clear to me in which state each component had to be at a particular time. I ensured that the program did not have to wait for anything to continue. I got the solution by simply manipulating the interrupts used by the flow sensors to make them function almost at the same time. However, I did not entirely implement the state machine program on my arduino. Designing the state diagram helped me get to the solution.

Glad the answer helped.  Now I have a question for you:  Since it sounds like you implemented your solution using only interrupts, how easy was it to test?  And are you sure you tested every situation?  Are you willing to ride a rocket ship or drive a car running your code?  I'm trapping you.  The answer?  It is very hard to test all situations when interrupts are involved.  That is why I suggested the state machine.  You can still detect situations using interrupts.  But using a state machine means you are in control of what happens when.  Instead of leaving it up to luck.

Thanks @st2000. You do have a valid point. I will try to implement it using state machines to have control over the program.

There is no real multitask on Arduinos. The Arduino can only do one thing at a time.
But, you can do things sequentially, one after another, so fast, that a human will think, that it happens simultaneously. This involves a non-blocking coding style, which needs no interrupts

Every delay in your code (at least the long onces) need to be removed. if you want to do timed things, you should use the coding principle from the BlinkWithoutDelay example, that comes with the Arduino IDE.
Also no function should wait for something to happen. Think of a function, that waits for a command from the serial interface. Blocking code would wait indefinitely, until a command was received, preventing any other code from execute. Instead the function could exit fast, when there is currently no command to process, leaving time for the other code to execute.

The whole principle relies on the loop() function executing very fast, so that your code can still be reactive. This works for most of the situations. Only sometimes you need to react that fast, that you need interrupts. Your usecase doesn't seem to belong to the interrupt needed faction.

Thank you for helping me out! I removed all the delays in my program and got the code working just right.

@Riya Please mark one answer that fits you most. This will help others seeking for help on similar problems.

source: Stack Exchange

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

sort: votes


text:
Internet switching
is it possible to switch internet connection from esp8266 wifi module to gsm sim 900A internet if the arduino detects that the esp have no internet connection and vise versa? Thanks

yes, it is possible.

Thank you!, can you guide me how to do it? I'm stuck in this situation, please

What did you try and what happened? Show your code please!

https://arduino.stackexchange.com/tour

@TimeGold, your question asks a simple yes/no confirmation ... if you actually need help with your code, then you need to rewrite your question

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


text:
Increasing ESP32 AP max connections
It has already been asked how many clients can connect to an ESP32 AP, but the answer is far from clear; the best one is from a year and half ago (ESP32 AP max connections: 4 or 10?) :

The answer is as clear as any other EspressIf configuration data, it is 4 or maybe 5, or 8, or 12, 16 or even 20 (the same as a ESP8266!)

As I'm trying to move a project from the ESP8266 because it does not have enough AP connections, two questions can be asked :

what is the maximum number of AP connections supported by the 4.0 ESP-IDF framework ?
can it be increased in any way ?

Thank you.

After some extensive testing with several modules (not just blindly trusting the documentation), here's what I found.
Short answer : maximum 10 AP connections for the ESP32 running ESP-IDF 4.0 (updated around 1st of march 2020), and no, it can't be increased (easily).
Details :

The maximum number of AP connections is defined somewhere in libnet80211, and can't be modified since I have no access to the source code.
when the 11th station tries to connect, libnet80211 prints I (39682043) wifi: max connection, deauth!, more or less like the ESP8266 for the 5th station
Changine the ESP_WIFI_MAX_CONN_NUM (defined in esp_wifi_types.h:258) from 10 to anything else ends up in unpredictable behavior (I'm labelling this as unpredictable since without the libnet80211 code, it can't be reliably assessed).

I'm not giving up on increasing the number of stations yet, so maybe there'll be an update to this answer.

According to the documentation:

uint8_t max_connection
Max number of stations allowed to connect in, default 4, max 4

The WiFi interface and AP can support up to 10 connections in its internal structures, but that is only practical for WiFi Mesh usage (which doesn't use all 7 layers of the ISO model), and for actual WiFi station connections, which entails the allocation of far more resources (IP addresses, ARP tables, etc) only a maximum of 4 are supported.
If you need more connections I suggest you invest in a real access point / router which can deal with the network management for you (i.e., an access point or router which can do the DHCP and other networking housekeeping for you, leaving your ESP32 free to be a simple station).

this is copy-paste from esp8266 doc

No, it's a quote from the ESP32 documentation. Hence the link to the ESP32 documentation.

Yes, it’s a quote from the documentation, but how reliable is the documentation ?

If you search in the ESP-IDF files you will find ESP_WIFI_MAX_CONN_NUM=10,

It looks like in 2016 they changed from a linked list to a static array for storage of connected stations. Since then the size of that static array has changed. For some reason the define started as 8, but the array was created as 8+2. Then the define changed to 10 and the array was also created directly from that define instead of adding 2. No idea what the significance of the "+2" was.  However, the 10 is not for wifi. The 10 is for mesh. How many connections it supports, and how many are allowed are different things. The WiFi itself can support 10, which is fine for mesh use, but ...

... for actual processing of connections it's limited to just 4 connections, since active connections to the IP stack use more resources.

Thank you for the explanation.
But the second question still stands ... can it be altered in any way ?

@stefanu Probably not. If the IDF limits it then there's not a lot you can do. You could try manually configuring the AP mode (incidentally I notice in the ESP-IDF code for doing that it's actually setting the number of connections to 5...) or adjust start_wifi_ap and see if that works. It may not though, since you may run out of memory

Thank you for the info; I'm in the process of replacing the ESP8266 with the ESP32 and I will soon be able to test the AP limits (as soon as I receive more chips to test with).
I will get back with the results.
What I've been able to test so far is that changing the
#define ESP_WIFI_MAX_CONN_NUM 10
to
#define ESP_WIFI_MAX_CONN_NUM 16
then rebuilding everything, does change the sizeof(wifi_sta_list_t), so ... maybe... just maybe ... there's a chance.

@Majenko : well...the documentation is WRONG ! Without any hacking at lower levels I was able to connect 8 stations in APSTA mode. On the other hand, changing the ESP_WIFI_MAX_CONN_NUM to a greater value produces strange behavior (for instance esp_wifi_ap_get_sta_list fails miserably). I will get back once I have more modules to play with.


text:
arduino connection to mysql fails
I tried to connect xampp/mysql to arduino but connection fails.
mysql is running on port 3306.
I searched a lot on the internet but could not understand where is the problem!
Would you please help me...
#include <Ethernet.h>
#include <MySQL_Connection.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(127,0,0,1);  // IP of the MySQL *server* here
char user[] = "root";              // MySQL user login username
char password[] = "";        // MySQL user login password

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(9600);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    delay(1000);
     Serial.println("Connection stablished.");
    // You would add your code here to run a query once on startup.
  }
  else
    Serial.println("Connection failed.");
  conn.close();
}

void loop() {
}

you forgot to put in the server IP ... 127.0.0.1 is not a network IP

I also try my pc IP but didn't work . Did you mean that?

i meant only what i said, that the IP you provided is invalid .... you said nothing about the MySQL server, so no comment can be made about the server

Sorry I didn't understand it. So which IP should I set to work?

you need to use the IP of the MySQL server ... you also have to make sure that the server can be reached .... use another computer to verify that .... the setup and verification of the MySQL server is not related to the Arduino, so don't ask about it here

how can I understand what is my MYSQL IP ? Is it different from my pc IP?


text:
Dynamically control the output voltage of a 60V DC input
I am hoping to control a 60V DC input source dynamically using my Arduino so that the output voltage could vary between 0v to 60v. At first i was looking into digital potential meter, however I couldn't find any digital pot that can support 60V DC input voltage.
I have came across a few articles with similar situation (but theirs with lower voltage).
Could anyone suggest any solution to my problem?
Thanks. Any help is much appreciated.

You could use a 5V digital pot, or a 5V DAC. Then feed that through an OpAmp to convert the 0-5V to a 0-60V output.

@Gerben could you guide me on how to design /which kind of opAmp that can step up from 5v to 60v? I tried googling but none of them step up from 5 to 60. Thanks in advance

Try asking at https://electronics.stackexchange.com/ . This isn't really my area of expertise.

Does your voltage source just have to output a voltage or does it need to drive any significant current (i.e. do you want to use it as a power supply)? BTW please be careful with these relatively high voltages. They can easily damage your Arduino and can be very unpleasant to touch.

@StarCat thank you for your comment, i am looking at a current around/less than 0.1 A

Try ZMPT101B. Easy to use and very cheap
Active Single Phase Voltage Transformer Module AC Output Voltage Sensor for Arduino Mega ZMPT101B 2mA

Can this be used to control output voltage real time?

I don't see how this answers the question. This module does not do what @jetjetboi wants. I would also advise against buying a random module off aliexpress with no documentation.


text:
Why does my Arduino 3.3v fluctuate?

For some reason, my 3.3v on my Arduino is fluctuating a lot, and I am not sure why.
The multimeter is measuring dc voltage and is connected between GND and 3.3v of an Arduino Mega.
The multimeter works fine. Connecting between 5v and GND gives 5V on multimeter.

the video is meaningless ... it does not show what you are measuring

Im measuring DC voltage between gnd and 3.3v

@jsotola can you tell me what information I should include?

you have to disconnect everything from the board, upload a blank sketch and measure it again.

Tried that still fluctuated

First check your connections. Otherwise: broken 3.3V regulator or too much load on the 3.3V supply.

Change the batteries in your meter. Try measuring things with your oscilloscope rather than your meter.

What happens if there is a load on the 3.3V rail. It kind of looks like the point you are measuring is floating/not connected. Try adding a 1kOhm resistor between 3.3V and GND, and remeasure. If it's indeed floating you should read 0V. Also try a different GND pin, just in case.

Arduino output voltages may "fluctuate" a few mV but what you showing us in that gif is really unstable.
What you should be doing is:

Disconnect everything from Arduino except the power source
measure the voltage again;

Is it stable? the problem was because of pulling too much current that causing voltage drop and instability .
Is it unstable?

Try checking with another MM and/or change auto-range to manual.

Is it stable when measuring the voltage with another MM? something was wrong with your previous MM.
Still unstable?

Connect the Arduino to a 9V power adapter and disconnect the USB cable.

Measure the voltage again, if it's stable the problem was because of some error in the cable or USB power source.
Voltage is still unstable?

change the 3.3V voltage regulator.

It should fix the problem if not report back to do some more in-depth problem solving.

My voltage Reg was off I should have tested before asking, but thanks!

@SanjitSarda Just for my curiosity, what do you mean with "my voltage reg was off"? Was it broken or did you switched it off. If you switched it off, how did you do that?


text:
Task watchdog gets triggered during Bluetooth initialization
The board ESP32-Dev-WROOM-32D cannot establish a bluetooth connection due to the task watchdog. Here's my code:
#include "BluetoothSerial.h"
//check if Bluetooth is enabled
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32test");
  Serial.println("The device started!");
}

The program runs fine until SerialBT.begin("ESP32test"); where it freezes, and does not continue to run. The message The device started! is not printed. Instead, the task watchdog gets triggered after some time: E (24791) task_wdt: Task watchdog got triggered.
Is there any way to turn off the task watchdog? Or is there any other issue?

Try adding esp_task_wdt_reset(); before SerialBT.begin(...).

Nothing changes, watchdog still gets triggered

SerialBT.begin("ESP32test") is hanging, and because ESP32 doesn't deal well with code that hangs, so it complains about it.
ESP32 runs a Real-Time OS (FreeRTOS).
The fact that it is a real-time OS means that execution of code needs to be guaranteed to finish within a certain time-frame. You'll often see RTOS functions containing the time limit in which that a blocking function should finish executing, such as:
    uart_wait_tx_done(uart_num, 100); // wait timeout is 100 RTOS ticks (TickType_t)

(from ESP-IDF docs)
FreeRTOS comes with a task API. Each task can execute code, but they need to give other tasks the chance to execute code too. I think that when a task blocks, it doesn't allow other tasks to do work on the same CPU. (but I can't find sources to back this up)
setup() runs in one of the RTOS tasks, and when SerialBT.begin() blocks the task for too long, the task watch dog complains that the task is hanging.
If the task is blocked by some kind of looping code, then it generally helps to run vTaskDelay() to yield the task to the task watchdog for a bit.
Because your task is blocked by a single call, there isn't much to do about it, given that SerialBT.begin() doesn't seem allow you to specify when it should time out.


text:
How to Set Sensor Data Parameters?
Good day! How to set sensor Data parameters?
Like the data only set for example it starts with minimum value of 3 and ends with maximum value of 6 and it will turn on led 1 and if minimum value of 1 and maximum value of 2 turn on led 2 just like that?
My actual code for that:
float basa = scale.get_units();
if( basa >= 4 )
{
  digitalWrite(led1, HIGH);
}
else if( basa >= 2 )
{
  digitalWrite(led2, HIGH);
}

This code shows that if ever it reaches value of 4 the value of 2 will react also so my question is how set sensor data value like it will only react Value1 - Value2 like that.
thank you

2 will not react

I don't understand, what your problem is. Please describe it more

Do you really see, that both LEDs get turned on, when basa >= 4? The logic of your if statements seems to be correct. If basa >= 4, the first condition will execute and LED1 will be turned on. The second condition will not execute, because it is in an else statement, where the if statement already evaluated true. Do you reset the LEDs somewhere else in your code? If not, you might see, that the values from your scale simply go up and pass both intervals. If only the first measurement is in the interval between 2 and 4, and the second is over 4, the code will light up both LEDs

For example:
float basa = scale.get_units();

digitalWrite(led1, LOW);
digitalWrite(led2, LOW);

if( basa >= 2 && basa < 4 )
{
  digitalWrite(led2, HIGH);
}

if( basa >= 4 )
{
  digitalWrite(led1, HIGH);
}

EDIT: as suggested by @chrisl (see comments)
If understand you problem correctly, you try to light up 2 LEDs according to the value you read from a scale. IMHO you want to assign three intervals (ranges) like so:
(-INF, 2) : none of the LEDs is switched on
[2, 4)    : only LED 2 is switched on
[4, +INF) : only LED 1 is switched on

[x or x] means the x belongs to the interval.
(x or x) means the x does not belong to the interval.
+INF and -INF are the positive or negative infinity.

My code does the following:
I use the observation, that the intervals do not intersect and the union of the intervals are the complete real number space. (Although your scale has a more narrow range: (0-?kg). The program can handle a wider range compared to the the scale, so it is not a problem.)
If the first condition (-INF, 2) is true, none of the others would be and we can be sure that the LEDs I switched off with the digitalWrite(ledX, LOW);
 statements will stay off. If the value is in the range of [2, 4) I switch on LED2 and can be sure that the other LED stays off because the condition basa >= 4 can not be true. And if the value is in the range of  [4, +INF) I switch on LED1 and can be sure that LED 2 has not been switched on because the condition basa >= 2 && basa < 4 can not be true.

I would say this does exactly the same as the OPs code, except for the digitalWrite(ledX, LOW) calls. Please explain more how this solves the OPs problem (whatever that problem actually is)

@chrisl OP wants when value is 2 turn on an LED and when it's 4 another. but in OP code when it's 4, 2 condition also applies. so Peter approach is correct. if it's bigger than 2 and less than 4 is what OP exactly wants.

@chrisl You're right, I should have explained the solution, but it was late last evening ;-). I'll edit the answer and add my understanding of the problem also. Btw, my code differs not only in the digitalWrite(ledX, LOW) statements. I removed the else and so I decoupled the two cases and I used a range [2,4) for the first case. The < 2 case is implicitly handled by the digitalWrite(ledX, LOW) statements.

@ElectronSurf No, in the OPs code, when basa >= 4 only the first condition applies and thus only led1 is turned on. The second condition is not executed in that case, because it is in an else statement. The code only comes to that condition, when basa < 4. Peter Paul Kiefer added the case for basa < 2 and decoupled the if statements (which could be seen as an improvement).

@chrisl "if ever it reaches value of 4 the value of 2 will react" what I said was based on OP explanation.

@PeterPaulKiefer, you missed the 'else' in OP's snippet?

@Juraj I did not missed the else; I removed it. For me it was one of the means to achieve what I thought the OP had asked for. Have I interpreted the OPs question right? Only the OP can told us. But I fear he stopped the collaboration ;-).

thanks pal appreciated it


text:
Sound sensor signals with time bracket
I've tried many codes for this to work but anything isn't helping at all, so my code should work like this: If a sound sensor (3 pins, A2) sends 5 signals into the Arduino within 10 seconds (the time gap of every signal varies, but doesn't matter as long as it sends 5 signals), the LED (13) will light up. This is my recent code if it could help
int led=13;
int sensor=A2;

void setup()
{
   pinMode(led, OUTPUT);
    pinMode(sensor, INPUT);
    Serial.begin(9600);
}

void loop()
{
    unsigned long StartMillis = millis();
    unsigned long CurrentMillis = millis();
    int signal_count=digitalRead(sensor);
    int signal_limit=5;
    Serial.println(signal_count);

    while ((CurrentMillis - StartMillis)==5000)
    if (digitalRead(sensor)=0)
    {     signal_count ++;
        Serial.println(signal_count);
    }
    if (signal_count>signal_limit) {
        digitalWrite(led, HIGH);
    }
    else {
    digitalWrite(led,LOW);
    }
}

think about the first two program lines inside the loop() block .... what do they do?

What sound sensor are you using? Is its output analog or digital? And what do you mean by "signal"? What counts as a "signal" for you?

I'm using digital sound detector sensor module. I don't know but it prolly uses analog (that's what I got from website references). The signal I referred to is the signal sent by the sound sensor to the arduino (HIGH or LOW)

Still you didn't explain what a "signal" is. Does it mean, that the sensor should go high and then low ( a pulse)? Or how do you want to count "signals"?

I just wanted to count the HIGH signals, then use the number of signals recieved in a short amount of time to trigger a led to light up

Your handling of millis() is wrong. With these two lines:
unsigned long StartMillis = millis();
unsigned long CurrentMillis = millis();

StartMillis will always have the same value as CurrentMillis. (Ok, I guess its possible for millis() to return a value that's increased by 1 the second time it's called, but that is extremely unlikely. The 2 lines takes much less than a millisecond to execute.)
Your
while ((CurrentMillis - StartMillis)==5000)

will never evaluate to true, so the code in the while block will never execute.
This if statement is also wrong:
if (digitalRead(sensor)=0)

You want == (comparison) not = assignment. I'm surprised the compiler even allowed that to compile, since you are trying to set the function digitalRead(sensor) to 0, which doesn't make sense.
Change that code to read:
if (digitalRead(sensor)==0)

(Assuming you want the body of the if statement to execute when your sensor value is 0.)


text:
Moving an object in an area
I am planning to build a little game and I would need to move a small magnet inside a rectangular area. Ideally I would be able to control movement arbitrarily e.g. using a joystick.
I am trying to find a way of doing this, something like an actuator, I guess, but allowing movement in 2D.
Any suggestions on which parts to use?
Edit : in brief, what I'm trying to do is this. I have a piece of plywood, underneath which I want to put a magnet. The magnet will be moveable using a joystick (everything controlled through an Arduino) and will be used to move a magnetised figurine on the other side of the plywood. I guess in term of precision of movement I am not looking for extreme precision, having something accurate to 2-3mm would be absolutely fine. Haven't really thought of speed... But not looking for extreme high speeds.

Two linear axes perpendicular to each other, made of pulleys (like most 3D printers) or of nuts on threaded rods. Or two rotational axes on top of each other, like a SCARA robot. Your question is really broad. You didn't explain enough, what you are trying to achieve. We don't know nothing about your requirements. And maybe this is better fit for the robotics SE site, since your question is not about Arduino.

Hi @chrisl, thank you for your comment. What type of details would help?

First an overview, what you are trying to achieve here. I'm sure moving a magnet is not all to the story. Then you need to think about how fast and precise the magnet should move. When using linear axes, pulleys are much faster, threaded rods are more precise. And I assume there is something important lying in the fact, that you try to move a magnet. Do you want to move it with another magnet from under a table? These information are important for designing a fitting solution.

Totally unrelated to the question, This question is #20,000 question in Arduino SE.

@chrisl thank you. I added a few more details. Anyways your suggestions are already a great start, I guess you could convert that to an answer?

@ElectronSurf, it is not. many questions are deleted and this will be deleted too after a month or so

@nico, I'm looking at this history of this question.  Keep in mind all stack exchange sites (not just Arduino) are best used 1 question at a time.  And often it is best to try something first then come here and ask question if that attempt did not work out.  If you need to discuss an Arduino project and get some direction it may be better to try forum.arduino.cc.  Look at this specific thread and search or others that are similar.  Then come back here with specific questions after trying something.

@st2000 I know, I've been using StackExchange for a very long time. You are right, I should have specified what I did try, but since I could not really find a proper way of looking for this I was just looking for some inspiration. Probably arduino forum would have been a better fit, anyway I got enough ideas from the answer and hopefully someone else facing a similar problem will benefit from this as well.

Well put.  I would search for project involving moving chess pieces with electromagnets like this one: https://magpi.raspberrypi.org/articles/ghost-chess-electromagnets-move-pieces

First you need to think about your axes configuration, then about the actual implementation. I for example can directly think of 2 options:

You could arrange your axes perpendicular to each other, like a Cartesian coordinate system. Here you might need more parts to build it, than with other arrangements, though it is a sturdy system and the positions and paths are easily to calculate. For implementation there are 2 common ways, both using stepper motors in most cases:

You could let the magnet travel on the 2 perpendicular axes pulled by a belt and stepper motor for each axis. As you have to mount one axes onto the other, you might need to use 2 stepper motors (one for each side) for the first axis (depending on your dimensions, how smooth the axes glide and how much force is introduced by dragging the figurine). This approach is mostly used by 3D Printers, since they need rather fast movement, which is also rather precise, but don't need to accommodate high forces.
Instead of belts and pulleys you could use threaded rods for each axis. The magnet is mounted on nuts on these rods. Rotating the rots will move the magnet over the axis, since the magnet is fixed in it's orientation. The precision is highly dependent on the used rods, but all in all it is often more precise, than belts. But it is also way slower.

You could use only rotational axes, like a SCARA robot. It has a rod on a rotational axis and another axis at the end of it. This approach might use less parts, than the Cartesian approach, but you need good servos to have precise and jitter-free positioning (though you could also go for a geared stepper motor here). Also the arm of the robot can look out under the field quite a bit, when positioning it to the far one side.

All of the above approaches can be way more precise, than you need it. They are all viable options.
I personally would go the first way, Cartesian axes with belts and pulleys. The principle is straight forward and you can easily hide it under your piece of plywood (including a margin for all the mechanical stuff of course).

Thanks for the answer! Extremely helpful and gave me some good directions to look at


text:
2 Fingerprint scanner using 1 arduino
I have problem in using 2 fingerprint scanner in arduino mega, every time I need to register I need to go and register my fingerprint on each fingerprint module,

what i am planning to do is when I registered on 1 fingerprint scanner
  then the other fingerprint module automatically registered the
  fingerprint and vise versa.

Can anyone help me with my project thanks. btw my project was already working but I have problems in registration of bio-metrics.
here is my code in verifying the registered fingerprint
#include <Adafruit_Fingerprint.h>
int door1 = 8;
int door2 = 11;
Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&Serial2);
//fplabas
Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&Serial3);
void setup() {
Serial.begin(9600);

pinMode(door2, OUTPUT);
  pinMode(door1, OUTPUT);
//  pinMode(Buzzer, OUTPUT);
//
  digitalWrite(door2, HIGH);
  digitalWrite(door1, HIGH);

 finger1.begin(57600);
  finger2.begin(57600);
    if (finger1.verifyPassword() || finger2.verifyPassword()) {
    Serial.println("Found fingerprint sensors!");
  } else {
    Serial.println("Did not find any fingerprint sensors :(");
    while (1) { delay(1); }
  }

  finger1.getTemplateCount();
  finger2.getTemplateCount();

  Serial.print("Fingerprint Sensor1 contains "); Serial.print(finger1.templateCount); Serial.println(" templates");
  Serial.print("Fingerprint Sensor2 contains "); Serial.print(finger2.templateCount); Serial.println(" templates");
  Serial.println("Waiting for valid finger...");
}

void loop () {
  getFingerprintdoor2();
  delay(50);
  //Fingerprint Sensor Labas
  getFingerprintdoor1();
  delay(50);
}

uint8_t getFingerprintdoor2() {
  uint8_t p = finger1.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      //Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
     // Serial.println("No finger detected");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
    //  Serial.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      //Serial.println("Imaging error");
      return p;
    default:
      //Serial.println("Unknown error");
      return p;
  }
  // OK success!

  p = finger1.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      //Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      //Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
     // Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
     // Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
     // Serial.println("Could not find fingerprint features");
      return p;
    default:
      //Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger1.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    Serial.println("Found a print match!");
    digitalWrite(door2, LOW);
//    sendsms(textForSMS + " Noah", f1001);
//    Serial.println(textForSMS);
//    Serial.println("message sent.");
    delay(3000);
    digitalWrite(door2, HIGH);
    delay(1000);
   // Serial.print(finger1.fingerID);
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    //Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {
//    Serial.println("Did not find a match");
//    digitalWrite(Buzzer,LOW);
//    delay(1000);
//    digitalWrite(Buzzer,HIGH);
    return p;
  } else {
    //Serial.println("Unknown error");
    return p;
  }

  return finger1.fingerID;
}

uint8_t getFingerprintdoor1() {
  uint8_t p = finger2.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      //Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
     // Serial.println("No finger detected");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
    //  Serial.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      //Serial.println("Imaging error");
      return p;
    default:
      //Serial.println("Unknown error");
      return p;
  }

  // OK success!

  p = finger2.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      //Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      //Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
     // Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
     // Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
     // Serial.println("Could not find fingerprint features");
      return p;
    default:
      //Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger2.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    Serial.println("Found a print match!");

    digitalWrite(door1, LOW);

   delay(5000);
    digitalWrite(door1, HIGH);

  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    //Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {

    return p;
  } else {
    //Serial.println("Unknown error");
    return p;
  }

  // found a match!
  return finger2.fingerID;
}

And here is the problem code where I need to register on both Fingerprint scanner:
#include <Adafruit_Fingerprint.h>
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&Serial2);

Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&Serial3);

uint8_t id;

void setup()
{
  Serial.begin(9600);
  while (!Serial);  // For Yun/Leo/Micro/Zero/...
  delay(100);
  Serial.println("\n\nAdafruit Fingerprint sensor enrollment");

  // set the data rate for the sensor serial port
  finger.begin(57600);

  if (finger.verifyPassword()) {
    Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1) { delay(1); }
  }
}

uint8_t readnumber(void) {
  uint8_t num = 0;

  while (num == 0) {
    while (! Serial.available());
    num = Serial.parseInt();
  }
  return num;
}

void loop()
{
  Serial.println("Ready to enroll a fingerprint!");
  Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");

 if (Serial.available()>0)
   switch(Serial.read())
  {
    case 'A':

        id = readnumber();
        if (id == 0) {
           return;
        }
        Serial.print("Enrolling ID #");
        Serial.println(id);

        while (!  getFingerprintEnroll1() );

      break;

       case 'B':

        id = readnumber();
        if (id == 0) {
           return;
        }
        Serial.print("Enrolling ID #");
        Serial.println(id);

        while (!  getFingerprintEnroll2() );

      break;

}

}

uint8_t getFingerprintEnroll1() {

  int p = -1;
  Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(1);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  Serial.println("Remove finger");
  delay(2000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER) {
    p = finger.getImage();
  }
  Serial.print("ID "); Serial.println(id);
  p = -1;
  Serial.println("Place same finger again");
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.print(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(2);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  Serial.print("Creating model for #");  Serial.println(id);

  p = finger.createModel();
  if (p == FINGERPRINT_OK) {
    Serial.println("Prints matched!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_ENROLLMISMATCH) {
    Serial.println("Fingerprints did not match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  Serial.print("ID "); Serial.println(id);
  p = finger.storeModel(id);
  if (p == FINGERPRINT_OK) {
    Serial.println("Stored!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    Serial.println("Could not store in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    Serial.println("Error writing to flash");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }
}

uint8_t getFingerprintEnroll2() {

  int p = -1;
  Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
  while (p != FINGERPRINT_OK) {
    p = finger2.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger2.image2Tz(1);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  Serial.println("Remove finger");
  delay(2000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER) {
    p = finger2.getImage();
  }
  Serial.print("ID "); Serial.println(id);
  p = -1;
  Serial.println("Place same finger again");
  while (p != FINGERPRINT_OK) {
    p = finger2.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.print(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger2.image2Tz(2);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  Serial.print("Creating model for #");  Serial.println(id);

  p = finger2.createModel();
  if (p == FINGERPRINT_OK) {
    Serial.println("Prints matched!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_ENROLLMISMATCH) {
    Serial.println("Fingerprints did not match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  Serial.print("ID "); Serial.println(id);
  p = finger2.storeModel(id);
  if (p == FINGERPRINT_OK) {
    Serial.println("Stored!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    Serial.println("Could not store in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    Serial.println("Error writing to flash");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }
}

Please help I am stuck in this situation..

did you do that and works properly?

The library, that you are using, doesn't seem to support exporting or importing fingerprints. Though if you look into the user manual of the fingerprint sensor at the Adafruit site, there are two commands mentioned, that seem to do what you need:

6.2.2 Upload image:  UpImage
Description: to  upload  the  image  in Img_Buffer  to  upper  computer.  Refer  to  1.1.1  for  more  about image buffer.
6.2.3 Download the image: DownImage
Description: to download image from upper computer to Img_Buffer. Refer to 1.1.1 for more about the image buffer.

These commands can be used to read or write the image buffer, where an image is stored, when it was taken by the sensor (this is only about the image data, not about the recognition or enrolling; that has to be done after loading the image to the buffer). I could not find corresponding functions in the library, so I guess it doesn't support this. So, to get what you need, you need to stop using the library and handle the things yourself (or - maybe better - extend the library to incorporate that feature).
The manual has no good documentation about these functions and the datasheet, that Adafruit has, is in Chinese, so I couldn't read it. You will need to try it out and see, what you get, when issuing the mentioned commands (unless you can read Chinese and there is more useful information in that datasheet).
I guess after requesting the upload of the current image, the module will send data packets in the configured package size, until it has transferred the whole image (Note, that it will only send 4 bits for every pixel over UART, meaning 16-greyscale image). After than you could request the download on the other module. After the acknowledgement packet, I guess you need to send the image data in the same format, as you received it from the first module, in packets with the configured packet size.
When configured to the same packet size, you could request upload and download at the same time for each module and simply let the packets pass through. After transferring the image, you can start the recognition on both modules.

thank you I will look for it ... but can I use that in arduino?

Yes you can. These are just commands issued over UART. You might only get into problems, if you try to buffer the full image in the Arduino. But as I wrote, you can pass the packages through, directly to the other module, so that you only have about 2 packets at the same time in the Arduino

thankyou!!! can you send me a link or guide on where should I start working plss

Start with the library from Adafruit, that you are already using. Try to understand, what the code does. Then you can use the manual, that I linked, and try to trigger the download/upload commands. If that works, you can extent the library for your use. There is no tutorial for doing that, so you need to dig into that topic yourself.


text:
BMP280 pressure as a DC motor switch - issues
I'm attempting to control a DC vacuum pump to turn off when it hits a BMP-280 reads a set pressure lower than when it spins up (guesstimate pressure, I've got it hooked up to tweak in person). Everything works fine for pressure until I get to the runPump() subroutine, when the pressure callouts go from pascal to very large odd numbers.  I've tried variations of INT/FLOAT/LONG but I still either get a 0 pascal reading or an OVF. The BMP later in runPump does return pressure in pascal.

#include <Wire.h>    //This library allows you to communicate with I2C devices (BMP280)
#include "i2c.h"     //same
#include "i2c_BMP280.h"   //same
BMP280 bmp280;
int inches = 0;
int motorPin2 = 10;
int motorPin1 = 9;
int triggerPin = 7;  // For ultrasonic sensor
int echoPin = 4;    // For Ultrasonic sensor
long duration;
long distance;

void setup() {

  pinMode(triggerPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);

  Serial.begin(9600);
  Serial.print("Probe BMP280: ");
  if (bmp280.initialize()) Serial.println("Sensor found");
  else
  {
    Serial.println("Sensor missing");
    while (1) {}
  }

  // onetime-measure:
  bmp280.setEnabled(0);
  bmp280.triggerMeasurement();
}

void trig() {
  Serial.println("Ping!");
  digitalWrite(triggerPin, LOW);
  delay(2);
  digitalWrite(triggerPin, HIGH);
  delay(10);
  digitalWrite(triggerPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  inches = (duration / 2) / 74;
  Serial.print("Inches: ");
  Serial.println(inches);
  delay(250);
}

void runPump() {
  //  Serial.println("Running Pump!!!!!!");
  //  #include <Wire.h>    //This library allows you to communicate with I2C devices (BMP280)
  //  #include "i2c.h"     //same
  //  #include "i2c_BMP280.h"   //same
  //  BMP280 bmp280;
  //  int motorPin1 = 10;
  //  int motorPin2 = 9;

  bmp280.awaitMeasurement();
  float  pascal;
  bmp280.getPressure(pascal);
  bmp280.triggerMeasurement();

  float runningpressure;
  float deflatepressure;
  runningpressure = (int) pascal;
  deflatepressure = (runningpressure - 600); //pascal minus a bit
  Serial.print("Starting pressure: ");
  Serial.println(pascal);
  Serial.print("Goal pressure: ");
  Serial.println(deflatepressure);

  while (runningpressure > deflatepressure) {
    Serial.println("Engaging Vacuum Pump!!!");
    digitalWrite(motorPin1, HIGH);
    digitalWrite(motorPin2, HIGH);
    delay(250);
    bmp280.awaitMeasurement();
    bmp280.getPressure(pascal);
    bmp280.triggerMeasurement();
    Serial.print("Current pressure: ");
    Serial.println(runningpressure);
    Serial.print("Goal pressure:");
    Serial.println(deflatepressure);
    Serial.print(runningpressure - deflatepressure);
    Serial.println(" more to go.....");
    delay(250);
  }
  //  else{
  Serial.println("Shutting Down!!!!!!!!!!!!!!");
  digitalWrite(motorPin1, LOW);
  digitalWrite(motorPin2, LOW);
  delay(2000);
  //  }
}

void loop() {

  bmp280.awaitMeasurement();
  float  pascal;
  bmp280.getPressure(pascal);
  bmp280.triggerMeasurement();
  Serial.print("Pressure: ");
  Serial.print(pascal);
  Serial.println(" Pa;");
  trig();

  if (inches > 4 && inches < 10) {
    runPump();
  } else
    digitalWrite(motorPin1, LOW);
  digitalWrite(motorPin2, LOW);
  delay(5);
}

//  Serial.println("Extruding Glove!@!!!");
//  digitalWrite(motorPinR, HIGH);  //extrudes gloves
//  delay(500);                      // waits .5 seconds
//  digitalWrite(motorPinR, LOW);   // stops extruding

Try manually controlling the pump with it powered from a different power source. The sensor might be acting erratically due to noise caused by the DC motor. Just make a loop to read the sensor. Turn on and off the pump (powered externally) and see if you have the expected behaviour. If the readings are OK then continue looking at the software.

Rudy, thanks!  I was already running the battery from a separate source and had modified the circuit to reduce noise.  What ended up fixing it was adding a diode on the ultrasonic sensor as a diagnostic to show it was working.  It just wasn't where I was expecting noise from.

I was concerned that you would be trying to figure out what was wrong with your program when then the problem could have been a hardware issue. Normally I am telling our programmers that it isn't a hardware problem and the problem is with their code.  I'm glad you figured it out.


text:
Home made drum kit - How can I speed up the response time after my sensor gets triggered?
I am trying to make a psudo drum kit with my Arduino Due and a couple Force Sensitive Resistors (activated with my fingers, no drum sticks). So far in my testing I'm only using one FSR. I've attached an SD Card reader and put a WAV File on there (44100 Hz, 16-bit, stereo). In my 'Loop', I read in the resistance of the FSR to know if it's been triggered, then I play the WAV file accordingly. It works but its not that fast. If this project is going to work, the response time needs to be much faster.
Here's my code:
#include "SD.h" //Lib to read SD card
#include "SPI.h" //SPI lib for SD card
#include <Audio.h>

#define SD_ChipSelectPin 2

const int FSR_PIN = A0; // Pin connected to FSR/resistor divider

const float VCC = 4.875;
const float R_DIV = 10000.0;

void setup()
{
  Serial.println("Starting Drum Kit!");
  Serial.begin(9600);
  while (!Serial) {}

  pinMode(FSR_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);

  Serial.print("Initializing SD Card...");
  if (!SD.begin(SD_ChipSelectPin)) {
    Serial.println("FAILED!");
    while(true);
  }
  Serial.println("done");

  // 44100kHz stereo => 88200 sample rate
  // 100 mSec of prebuffering.
  Audio.begin(88200, 100);

  void loop()
{
  File snare_file;
  short snare_buffer[1024];
  int fsrADC = analogRead(FSR_PIN);
  if (fsrADC > 20) // If the analog reading is non-zero
  {
    Serial.println(String(fsrADC));

    snare_file = SD.open("606snare.wav");
    while (snare_file.available()) {
      snare_file.read(snare_buffer, 1024);
      Audio.prepare(snare_buffer, 1024, 1024);
      Audio.write(snare_buffer, 1024);
    }
    snare_file.close();
  }
}

If I hold down the sensor (constant triggering), the fastest that the file plays is about every half second. Here's the Serial output:
15:12:28.453 -> Initializing SD Card...done
15:12:28.487 -> 1023
15:12:28.930 -> 1023
15:12:29.510 -> 1023
15:12:30.050 -> 1023
15:12:30.628 -> 1023
15:12:31.136 -> 1023
15:12:31.744 -> 1023
15:12:32.328 -> 1023
15:12:32.834 -> 1023
15:12:33.411 -> 1023
15:12:33.955 -> 1023

I've tried playing around with loading the file and buffer in the setup section but I can't get it to work properly. There's not a whole lot of documentation on the Audio library either.
If you know of a better way to speed this up, or if I should be using a different library, please let me know.

You wrote, that you tried loading the file in setup(), but it didn't work properly. How did it not work?  I think moving the loading there is really time consuming. Though keeping the sound loaded permanently might get a problem, when you need to load several files for several drum pads.

I tried creating a global snare_buffer. Then in the setup I would open the file, read the file into the global snare_buffer, and close the file. Then in the loop I would call the two Audio commands: Audio.prepare and Audio.write. This resulted in no sound being produced. I'm not sure how the Audio library works. There wasn't a whole lot of documentation on it. Not sure if there's a better way or a better library.

I would try to also execute prepare in setup, then only call write in loop. Also not closing the file. If that still doesn't give you the required performance, you might need to use an external player, that just get's triggered by the Arduino.

This is not really a 'solution', but it might help you in finding out where the real problem is.
Check out which of the statements in the loop function uses up the most time, probably;

int fsrADC = analogRead(FSR_PIN);
Serial.println(String(fsrADC));
snare_file = SD.open("606snare.wav");
while (snare_file.available()) {
snare_file.read(snare_buffer, 1024);
Audio.prepare(snare_buffer, 1024, 1024);
Audio.write(snare_buffer, 1024);
snare_file.close()

Try improving the most time consuming item if possible.
Some possibilities you can try in the steps above:

Do not use AnalogRead but direct port commands
Remove this completely or at least remove the String instance.
Not much you can do here, except not using a file system but raw SD read (you might have problems getting the files on your SD) without a dedicated program on your PC
Not sure about improving this one
Read less bytes, although it might even worsen things. Or read the bytes BEFORE waiting on the trigger (if you know which sample will be played).
Execute the prepare as before the trigger as 5 if possible.
Not sure about this... High likely you cannot keep too many files open at the same time.

Afaik in my synthesizer (Korg Kronos), it reads from all samples the initial part, meaning it can startup the data from RAM, while the rest is read through SSD (in your case SD). However, you might not have enough memory in an Arduino for that.

I know that it's not the analogRead or the print statement. If I comment everything else out and just leave those two in the loop(), the response time is extremely fast. There must be a way to read in my file into the buffer in setup(). I think the main bottle neck is opening and closing the file each time. I'm not sure how to get around this.

With millis you can exactly time it (run each command 1000 times, print times AFTERWARDS and divide it by 1000). Than you have to check into the library what happens exactly. When opening/closing a file takes too long, concatten all files you need, and read manually from the part of the big single file what you need.


text:
problem with decrement in a loop
I am trying to write a sketch wherein the led brightness increases in increments of 15 until it reaches 255. At that point I want to make decrements of 15 until it reaches 0. The increment part of the program works well but the decrement part goes haywire. It gets stuck between 255 & 240. I am not sure how can I fix it. Could you please tell how can I make it work?
Here is my sketch:
int led = 9; //led pin
int fade = 0; // pwm value

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

  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

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

   analogWrite(led,fade);
   fade += 15;
   Serial.println(fade);
   delay(250);

  if (fade >= 240){
    fade = fade - 15;
    analogWrite(led, fade);
    Serial.println(fade);
    delay(250);
  }

}

the decrement part is not haywire ... it is doing exactly what you told it to do

see the Fading example in Arduino IDE

Perhaps with a for loop it's easier to implement as in Fading example but I was trying to do it using a conditional statement.

sorry, I thought the example is better

Does this answer your question? PWM delay without blocking the code

The problem is that you add 15, and than if it's >= 240, you decrease 15, so it will not change  (I wouldn't consider it haywire though).
You can better use a direction sign. Below is only the relevant code (not the GPIO functionality). What it does in the loop is, in case up is true, it adds fifteen, otherwise it subtracts 15. When 255 is reached, it starts counting down (up is false), when reaching 0, it starts counting up (up is true). This only works if 255 / the amount to add/subtracts reaches exactly 255, otherwise you have to check for <= 0 and >= 255.
bool up = true;
int fade = 0;

void loop()
{
    fade += up ? 15 : -15;
    if (fade == 0)
    {
      up = true;
    }
    else if (fade == 255)
    {
      up = false;
    }
}

Not considered good coding practices:
The last if statement can be substituted for the following line, which means: if going up and 255 is reached, go down, else if going down and 0 is reached, go up, otherwise don't change direction. But it is much less readable, so I prefer the longer if statement.
up = (up && (fade == 255)) ? false : ((!up && (fade == 0)) ? true : up);

Another version: if fade is 0 or 255 (only two possibilities), go up if 0 is reached, else (can only be 255) go down, else don't change.
up = (fade % 255 == 0) ? (fade == 0) : up;

Thanks. Yes I realized why the decrement loop was stuck. It wasn't going haywire. I am new to programming and loops within loops are not really my forte :) Need to practice more but thanks for explaining.

You're welcome. Just follow the first part (the 'good pcoding practice'), use good variable names, and break your problems in small steps. Good luck with your project.

The if condition is causing the issue. When the global variable fade reaches 240, upon entering the loop(), you are incrementing it by 15, making fade = 255. So, the if condition becomes true and 15 is subtracted from 255 making fade to be equal to 240 again. This keeps repeating and hence the value fade variable is stuck between the values 240 and 255.

Thanks. I see the error in my logic now :)

Great! Good luck!


text:
Bootstrap not working: Arduino MKR WiFi 1010 AP mode
I'm trying out the AP mode of the device, where it can serve as its own server. Most of the tutorials have been loading the html from the SD card. I can do the same, but the bootstrap of the website is not working. It just loads the basic version of the website. How can I fix this?
APMode.ino
#include <SPI.h>
#include <SD.h>
#include <WiFiNINA.h>
#define WEBHTM "SERVER/index.htm"

///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "MKRTEST";        // your network SSID (name)
char pass[] = "PASS";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;                // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;
WiFiServer server(80);

File webFile;

void setup()
{

    //Initialize serial and wait for port to open:
    Serial.begin(9600);
    while (!Serial);

    Serial.println("Access Point Web Server");

    // check for the WiFi module:
    if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
    }

    if(!SD.begin(4))
    {
        Serial.println("SD card not found!");
        while(1);
    }

    if (!SD.exists(WEBHTM))
    {
        Serial.println("missing index.htm!");
        while(1);
    }

    String fv = WiFi.firmwareVersion();
    if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
    }

    // by default the local IP address of will be 192.168.4.1
    // you can override it with the following:
    // WiFi.config(IPAddress(10, 0, 0, 1));

    // print the network name (SSID);
    Serial.print("Creating access point named: ");
    Serial.println(ssid);

    // Create open network. Change this line if you want to create an WEP network:
    status = WiFi.beginAP(ssid);
    if (status != WL_AP_LISTENING) {
    Serial.println("Creating access point failed");
    // don't continue
    while (true);
    }

    // wait 10 seconds for connection:
    delay(10000);

    // start the web server on port 80
    server.begin();

    // you're connected now, so print out the status
    printWiFiStatus();
}

void loop() {
  // compare the previous status to the current status
  if (status != WiFi.status()) {
    // it has changed update the variable
    status = WiFi.status();

    if (status == WL_AP_CONNECTED) {
      // a device has connected to the AP
      Serial.println("Device connected to AP");
    } else {
      // a device has disconnected from the AP, and we are back in listening mode
      Serial.println("Device disconnected from AP");
    }
  }

  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    Serial.println("new client");           // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();
            webFile = SD.open(WEBHTM);
            if (webFile)
            {
              while (webFile.available())
              {
                client.write(webFile.read());
              }
              webFile.close();
            }

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          }
          else {      // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        }
        else if (c != '\r') {    // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
        if (currentLine.endsWith("POST /enterCredentials")) {
        //   digitalWrite(led, HIGH);               // GET /H turns the LED on
        Serial.println("Hello there!");
        }
      }
    }
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}

void printWiFiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print where to go in a browser:
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);

}

index.htm
<!DOCTYPE html>

  <title>LPS Server</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

Low Power Sensor (LPS) Server

Please enter needed Credentials

  <form action="/enterCredentials.htm" method="post">SSID:<input type="text" class="form-control" name="SSID">PASS:<input type="password" class="form-control" name="PASS">Broker/Host:<input type="text" class="form-control" name="BROKER">Device ID:
    <input type="text" class="form-control" name="DEVID"><input type="hidden" name="eof" value="#EOF">
<button type="submit" class="btn btn-primary btn-block" value="Submit">SUBMIT</button></form>

All Rights Reserved 2020

so, what does this have to do with the arduino?

I'm using the Arduino MKR WiFi 1010. The library used is the "WiFiNINA" library which has an "AP mode" where the device can act as its own mini server.

how are you getting this file? ... https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css

Now I understand. I need to load the stylesheet from the file in the SD card. This won't work without internet connection. The only problem is how I can do that.

Any ideas or suggestions would be greatly appreciated. Thank you.

take the css file, copy it to SD card and modify the path in html file

there is no reason for sending headers in a command line ... client.println("HTTP/1.1 200 OK"); .... just put the header lines at the top of index.htm

@jsotola, then it would not be a valid html file to debug it on PC


text:
Reading Buffer from Software-Serial & Writing to Serial
My progress so far:
#include <SoftwareSerial.h>

SoftwareSerial ttySerial(10, 11); // RX, TX
byte buffer;

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

  Serial.println("Serial Initialized");

  //Set the data rate for the SoftwareSerial port
  ttySerial.begin(115200);
  ttySerial.println("tty Initialized");
}

void loop()
{
  ttySerial.listen();
  while (ttySerial.available())
    //byte buffer = ttySerial.read();
    //Serial.write(buffer);
    Serial.write(ttySerial.read());

//    if (Serial.available())
//      ttySerial.write(Serial.read());
}

I am really confused because if I write the data as the as the buffer I have defined, the serial monitor goes crazy. If I upload the code as shown, I don't get anything weird in the monitor but the behavior is not what I expect.
I am writing to the software-serial on RX10 & TX11 (from javascript) the following data:
Buffer.from([0, 0, 4, 0, 0, 0, 0, 0]) (keystroke "a")
The Buffer.from method comes from node using the serialport npm module. (This is basically irrelevant since sending the data from Buffer.from('test') works and is output to the monitor.
As you can see, the buffer is 1 byte (the array forming the 8 bits). Why is the buffer not read as "a" in the monitor? Is it because the Micro has an abstract HID report descriptor (see below)?
Additionally, what does Serial.write(...) represent? I.e. when I close the Arduino IDE serial monitor, will my Arduino Micro automatically assume its HID function and write the data as an HID device? S
I know there are already keyboard and mouse HID libraries but I already have code that generates the raw HID data that I would prefer to utilize. Note that the buffer described above comes from the HID report descriptor for a generic keyboard i.e. the "4" is not merely the ASCII code for "a". Explained Here Maybe I can use https://www.arduino.cc/en/Reference/HID ?
Thanks in advance!
EDIT 1:
This is the output I see from the code as shown (without the monitor "going crazy")
19:51:03.017 -> Serial Initialized
19:51:13.932 -> //Where I was hoping to see "a"

EDIT 2: I found the report descriptor in Keyboard.cpp:
  //  Keyboard
    0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)  // 47
    0x09, 0x06,                    // USAGE (Keyboard)
    0xa1, 0x01,                    // COLLECTION (Application)
    0x85, 0x02,                    //   REPORT_ID (2)
    0x05, 0x07,                    //   USAGE_PAGE (Keyboard)

  0x19, 0xe0,                    //   USAGE_MINIMUM (Keyboard LeftControl)
    0x29, 0xe7,                    //   USAGE_MAXIMUM (Keyboard Right GUI)
    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
    0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
    0x75, 0x01,                    //   REPORT_SIZE (1)

  0x95, 0x08,                    //   REPORT_COUNT (8)
    0x81, 0x02,                    //   INPUT (Data,Var,Abs)
    0x95, 0x01,                    //   REPORT_COUNT (1)
    0x75, 0x08,                    //   REPORT_SIZE (8)
    0x81, 0x03,                    //   INPUT (Cnst,Var,Abs)

  0x95, 0x06,                    //   REPORT_COUNT (6)
    0x75, 0x08,                    //   REPORT_SIZE (8)
    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
    0x25, 0x73,                    //   LOGICAL_MAXIMUM (115)
    0x05, 0x07,                    //   USAGE_PAGE (Keyboard)

  0x19, 0x00,                    //   USAGE_MINIMUM (Reserved (no event indicated))
    0x29, 0x73,                    //   USAGE_MAXIMUM (Keyboard Application)
    0x81, 0x00,                    //   INPUT (Data,Ary,Abs)
    0xc0,                          // END_COLLECTION

I will need to compare this to the data I would be sending to Keyboard.write()

you have not said what problems you are experiencing ... serial monitor goes crazy and behavior is not what I expect are both meaningless

please refer to this https://www.arduino.cc/en/Tutorial/SoftwareSerialExample

@jsotola
serial monitor goes crazy - the monitor receives a ton of output that is coming so fast I can't actually see what it is saying and its continuous scrolling wont let me narrow it down.
behavior is not what I expect - If I turn the timestamp on I can see that data was received but it is nothing visible let alone the "a" I was hoping for

@jsotola Thanks but that is the example I used to come up with what you see above. In a sense, the software-serial works fine - it is the reading/writing I am struggling with

use a lower baud rate and you may be able to see what is flying by ... turning off the auto-scroll may also help .... otherwise, use an external serial monitor, such as putty and turn on file capture

@jsotola it looks like it is just saying "Serial Initialized" a bunch of times - yup can confirm: 19:58:43.472 -> Serial Initialized 19:58:43.555 ->  is the continuous output

Don't use listen() this way. It clears the receive buffer. You loose the data received before listen() call.
You have only one SoftwareSerial instance so you don't need to call listen(). The listen() function clears the receive buffer because there is only one buffer for all SoftwareSerial instances.

This did not solve my issue. I will post my output in an edit

I am thinking that the Serial is not sure how to parse the input buffer. I thought that it might work for a Keyboard.write(<buffer>) method since the report descriptor in Keyboard.cpp might know how to parser the buffer input - but to no avail. This was part of reason for the question "what does Serial.write(...) represent?...

Perhaps HID.SendReport(uint8_t id, const void* data, int len) might work but idk what id, data, or len would be exactly in this context... maybe id is the buffer and len is 8 but what would data be?

@SterlingButters, your code in Question doesn't initialize and use HID, so there is no HID in play and sure not over SoftwareSerial

but you think that if I initialized the HID, that buffer might work? Could you also speak to what id, data, and len might be in this case?

what buffer?. SoftwareSerial and HID have nothing to do one with other.

As I understand it, I am using Software Serial to collect the buffer I am transmitting to pin 10 (from js). Then I would like to write the buffer using some HID emulation library. My question is, with the buffer I have defined above, would this work and how would I specify the arguments to HID.SendReport(...)?

if you want to sent keyboard keys, use the Keyboard library. see the examples of the library.

Let us continue this discussion in chat.


text:
Why does this scope-based timer not work as intended?
I wrote the following scope-based timer to help me profile my code and improve its efficency, but in testing I found that it reports durations far shorter than it should:
class CodeTimer {
 public:
  CodeTimer(const String& name) : _name(name) {
    Serial.println("Begin execution of \"" + _name + "\".");
    _begin = micros();
  }

  ~CodeTimer() {
    unsigned long duration = micros() - _begin;
    Serial.println("\"" + _name + "\" execution took " + duration + "µs.");
  }

 private:
  unsigned long _begin;
  String _name;
};

For example, I'd use it like so in my sketch:
void setup() {}

void loop() {
  CodeTimer("void loop()");
  int begin = millis();

  delay(100); // Simulation of work that takes 100ms.
  Serial.println(millis() - begin);
}

Then, when I go to run the above sketch on my Blue Pill board (STM32F103C8), I get something like this printed to the terminal:
Begin execution of "void loop()".
"void loop()" execution took 4µs.
100
Begin execution of "void loop()".
"void loop()" execution took 3µs.
101
Begin execution of "void loop()".
"void loop()" execution took 4µs.
100

Something is very wrong with when the destructor to CodeTimer is being called, and I'm not exactly sure what it is.

the code is optimized by the compiler. It executes the prints and ready. there is no reason to hold the object on stack longer

@Juraj Interesting... Is there any way I can prevent it from doing this?

Access the instance after the delay.

@Juraj This makes sense, thank you. However, I'd still be interested in knowing if there's some sort of compiler flag or keyword I can use to prevent this behavior.

Sure, but I mean like for just this one class/instance.

Maybe if you make _begin a static member...? Untested, just off my head

:-) the coders on Stack Overflow have better eyes (or experience). the variable name is missing so there is no variable to live until the end of the scope https://stackoverflow.com/questions/60496359/prevent-compiler-from-calling-class-deconstructor-before-scope-completed

Yes, I discovered this earlier today. Kicking myself for not seeing this...


text:
Motors working with Ultrasonic Sensor and Servo as expected?
So, I tried making an Arduino Project(Controlling Motors by Remote and Ultrasonic Sensor would activate Servo when the distance is less than 50cm).
I am trying to build a project, A remote controlled car, which will pick up objects when it encouters an object within 50cm. The remote controlled car works fine, but, to pick up objects i am trying to make it work with ultrasonic sensor, but to no avail
First when I just build the circuit for Remote Controled Motors the circuit worked fine, but after adding an Ultrasonic Sensor and Servo the circuit is not working)
This is the code without Ultrasonic and Servo:
#include <IRremote.h>      //including the remote library

#define Next_button 16615543  // code received from next button
#define Prev_button 16619623  // code received from previous button
#define left_button 16591063  // code received from left button
#define right_button 16607383 // code received from right button
#define Stop_button 16580863   // code received from stop button

int receiver_pin = 12;      //output pin of IR receiver to pin 2 of arduino
//initializing the pins for leds
int left_motor1 = 2;      //pin 6 of arduino to pin 7 of l293d
int left_motor2 = 3;      //pin 7 of arduino to pin 2 of l293d
int right_motor1  =4;      //pin 5 of arduino to pin 10 of l293d
int right_motor2 = 5;      //pin 4 of arduino to pin 15 of l293d

IRrecv receiver(receiver_pin); //Arduino will take output of IR receiver from pin 2
decode_results output;

void setup() {
  Serial.begin(9600);
  receiver.enableIRIn(); // Start to take the output from IR receiver
  //initializing all the pins where we have connected the led's as output pins
  pinMode(left_motor1, OUTPUT);
  pinMode(left_motor2, OUTPUT);
  pinMode(right_motor1, OUTPUT);
  pinMode(right_motor2, OUTPUT);
}

void loop() {
  if (receiver.decode(&output)) {
    unsigned int value = output.value;
    switch(value) {
      case Next_button:
           digitalWrite(left_motor1,LOW);
           digitalWrite(left_motor2,HIGH);
           digitalWrite(right_motor1,HIGH);
           digitalWrite(right_motor2,LOW);
           break;
      case Prev_button:
           digitalWrite(left_motor1,HIGH);
           digitalWrite(left_motor2,LOW);
           digitalWrite(right_motor1,LOW);
           digitalWrite(right_motor2,HIGH);
           break;
      case left_button:
           digitalWrite(left_motor1,LOW);
           digitalWrite(left_motor2,HIGH);
           digitalWrite(right_motor1,HIGH);
           digitalWrite(right_motor2,HIGH);
           break;
      case right_button:
           digitalWrite(left_motor1,HIGH);
           digitalWrite(left_motor2,HIGH);
           digitalWrite(right_motor1,HIGH);
           digitalWrite(right_motor2,LOW);
           break;
      case Stop_button:
           digitalWrite(left_motor1,LOW);
           digitalWrite(left_motor2,LOW);
           digitalWrite(right_motor1,LOW);
           digitalWrite(right_motor2,LOW);
           break;
    }
    receiver.resume();
  }
}

This is the code with Ultrasonic and Servo:
#include <IRremote.h>      //including the remote library
#include <Servo.h>

#define Next_button 16615543  // code received from next button
#define Prev_button 16619623  // code received from previous button
#define left_button 16591063  // code received from left button
#define right_button 16607383 // code received from right button
#define Stop_button 16580863   // code received from stop button
#define trigPin 11
#define echoPin 10

int receiver_pin = 12;      //output pin of IR receiver to pin 2 of arduino
//initializing the pins for leds
int left_motor1 = 2;      //pin 6 of arduino to pin 7 of l293d
int left_motor2 = 3;      //pin 7 of arduino to pin 2 of l293d
int right_motor1  =4;      //pin 5 of arduino to pin 10 of l293d
int right_motor2 = 5;      //pin 4 of arduino to pin 15 of l293d
Servo servo;

IRrecv receiver(receiver_pin); //Arduino will take output of IR receiver from pin 2
decode_results output;

void setup() {
  Serial.begin(9600);
  receiver.enableIRIn(); // Start to take the output from IR receiver
  //initializing all the pins where we have connected the led's as output pins
  pinMode(left_motor1, OUTPUT);
  pinMode(left_motor2, OUTPUT);
  pinMode(right_motor1, OUTPUT);
  pinMode(right_motor2, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  servo.attach(8);
}

void loop() {
  if (receiver.decode(&output)) {
    unsigned int value = output.value;
    switch(value) {
      case Next_button:
           digitalWrite(left_motor1,LOW);
           digitalWrite(left_motor2,HIGH);
           digitalWrite(right_motor1,HIGH);
           digitalWrite(right_motor2,LOW);
           break;
      case Prev_button:
           digitalWrite(left_motor1,HIGH);
           digitalWrite(left_motor2,LOW);
           digitalWrite(right_motor1,LOW);
           digitalWrite(right_motor2,HIGH);
           break;
      case left_button:
           digitalWrite(left_motor1,LOW);
           digitalWrite(left_motor2,HIGH);
           digitalWrite(right_motor1,HIGH);
           digitalWrite(right_motor2,HIGH);
           break;
      case right_button:
           digitalWrite(left_motor1,HIGH);
           digitalWrite(left_motor2,HIGH);
           digitalWrite(right_motor1,HIGH);
           digitalWrite(right_motor2,LOW);
           break;
      case Stop_button:
           digitalWrite(left_motor1,LOW);
           digitalWrite(left_motor2,LOW);
           digitalWrite(right_motor1,LOW);
           digitalWrite(right_motor2,LOW);
           break;
    }
    receiver.resume();
  }
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
  if (distance < 50) {
    Serial.println("the distance is less than 5");
    servo.write(90);
  }
  else {
    servo.write(0);
  }
  if (distance > 60 || distance <= 0) {
    Serial.println("The distance is more than 60");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
}

Lose the big delay. Are you really trying to use a PP3 to power it all?

Yes, 9v. Should I use more volts or this is fine.

It's not the volts, it's the current. Those batteries are insanely weak. They are not suitable for driving motors.

"is not working" not a sufficient problem description. We cannot know, how it is not working. Have you tried to debug your code by using Serial prints? As Majenko already stated, the 500ms delay at the end of loop will really break down the performance of the code (since nothing can be done during these 500ms). Look into the BlinkWithoutDelay example, that comes with the Arduino IDE, to learn, how delays can be avoided.

As you mentioned, I used a Variable Power Supply and it actually increased the RPM of the motor. But, can you elaborate how to supply more amps.

As you suggested, I've removed the delay.  I'm a newbie i don't know about the errors.

what errors are you talking about?

Actually i don't know about it, i am a rookie when talking about arduino. The motors don't get Volts, when checked using Multimeter


text:
Esp32 and 74hc595 problem
I am using 74hc595 in several projects where I need more I/O and always worked fine using arduino pro mini or arduino mega. Now I connected same 2 of 74hc595 to an esp32 and does not work.
Is there any special things to do for esp32?
Wiring is exactly the same like here https://www.arduino.cc/en/tutorial/ShiftOut on chapter 2 (Connect the 2 registers.). If I use this with an arduino mega on pins 10,9,8 (see commented in code) is working perfect.
Then I replace arduino mega with esp32 and using pins 23,18,5 and does nothing. I get in serial monitor on/off prints but nothing changes to the relays.
Code
int SER_Pin = 23;//10; //pin 14 on 75hc595 //data pin
int RCLK_Pin = 18;//9; //pin 12  //latch
int SRCLK_Pin = 5;//8; //pin 11  //clock

#define number_of_74hc595s 2

#define numOfRegisterPins number_of_74hc595s * 8

boolean registers[numOfRegisterPins];

void setup() {
  Serial.begin(9600);
  pinMode(SER_Pin, OUTPUT);
  pinMode(RCLK_Pin, OUTPUT);
  pinMode(SRCLK_Pin, OUTPUT);

  clearRegisters();
  writeRegisters();
}

void clearRegisters() {

  for (int i = numOfRegisterPins -1; i >= 0; i--) {
    registers[i] =HIGH;
  }
}

//Set and display registers
//Only call after all values are set how you would like
void writeRegisters() {
   digitalWrite(RCLK_Pin, LOW);

   for (int i = numOfRegisterPins -1; i >= 0; i--) {
      digitalWrite(SRCLK_Pin, LOW);
      int val = registers[i];

      digitalWrite(SER_Pin, val);
      digitalWrite(SRCLK_Pin, HIGH);
}
  digitalWrite(RCLK_Pin, HIGH);

}

//set an individual pin high or low
void setRegisterPin (int index, int value) {
  registers[index] = value;
}

void c_on() {
  Serial.println("on");
  setRegisterPin(13,LOW);
  writeRegisters();
  delay(50);
}

void c_off() {
  Serial.println("off");
  setRegisterPin(13,HIGH);
  writeRegisters();
  delay(50);
}

void loop() {

c_on();
delay(1000);
c_off();
delay(1000);

}

Is there any special thing to do for using esp32?
Thank you very much

Are you powering the shift registers from 5V or 3.3V?

What relays are you using? Are you sure they work with the voltage you are powering your shift registers with? If you connect an LED+resistor to the shift register pin you are testing (#13 according to your code), does it light up?

the speed is different. maybe add some short delay in micros after setting the SRCLK

@Juraj, one single microsecond should be more than enough for the HC595.

The issue was from the power supply. Weird because same power supply worked with arduino mega

WiFi requires more current


text:
Atmega328 standalone not working unless Pin1 connected to Arduino RESET
I'm new into this domain field. My principal occupation is as a .NET developer.
I'm trying to do a personal project in which a AtMega328 takes some output from a scale using HX711 and sends a SMS via SIM800L GSM module. Before creating the whole module I tested each part separately with Arduino and the specific modules directly on breadboard. Everything works fine.I created a standalone using the guide from Arduino website(16Mhz crystal, 2x22 picoFarad capacitors, 10k Resistor to PIN1, RX/TX connected to PIN2/3). I designed the circuit using EasyEDA, printed it into pcb and assembled it. The only issue is that, when the standalone is not connected to the Arduino, and powered up by an external 5V source, unless I connected the pin1 to Arduino(connectd to PC)RESET pin, it's not working. I tried to attach a button for RESET to PCB, and connected it to PIN1 and GND, but like this I cannot upload to Atmega328, unless i disconnect the button from 10k Resistor/PIN1 and GND. In the first picture is the standalone which is not working if powered by an externalSource, unless I remove the button and add wire between Arduino-RESET and Atmega-PIN1. In the 2nd picture is my circuit, without HX711 module and in the 3rd picture is my circuit, working only because I connected the ARDUIN-RESET to Atmega328-PIN1 .[![ATmega328 powered by wallplug, not working][2]][2][![PCB schema, working, after connecting PIN1 to Arduino RESET][4]][4]enter image description here][5]][5][

Comments are not for extended discussion; this conversation has been moved to chat.

So, the comments went to chat. Somebody recommended to use decoupling caps as close as possible near the VCC/GND of Atmega. I have 10uF in my workbench, so I used on of these caps and the issue was solved.

Not having bypass caps can cause some very weird errors. Guess you learn a lesson here, as I did some time ago (-;


text:
How to display CAN BUS information on EPS32 web server?
I try to display the transmitted information from CAN bus on ESP32 web server. I saved the CAN.read() in a buffer receivedChars[i] and try to display the data by  client.println(receivedChars[i]);}. However, nothing shows on the webserver... The complete code shows below,
// Copyright (c) Sandeep Mistry. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include <CAN.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Replace with your network credentials
const char* ssid     = "NGW_2.4G";
const char* password = "NextGW2018";

// Set webserver port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

void setup() {
  Serial.begin(115200);
  while (!Serial);

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }
  delay(2000);
  display.clearDisplay();
  display.setTextColor(WHITE);

  Serial.println("CAN Receiver");
  CAN.setPins(16, 17);
  // start the CAN bus at 500 kbps
  if (!CAN.begin(500E3)) {
    Serial.println("Starting CAN failed!");
    while (1);
  }

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop() {

    char receivedChars[10];
  // try to parse packet
  int packetSize = CAN.parsePacket();

  if (packetSize) {
    // received a packet
    Serial.print("Received ");

    if (CAN.packetExtended()) {
      Serial.print("extended ");
    }

    if (CAN.packetRtr()) {
      // Remote transmission request, packet contains no data
      Serial.print("RTR ");
    }

    Serial.print("packet with id 0x");
    Serial.print(CAN.packetId(), HEX);

    if (CAN.packetRtr())
    {
      Serial.print(" and requested length ");
      Serial.println(CAN.packetDlc());
    }
    else
    {
      Serial.print(" and length ");
      Serial.println(packetSize);

      // only print packet data for non-RTR packets
      while (CAN.available())
      {
         for (int i=0; i<5; i++)
         {
           receivedChars[i] = (char)CAN.read();
           Serial.print(receivedChars[i]);
         }
      }
      Serial.println();
    }

    Serial.println();
  }

   WiFiClient client = server.available();   // Listen for incoming clients
   if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // Display the HTML web page
            client.println("<!DOCTYPE html>");
            client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the table
            client.println("
Can bus
");
            client.println("
text: 	");

         for (int i=0; i<5; i++)
         {
           receivedChars[i] = (char)CAN.read();
           client.println(receivedChars[i]);
         }

            client.println(" .
");

            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

It looks like the CAN-BUS can not be activated in web server session, I save the transmitted information in a buffer before starting the web server session, and print out the information from the buffer.


text:
How to get Transmission package Timestamp from ESP8266
I am trying to make an Indoor positioning system using ESP8266 as a beacon, how do I get the transmission package timestamp from router to ESP8266 and vice-versa?
Thank you in advance for any advice

what is a transmission package timestamp?

it's the timestamp that's attached to a package every time it is sent from the receiver to the router or vice-versa

What do you hope to use the timestamp for?

I'm going to compare the received package timestamp from ap to dongle and vice versa to get the distance between the ap and dongle

You can use timestamp from NTP client and attach it
Install NTPclient library from Arduino library manager
This library uses WiFiUdp library to connect to the NTP server, so download that too
Then you can just update the time every time your sending/receiving something and log it as and how you see fit!

this answer is so wrong. it doesn't answer the question and it doesn't answer right the question I assume it answers

How do I access it though?

@Juraj oh I see! maybe I misunderstood the question, I definitely didn't know what Indoor positioning system using ESP8266 as a beacon was! I was working on sending sensor data to database and added this NTP client to get time every time i sent data to database, so i thought the requirement was the same and hence suggested it! would love to hear your thoughts!


text:
Firebase.failed() returns 0 after Firebase.begin(), but returns 1 while reading or writing from/to firebase from ESP8266
The program was running fine, a few days ago, but now it just wouldn't read/write to the database. I'm running on ArduinoJson 5.13.5 and using FirebaseArduino library. I have set all the rules to true, would love to know how to debug this error. Also Firebase.error() does not give any output at all!

Apparently the Firebase's fingerprint has changed recently and has caused the above issue!
from here get the latest finger print and change it in the ...\Arduino\libraries\firebase-arduino-master\src\FirebaseHttpClient.h
In the file mentioned above: update the value of static const char kFirebaseFingerprint[] to the new one mentioned above.
P.S. One issue going forward for me(planing on implementing it on a long term basis) is how to be ahead of this issue in the future, so that I can get the data uninterrupted!

It is OK to accept your own answer as the solution to the problem.