text:
Routing Matrix with a large number of I/O
Lets say that i would like to make a 128x128 routing matrix with an arduino uno,
Since i am unexperienced i think of using two 4051’s for 8x8 patching and because i want to persist the patch, controlling them with two quad d type flip flops, then repeat the circuit to reach 128x128 patching capibility. Then my output count would be sufficent in arduino uno.
I think this would work but sounds unelegant to me.
Do you have another advice for me to achieve this task?
Actually what I would like to achieve is a big digitally controlled patching matrix for my own analog synth circuits at home. So analog signals will be present and should have the avalibility to patch anything to anything.

That is 128*128 = 16384 junctions! Can you tell what it is for? Is it for analog signals in both directions? Can all inputs be active at the same time? Please update you question with more information. This is the arduino section, I think your question will be moved to the electronics section.

Actually what I would like to achieve is a big digitally controlled patching matrix for my own analog synth circuits at home. So analog signals will be present and should have the avalibility to patch anything to anything.

Can you draw a circuit with two 4051's for a 8x8 matrix? They have a single common pin, they are not a matrix. The cd4066 has 4 analog switches, then you need 16384/4 = 4096 of those chips.

I think it can be done with 2304 74HC4067 chips ((1+8)*256). Who can reduce the amount of chips that are needed further?

Ah you are right, I thought terribly wrong, this way they can not be patched at the same time. Rudy’s advice for ad 75019 explains the situation. Sorry a bit confused now.

But isn’t there a way to go for this task not using amazing amount of chips?

I think that there is not a single chip for 128x128. A small module for 8x8 or 16x16 can not easily be scaled up, because it is a two-dimensional matrix. You need a large amount of chips.

I would use a port expander that uses I2C for communications. One example is the PCA9555. You can add up to eight by setting the address bits (A0-A2). This will give you up to 64 outputs to control the selection bits of the 4051s.

While this is all intelectionally possible, from a logic perspective, I have concerns about how this can be practically implemented. I think you need to go into more detail on what you plan to do. What the purpose is.
Also, there are larger chip for do analog matrix switching. AD75019 is one example. https://www.analog.com/en/products/ad75019.html
They are more expensive but cost should not be the primary factor. Getting a design to work is more important.
Do a search for "Crosspoint Switch Array" for more chips like this.

Wow thank you i will immediately chack all of those. What are your concerns about practical implementation?

Anything that large is a problem. Physical implementation. Noise issues.  What is your application?

I edited the question to include my purpose.

OK that's more doable. I was worried you were trying to take signals in from the real world. Good luck.

20 dollars per ad75019. How many will be needed?

Well, since this is the case I can live with 6 of them. Maybe 96x96 is big enough.

Six ad75019 make a matrix of 16x96. I think you need 36.

Ah you are right, but these were quite informational for me thank you both. Now I get the picture better I would research according to that. Well maybe in the future this would not be a bad investment for such a large patch bay. Do you think there will be other problems that i can not think of right now in such a large project? Like rudy mensioned, distortion, noise?

Anything that complex will be difficult. It will certainly be a learning experience. (problems that need to be solved) I suggest starting small. Also look to see how other people have done something similar.

This one is 100$ and I think can keep me busy for a long time, thanks again.
32x32 Analog Switch Matrix,ADV3200.
https://www.analog.com/media/en/technical-documentation/data-sheets/ADV3200_ADV3201.pdf

Of course you would need to make a custom circuit board. 0.5mm pitch is hard to solder. I hate fine pitched components. I do some, but I tend to leave most of it to the production department at work.


text:
Is it possible to combine a HC-05 Bluetooth module and a shrinked arduino ATtiny45/85 to control a motor, LEDs, or other components?
I'm thinking of making a tiny RC toy project that is controlled through Bluetooth with most components at its tiniest size. I'm a complete beginner in this area so i'm not completely familiar with lots of components so please don't mind me if i sound dumb and uneducated. Anyway...
If it's possible: how many components can i use with the ATtiny45/85? or should i go with the atmega8.
I have a m20 mini motor, a micro servo and a few leds. This doesn't include other components that i havent purchase such as dc driver module and HC-05 Bluetooth module.
If not possible: what other options I can do to create my project.

The ATTiny has 5 usable pins (6 if you decide to reuse the Reset pin). Since it doesn't have UART hardware, you need to use a SoftwareSerial library to communicate with the HC-05. This takes 2 pins. To drive a motor, you need at least 1 pin. If you need to control it's speed (instead of just on and off), you would need to generate a PWM signal. Either through hardware timer or by code. (The ATTiny has 2 timers. When you want to use PWM with hardware timer, you need to make sure, that the SoftwareSerial library doesn't want to use the same timer). For the servo it's similar. The servos position is encoded by pulse lengths. (Make sure, that the used library doesn't want to use an already used timer)
Unless you use techniques as multiplexing or matrixes (which are not that useful for a small number of LEDs), you need 1 pin per LED.
Depending on what exactly you want to achieve, you will pretty fast run out of pins. Since you are a beginner you should start with a chip with more pins. If you don't know, how exactly your project will be in the end, better by a chip with maybe double the pins, that you think you need. Develop, until you really know, what functionality your project should have, what not and what you need to achieve that. Based on this you can choose the correct chip, that is as small as possible. Also consider using SMD parts in the finished version. There are mostly much smaller, but also more difficult to solder.

Thank you for your answer :) i understand most of the information you mention in the first part but i've never counter information about using chips as shrink arduino. Can you inform me more about that topic?

An ATTiny is a chip (more precise a microcontroller), but not an Arduino. Mostly an Arduino is a complete board with the microcontroller and every other essentiell part, that is needed for operation. If you use the internal oscillator of the microcontroller, you can operate it nearly without extra components, though you should add a decoupling capacitor.

I see thank you I learnt alot from it. So i looked around and found the ATtiny2313 that is relatively quite a good size and contain lots of pins. Can i get your opinion on this chip. Will it be good for my project?

That looks good. It has a hardware UART, so that you don't need SoftwareSerial, also 4 PWM outputs with 2 timers and more pins. I think with this you should be able to create your project. For the LEDs: If you only want to control them between on and off, you can also use shift registers to expand on the pins. Finally, when you are finished developing the project, you can change the chip to a smaller one, that is right enough for it (too much limitation during development can be frustrating and expensive).

Thank you for your guidance, with these information I can learn more on electronics and start on my project :)

source: Stack Exchange

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

sort: votes


text:
LCD lights up but shows no text
I've connected an LCD display to an Arduino Uno following the instructions from the Adafruit LCD lesson.

I've used the code sample described in the Adafruit lesson.
What happens after I connect the Uno to the USB cable is that the LCD lights up, but no text is displayed.
I've checked all connections and they look good. I am not 100%sure I have connected the potentiometer correctly, as this is the symptom I usually found online.
Could this also be a bad solder job? It's my first attempt and I guess it did not go that great.

Here are some more images, maybe someone with more experience can spot the error.

Update: here's what the board looks like once connected

and after removing the ethernet shield I get some weird flashes from time to time, only when I switch the potentiometer to maximum on one side, see video at https://i.imgur.com/ZclD2xz.mp4 .
Update 2: I realised that this is a 20-pin LCD screen and re-reading the datasheet and some online tutorials I switched digital wire connections to pins to the LCD 7-10 (DB0-DB3) - same result and then 11-14 (DB4-DB7) - garbled output, shown below. Still no idea what is wrong.

By "no text is displayed" what do you mean?  Are there 4 rows of blocks displayed that are lighter than the background or darker than the background?  Can you post a picture of the display when lit?   Also I have had the Ethernet shield be problematic.  Try removing that shield and givi'n her a go without it.  If you have a volt meter, you can test the wiper voltage (the yellow wire) to ground and see if it varies as you turn the stem of the potentiometer.

Hint: Start by removing the Ethernet Shield, then check the schematics for the shield and you will see why this was not a very good idea.

@MrFixIt87 - thanks for the pointers! See my update with a screenshot and a link to a video of what happens after removing the Ethernet shield.

@MikaelPatel - thanks for the pointers! See my update with a screenshot and a link to a video of what happens after removing the Ethernet shield.

Ok, so the LCD is a LCD12864 and that needs a different LCD driver. Use this "tutorial" instead. https://playground.arduino.cc/Code/LCD12864

The ethernet shield uses power and the backlight of the display uses power. I don't know this display, but the common 16x2 lcd displays needs a resistor for the backlight. The common displays require also a voltage near 5v. Perhaps you can add a resistor to the backlight to reduce the power usage. Measure the 5v pin to check that it is above 4.5v.

From provided picture it is visible that your display is not alphanumeric display (with most popular HD44780 driver). It is a graphical display (most popular: KS0107 or KS0108 or ST7920). You can count horizontal pixels and vertical ones in the picture to confirm its resolution.
Without too many problems you can drive it with your Arduino. Try to use some of 128x64 Arduino libraries. Also, check the rear of the display for any part number to confirm the driver (search in google).
 Good luck!

Thanks for the answer. I still need to wait a couple of days as I ran out of wires, so can't validate this right away...

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


text:
Why to store a function parameter value in a class private variable?
I'm just curious, I'm going through a C++ library for the mcu2.4 TFT display.
And this method I notice when I run through C++ libraries.
Which is when a parameter is passed through a function, it's stored in a private variable; like this one:
HCTFT::HCTFT(byte DisplayType)
{
    _Display = DisplayType;

What's the benefit of this method? What's the similar method when I want to do it in C code?

C doesn't have classes or private variables, so you can't do that in C?

You should read up on constructors.

@immibis I know, I just considering that the common methods in C++ and the equivalent in C.

The reason is that _Display will be used probably after its construction.
So you pass the byte during construction, and afterwards the value is available during the object's lifetime.
In C you probably will do this by:

Passing the variable (byte DisplayType) in each function where the value is needed (you can use this way in C++ too but it's cumbersome in both C/C++ to pass the variable in all functions needed).
Storing it in a global variable (static for that .c file); this is the typically C method.

* Added explanation *
Such a variable is called class variables and are mostly made private. The reason is that other objects cannot change the value directly. The only way to change a variable is:

By initializing it in the class constructor (like in your example).
Within the class itself (by any method).
By a typical Set method (like SetDisplayType). This method can check if the value passed is within a range, and there is only one entry point in this class to change it.

To retrieve the value, typically a GetDisplayType method should be created which is public. The variable itself is private.

OK, I understand, so it's a programming style. Hmm alright, I'm starting to understand C++ syntax. I'm just running through the library. Most of the time when I run through C++ libraries I encounter things; like, private, public, inline, virtual .. etc. There are also things I want to understand too, I'm just taking it step at a time to get to know C++ better, I'm thinking how C++ would be effective to me when I want to write a library.

Well in C++ (or actually an OO language) it's very normal to put information (data/variables) and functionality together, and in a class (private) variable you store data that belongs to that instance of the class.

OK, this one is clear to me now, so the class is just a complete object which has its own functions and variables and that's it. Then also there are other specifiers which provide the property to use this class functions or variable by other classes but of course it's much more advanced topic than my current knowledge.

It's better to read a book about OO design, than you will get to learn all the reasons behind it. The main idea is: keep data/functions together, keep data private, keep functions lean and public to others.

Michel Keijzers explained pretty well the purpose of that idiom. Just to
complement his answer, you can do exactly the same in C, only with a
slightly different syntax:
typedef struct {
    byte _Display;
    // ...
} HCTFT;

HCTFT_construct(HCTFT *this, byte DisplayType)
{
    this->_Display = DisplayType;
    // ...
}

Now, every function that receives a pointer to an HCTFT (a HCTFT
“method”) has access to that data as a member of the struct.

So you mean I have to store it somewhere whether in a class private member with C++, struct variable with C or a global variable. So I don't have to pass it again to other functions, and I just can call its value from any function without passing it to that function? Am I understanding it correctly?

@PerchEagle: You don't have to: there are always many ways to do one thing. What I say is that, if you need to store several pieces of data for managing a TFT display, it is convenient to bundle them together into a single data structure (a struct). Then, instead of passing all the pieces as separate arguments to every function that deals with the display, you just pass a pointer to that single struct. The code becomes better structured and more readable. The C++ classes and methods are basically syntactic sugar over this programming pattern.

Wonderful, I just have to dive into writing the TFT library to learn how to use these skills, I started to put the definitions in the header file. But what I'm considering now is that the process could be similar if I used my basic C skills to write a library hmmm. I found a good example like this piece of code. void HCTFT::SetFG(byte R, byte G, byte B) {  _FGR = R;  _FGG = G;  _FGB = B; } so now the result is that the underscore variables are declared in the private section. And now by passing them to this function then they can be used right away in other functions! Nice.

That is more Object Oriented Programing question than the Arduino related.
Encapsulation is one of the fundamentals of OOP and it's basically you'll provide some interface to the object and the outside world doesn't have to know anything about it's internals (so it's not possible to change it into inconsistent state).


text:
Converting of 32 bit signed hex value to dec
Using Seed studio CAN shield to read and convert CAN data to dec value.
Example of expected result:
Full CAN message is 70 3B F1 FF 00 00 00 00 , using little endian first 4 bytes gives: FFF13B70 , which should be equal to converted dec value of -0.967824 (using factor of 0.000001).
Here is code to extract the text value I am using.
CAN.readMsgBuf(&len, buf);
unsigned char len = 0;
unsigned char buf[8];
    {
           String reg0 = String (buf[0], HEX);
           String reg1 = String (buf[1], HEX);
           String reg2 = String (buf[2], HEX);
           String reg3 = String (buf[3], HEX);
           Serial.print(reg3);
           Serial.print("\t");
           Serial.print(reg2);
           Serial.print("\t");
           Serial.print(reg1);
           Serial.print("\t");
           Serial.print(reg0);
           Serial.print("\t");
           String regsumm = (reg3 + reg2 + reg1 + reg0);

           Serial.println(regsumm);
        }

As result I got only text string which couldn't be converted into dec. Any other ways how do it?

You have taken completely the wrong tack. You don't want to convert your data into text and then convert it back into data again - it's already data.
You can combine your first four buffer bytes into a single 32-bit signed integer with just:
int32_t val = ((int32_t)buf[3] << 24) | ((int32_t)buf[2] << 16) |
              ((int32_t)buf[1] << 8) | (int32_t)buf[0];

That gives you the value -967824, which is 0xFFF13B70 in hex notation, or 11111111 11110001 00111011 0111000 in binary.  All of them are the same thing and are just a number.
You can then multiply that result by your "factor" into a float variable:
float dec = val * 0.000001;

Chances are it won't give you -0.967824 due to the nature of floating point values, so you may be better off keeping it as -967824 and working in "micro-units" instead of "units".

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

Since the bytes you received in the buffer are in little endian order,
and your Uno is itself little endian, you don't even need to move bytes
around: you can just reinterpret the bytes you already have as an
int32_t:
union {
    uint8_t bytes[8];
    int32_t numbers[2];
} buffer;
unsigned char len = 0;

CAN.readMsgBuf(&len, buffer.bytes);
Serial.println(buffer.numbers[0] * 1e-6, 6);

This prints -0.967824 to the serial port.
Note that this code will not work as expected on a big endian platform.
If you want something portable, the usual solution is to build the
result using bit shifts, as in Majenko's answer.


text:
Rescuing an Arduino With a Broken Setup()
I may have bricked my Arduino Pro Micro by writing a broken code into the setup() function. When I plug my Pro Micro into my PC, I see it register a COM port for a brief moment before it disappears. Grounding and ungrounding the RST pin causes the device to appear in my control panel again for a brief moment. Attempting to upload the blink example from the Arduino IDE fails, since the COM port disappears before the process can complete.
Is there an alternate way of flashing code to the arduino which I could possibly use to fix this? I have a working Pro Nano I could use if needed.

Try grounding RST twice in quick succession.

When working with any microcontroller it can be good practice to always have a hardware programmer on hand. Bootloaders are all very well, but when they go wrong they leave you stuck. Hit eBay for a USB-ASP (~$2 from China - get the adaptor with it).

After Majenko's suggestion I tried looking into USB ASPs, and then did research about whether you can use an arduino as an ASP. Sort of. I'm not sure if an ASP is exactly the same thing as an ISP, but I used an Arduino Nano as an ISP to program the Arduino Pro Micro.
To do this, I opened the ArduinoISP example sketch and burned it to the Nano (over USB). Then I connected it to a breadboard, along with the Pro Micro. Connected the following pins:
nano pin          micro pin
13                15 (SCK)
12                14 (MISO)
11                16 (MOSI)
10                RST
5v                5v
GND               GND

It is important to connect a capacitor from Nano RST to GND. I was told to use a 10uF capacitor but I had a 1uF on hand that worked just fine. Then I opened up the Blink example sketch, set up the Arduino IDE for programming the Pro Micro, and set programmer to "Arduino as ISP". Hold shift, click upload, problem solved. Pro Micro is running Blink and I can now recognize it and program it over USB.
So I agree with Majenko; someone faced with this problem should buy a hardware programmer. But only if you don't have a spare Arduino ;)

The ASP in USBasp is just part of the name. It probably stands for something like USB Atmel/AVR Serial Programmer. It still uses the ISP protocol.

It's worth mentioning that my Arduino-Arduino programmer has begun to fail me. I'm not sure exactly why, but I'm no longer able to pull this off. More research required. I'm purchasing a USBasp to see what I can salvage.

You can try running the code upload command directly using a precompiled hex file.
Here is how.
Go to preferences in Arduino IDE
Set the Show verbose output during: upload option.
Upload the blink sketch. (arduino does not have to be connected)
After the compilation, check the log window at bottom of the IDE.
You will find a line like this:
E:\arduino\hardware\tools\avr/bin/avrdude -CE:\arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\xxxxxxx\AppData\Local\Temp\build918c1e88f8d0a4c453f8bdfce4cccd30.tmp/Blink.ino.hex:i

That is the actual code upload command.
Copy the command line and paste it into a windows CMD window.
Edit the COM port to match your Arduino.
Reset the Arduino and immediately press Enter to run the command line.
You may get lucky and the upload "squeaks" through.
You can also move the hex file to another folder so that it is always available for doing a quick recovery.
You could also create a BAT file so that double-click on the icon runs the upload.


text:
Regarding turning exact 180 degrees using an MPU6050
I want to turn robot exact 180 degrees by using an MPU6050. This is the code I tried. Can anyone help me?
#include <MPU6050_tockn.h>
#include <Wire.h>

#define enA 9
#define in1 4
#define in2 5
#define enB 10
#define in3 6
#define in4 7

MPU6050 mpu6050(Wire);

void setup() {
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets(true);
  setupmotor();

}

void setupmotor(){
    pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);

}

void loop() {
updatempu();

while(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ){
       turn();
  }

}

void updatempu(){
    mpu6050.update();
  Serial.print("\tangleZ : ");
  Serial.println(mpu6050.getAngleZ());

}

void turn(){
  Serial.println("turn");
        digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
      digitalWrite(in4, LOW);
    digitalWrite(in3, HIGH);
      analogWrite(enA, 100); // Send PWM signal to motor A
  analogWrite(enB, 100);
}

void stp(){
    Serial.println("stop");
        digitalWrite(in1, LOW);
    digitalWrite(in2, LOW);
      digitalWrite(in4, LOW);
    digitalWrite(in3, LOW);

}

do you understand that while(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ) is true when getAngleZ IS either 180 or -180? perhaps you meant while(mpu6050.getAngleZ()!= 180 && mpu6050.getAngleZ()!= -180 )

when mpu6050.getAglez() = 180 0r -180 then robot should stop. but it is not happening. without stopping ,it is turning

your logic as it stands now is, if getAngleZ() is 180 OR -180, call the function turn - but you want to turn if getAngleZ is NOT 180 AND NOT -180 - is that correct

if(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ){
stp();
}                                                                else { turn();} it should be like this or not??

maybe, I don't know, seems about right - did you try?

you are asking for help, but you do not say what the problem is. .... the information about what you observe should be in the question above .... please add it

As I understand, you want the robot to position itself automatically at either 180° or -180° and stay there. When an outer force get's applied to the robot - turning it out of the target positions - it should again try to reach the target positions.
The first problem was pointed out in the comments and your own code correction seems ok to tackle that:
if(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ){
    stp();
} else {
    turn();
}

But I see a second problem: In the real world sensor mostly have some kind of noise imposed on their signal (not necessarily meaning electrical noise). For example if you shake the table, where the robot stands on. Or - more importantly in my opinion - The motor, that you use, might not stop fast enough. The MPU might return a value of 179° or 181° when it should be at 180°, because the motor could stop the robot fast enough (inside the time span it needs to travel 1°). In your current logic, this would trigger another turn command. Since you are only turning in one direction, this can create an instable system, which will turn infinitely.
This kind of problem is often solved by using a feedback loop control (of course in combination with the ability to control/turn into both directions). A good and useful example is a PID control (Proportional, Integral, Differential: This is how the control is mathematically structured), where there are already Arduino libraries for it (like this one). If you want it easier, you can define a range of angles, which are acceptable for your positioning (where it should stop) (for example 175° to 185°). The size of the range, that you need, would depend on the mechanics of your robot and the motor. Note, that this also has drawbacks, but it might be easier for now, depending on what exactly you want to achieve.

As Tom pointed out in his comment, you also get trouble with your first approach, if the method getAngleZ() returns not an integer, but a float, which it indeed does. You can see this in the source code of the used library here. The line
float getAngleZ(){ return angleZ; };

tells us, that the return type of the method is float. The problem with this type is, that it cannot represent every rational value inside it's range. There are gaps between two following float values. The values inside this gap cannot be represented by float. Instead a value nearby will be used (Actually I'm not sure, how this is been done. Probably by going to the next lower value, like with int). This also means, that not every integer is representable by float. Even if the Z angle is exactly 180°, the float value may be something like 179,98. But since 179,98 is not equal too 180 the statement
mpu6050.getAngleZ() == 180

would never become true. Of course the mentioned solutions above apply here too.

I completely agree, and I would also check that getAngleZ() returns an integer, not a float or double.

You are right, I have not thought of this. I will add it to the answer. thx


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

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

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

Thanks for the comments guys. Please keep the good ideas coming. So what you're telling me is that I should look into the library called libuvc https://github.com/ktossell/libuvc ? Could this library actually work with the Arduino Uno / Mega and the Arduino IDE ? Or do you know of another UVC library that's compatible with Arduino ? I couldn't find anything UVC related in the Arduino Library Manager.

@Passerby If this is an old webcam, it may not use the UVC protocol.

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

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

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


text:
Can a push button be used for TFT LCD screens?
I am trying to link my TFT LCD touch screen to a few push buttons. May I enquire why my code is not working? I'm trying to link the screen and the button so I'm trying to make the image display a flower if the button is not pushed and the tiger only if pushed.
At the moment this code ends up displaying both images at once and the button whether or not the button is pushed.
My components include a 2.8" TFT LCD screen and an Arduino Mega

#include <SD.h>
#include <SPI.h>
#include <LCD_GUI.h> //Core graphics library
#include <LCD_KBV.h> //Hardware-specific library

LCD_KBV mylcd(ILI9341,A3,A2,A1,A0,A4); //model,cs,cd,wr,rd,reset

#define BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

#define PIXEL_NUMBER  (mylcd.Get_Display_Width()/4)
#define FILE_NUMBER 4
#define FILE_NAME_SIZE_MAX 20

const int buttonPin = 41;
int buttonState = 0;

uint32_t bmp_offset = 0;
uint16_t s_width = mylcd.Get_Display_Width();
uint16_t s_heigh = mylcd.Get_Display_Height();
//int16_t PIXEL_NUMBER;

char file_name[FILE_NUMBER][FILE_NAME_SIZE_MAX];

uint16_t read_16(File fp)
{
    uint8_t low;
    uint16_t high;
    low = fp.read();
    high = fp.read();
    return (high<<8)|low;
}

uint32_t read_32(File fp)
{
    uint16_t low;
    uint32_t high;
    low = read_16(fp);
    high = read_16(fp);
    return (high<<8)|low;
 }

bool analysis_bpm_header(File fp)
{
    if(read_16(fp) != 0x4D42)
    {
      return false;
    }
    //get bpm size
    read_32(fp);
    //get creator information
    read_32(fp);
    //get offset information
    bmp_offset = read_32(fp);
    //get DIB infomation
    read_32(fp);
    //get width and heigh information
    uint32_t bpm_width = read_32(fp);
    uint32_t bpm_heigh = read_32(fp);
    if((bpm_width != s_width) || (bpm_heigh != s_heigh))
    {
      return false;
    }
    if(read_16(fp) != 1)
    {
        return false;
    }
    read_16(fp);
    if(read_32(fp) != 0)
    {
      return false;
     }
     return true;
}

void draw_bmp_picture(File fp)
{
  uint16_t i,j,k,l,m=0;
  uint8_t bpm_data[PIXEL_NUMBER*3] = {0};
  uint16_t bpm_color[PIXEL_NUMBER];
  fp.seek(bmp_offset);
  for(i = 0;i < s_heigh;i++)
  {
    for(j = 0;j<s_width/PIXEL_NUMBER;j++)
    {
      m = 0;
      fp.read(bpm_data,PIXEL_NUMBER*3);
      for(k = 0;k<PIXEL_NUMBER;k++)
      {
        bpm_color[k]= mylcd.Color_To_565(bpm_data[m+2], bpm_data[m+1], bpm_data[m+0]);
        m +=3;
      }
      for(l = 0;l<PIXEL_NUMBER;l++)
      {
        mylcd.Set_Draw_color(bpm_color[l]);
        mylcd.Draw_Pixel(j*PIXEL_NUMBER+l,i);
      }
     }
   }
}

void setup()
{

    Serial.begin(9600);
    pinMode(buttonPin, INPUT);
   mylcd.Init_LCD();
   mylcd.Fill_Screen(BLUE);
   //s_width = mylcd.Get_Display_Width();
   //s_heigh = mylcd.Get_Display_Height();
   //PIXEL_NUMBER = mylcd.Get_Display_Width()/4;
   if(PIXEL_NUMBER == 60)
   {
       strcpy(file_name[0],"flower.bmp");
       strcpy(file_name[1],"tiger.bmp");
       strcpy(file_name[2],"tree.bmp");
       strcpy(file_name[3],"RedRose.bmp");
   }
   else
   {
       strcpy(file_name[0],"01.bmp");
       strcpy(file_name[1],"02.bmp");
       strcpy(file_name[2],"03.bmp");
       strcpy(file_name[3],"04.bmp");
   }
  //Init SD_Card
   pinMode(10, OUTPUT);

    if (!SD.begin(10))
    {
      mylcd.Set_Text_Back_colour(BLUE);
      mylcd.Set_Text_colour(WHITE);
      mylcd.Set_Text_Size(1);
      mylcd.Print_String("SD Card Init fail!",0,0);
    }
}

void loop()
{

 buttonState = digitalRead(buttonPin);

    File bmp_file;
    if (buttonState == HIGH)
    {bmp_file = SD.open(file_name[0]);
      } else {bmp_file = SD.open(file_name[1]);
      }

       if(!bmp_file)
       {
          mylcd.Set_Text_Back_colour(BLUE);
         mylcd.Set_Text_colour(WHITE);
         mylcd.Set_Text_Size(1);
         mylcd.Print_String("didnt find BMPimage!",0,10);
         while(1);
        }

          draw_bmp_picture(bmp_file);
         bmp_file.close();
         delay(2000);
     }

First of all, I suggest you to keep your source code tidy, this makes a lot easier to follow the flow.
As I don't know the library you are using, I'm assuming you have tested loading one single image works as expected in which case you probably need to wipe the screen before drawing a new image: I can't tell for sure because you didn't mention which library you are using (a link would have helped).
If there's a function named clear, emptyBuffer or similar, then you should call it before drawing the image, otherwise, you probably have to draw a filled rectangle in the same area where you are going to put your image.


text:
How to read a PWM OUTPUT PIN value?
How to get a pwm pin value that is in pinMode OUTPUT?
How to get a digital OUTPUT PIN value:
#define pin 3

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

void loop()
{
    delay(1000);
    digitalWrite(pin, HIGH);
    Serial.println(bitRead(PORTD,pin));
    delay(1000);
    digitalWrite(pin, LOW);
    Serial.println(bitRead(PORTD,pin));
}

For testing reasons, I want to get PWM output pin value.
Incorrect sketch:
#define pin 3

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

void loop()
{
    delay(1000);
    analogWrite(pin, 100);
    Serial.println(pulseIn(pin, HIGH)); // value of the PWM output pin
}

This sketch was created for example only.
I don't know PWM value because PWM value will be generating dynamically.
Could you explain how to get a PWM output pin value, please?

You can't. There is no single "value" for it, it's constantly changing. You could average it through a low-pass filter and feed it back through an analog pin. Or you could connect it to an input pin and measure pulse width and frequency, but you can't do it on the pin itself. Not with normal Arduino tools. Besides, you know the value already. It's "100", since that's what you set it to. What are you actually trying to achieve?

BTW: the first sketch reads value in POTD register, not the value on the actual pin. It might be for example shorted and PIND register would read it correctly. It's possible to read the actual value (by reading PIND) but as Majenko wrote, it's changing, so you'd have to read it at constant rate or measure the low and high time. Funny, the pulseIn should be actually working as it must be using PIND internally

Maybe you would be able to get the value back by reading the corresponding Output Compare Registers of the used timer (I think, this is used for the generation, though I didn't check).

store the value to a variable. that is the right way. but if your task is to read the generated pwm on analog pin, then https://arduino.stackexchange.com/questions/55698/read-analog-port-set-as-output/55700#55700

According to the source code implementation of analogWrite function
(Arduino analogWrite source code explanation).
You can use OCRnx register for reading PWM value.

That would be OCR2B for pin 3.

I want to get PWM output pin value.

The pin will either be 0 or 1.

analogWrite(pin, 100);

It will be 1 for 100/256 (39%) of the time, and 0 the rest of the time.

Why do you want to do this?

Because I'm seeking a solution for solving this question without creating a new variable for store the PWM value.

As mentioned in another answer you could interrogate the timer's register to see what value the analogWrite put there, but why bother doing this obscure thing (which would change for every output pin) when you can save the value in one byte in a variable? Also, that is not the "output pin value" but the duty cycle of the PWM output.


text:
Debug-logging without using Serial.print and without WiFi
In order to transmit text from the Arduino board to the HC-05 Bluetooth module, I have use Serial.print. However, I don't see a way to debug the code without using Serial.print to test the other features of the software. Is there another way to transmit text from the Arduino to the computer, and from the Arduino to the HC-05, simultaneously (and without WiFi)?

Yes. Plenty. You could add WiFi to it. You could use an external UART adaptor and SoftwareSerial. You could add Ethernet to it. There's many ways.

WiFi isn't available in this case. I'll edit the question.

The simplest is probably to just use SoftwareSerial and an external USB to UART adaptor. Or just move the HC-05 to other pins and use SoftwareSerial with it (as long as you're no faster than around 9600 baud).

Yes, what version of Arduino are you using?

For Arduino Mega, you can use Serial.println for writing debug data and Serial1.println for communication with HC-05. (See Example: MultiSerial Example)
For other Arduino boards, you can use Serial.println for writing debug data and SoftwareSerial library for communication with HC-05. (See Example: SofwareSerial)

I'm using an Arduino Uno.

Ok, connect RXD pin and TXD pin of HC-05 to pin 10 and 11 of Arduino Uno and follow SoftwareSerial example. https://www.arduino.cc/en/Tutorial/SoftwareSerialExample


text:
Why does my 16x2 LCD displays weird letters and can't insert key from keypad?
I'm a newbie on Arduino here, and this is my first project on 16x2 LCD, 4x4 keypad and others. So, the story is, after I uploaded the program for my group's Arduino alarm clock to the Arduino board, the LCD displays black boxes on the first row of the LCD. But after soldering the LCD pins again and connect the Vo to the 10k ohm potentiometer, the LCD can display the "welcome" part properly. This can be seen in the two pictures below.

However, after a while, there are weird letters appearing on the second row of the LCD, blinking from the first picture below to the second picture again and again. Plus, I couldn't input any key from the keypad to the LCD, since the display's stuck at there.

I'm not sure if there's any problem in the circuit or in the programming. I'm quite confused here. Below is the code I uploaded to the Arduino board. Thank you in advance.

#include <EEPROM.h>
#include <Keypad.h>
#include <DS1307.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <LiquidCrystal.h>

DS1307 rtc(SDA, SCL);
LiquidCrystal lcd(A3, A2, A1, A0, 5, 4);
Time t;

#define buz 3

int Hor, Min, Sec, h, m, s;
int ASCII = 48;
char* tim;
char* dat;
const char key = 0;
char buffer[2];
const byte numRows= 4;
const byte numCols= 4;
char keymap[numRows][numCols]=
{
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
byte rowPins[numRows] = {12, 11, 10, 9};
byte colPins[numCols]= {8, 7, 6, 5};
Keypad myKeypad= Keypad(makeKeymap(keymap),rowPins, colPins, numRows, numCols);

void setup() {
  Wire.begin();
  rtc.begin();
  pinMode(buz, OUTPUT);
  lcd.begin(16, 2);
  welcome();

  rtc.setDOW(SATURDAY); //Set Day-of-Week to SUNDAY
  rtc.setTime(10, 54, 0); //Set the time to 12:00:00     (24hr format)
  rtc.setDate(7, 1, 2017); //Day, Month, Year
}

void loop() {
  t = rtc.getTime();
  Hor = t.hour;
  Min = t.min;
  Sec = t.sec;
  tim = rtc.getTimeStr();
  dat = rtc.getDateStr();
  char key = myKeypad.getKey();

  if (key == 'C'){
    digitalWrite(buz, LOW);
    EEPROM.write(2, ASCII+6);
    EEPROM.write(3, ASCII);
  }

  if(key == '#'){
    lcd.setCursor(0,0);
    lcd.print("Enter New Time");
    lcd.setCursor(0,1);
    int j =0;
    int i=0;
    while( j<6)
    {
      if(i==2 || i == 5){
        lcd.print(":");
        lcd.display();
        i++;
      }
      key=myKeypad.getKey();
      if(key)
      {
        lcd.print(key);
        lcd.display();
        EEPROM.write(j,key);
        j++;
        i++;
      }
    }
  }

  changealarm();
  checkalarm();
  timedate();
}

void checkalarm(){
  if( Hor == h && Min == m)
  {
    delay(3000);
    lcd.setCursor(0,1);
    lcd.print("Hold C");
    digitalWrite(buz, HIGH);
    delay(3000);
  }
}

void changealarm(){
  buffer[0]=EEPROM.read(0);
  buffer[1]=EEPROM.read(1);
  h = atoi(buffer);
  buffer[0]=EEPROM.read(2);
  buffer[1]=EEPROM.read(3);
  m = atoi(buffer);
  buffer[0]=EEPROM.read(4);
  buffer[1]=EEPROM.read(5);
  s = atoi(buffer);
}

void timedate(){
  lcd.setCursor(0,0);
  lcd.print("Time: ");
  lcd.print(rtc.getTimeStr());

  lcd.setCursor(0,1);
  lcd.print("Date: ");
  lcd.print(rtc.getDateStr());
  delay(3000);
  lcd.setCursor(0,1);
  lcd.print("Alarm: ");
  lcd.print(h);
  lcd.print(".");
  lcd.print(m);
  lcd.print(".");
  lcd.print(s);
  delay(3000);
}

void welcome(){
  lcd.setCursor(0,0);
  lcd.print("Welcome");

  lcd.setCursor(0,1);
  lcd.print("To");
  delay(3000);

  lcd.setCursor(0,1);
  lcd.print("TIMeProject");
  delay(3000);
}

Which of the many DS1307 libraries are you using in paricular?

I use DS1307 library from this website http://www.rinkydinkelectronics.com/library.php?id=34

Only a beginner would try to make a full project work. An more experienced programmer makes a small part and test if it works, and then another part and so on. You could make a small sketch to test the buttons for example. A text has a zero terminator. Make your buffer 10 or 16 or 40, but not just size 2. Set buffer[2] to '\0' before calling atoi. The 'key' is printed on the display, I think that is what you see.

I've already changed the changealarm() code according to jose can u c's solution, but the weird letters are still there. What should I do?

In your changealarm() function, you call atoi(buffer), and buffer is defined as char buffer[2].
atoi() expects a c-style string, which is null-terminated, and you have to include space for the null termination character ('\0', 0, 0x00, etc.), but you write to both allocated spaces in the changealarm() function. If your 2nd byte of each EEPROM space (1, 3, 5) is non-zero, then your have an unterminated string.
atoi() expects a null-terminated string, and so the behavior is unexpected. Probably atoi() is running into other memory. If the string being sent is not representable by a int type, then the behavior of atoi() is undefined.

A quick fix would be to increase the size of buffer and guarantee null termination:
char buffer[3];  // Make the buffer 3 bytes long
[...]
void changealarm() {
  buffer[2]=0;   // Set the 3rd byte to zero to null-terminate

  buffer[0]=EEPROM.read(0);
  buffer[1]=EEPROM.read(1);
  h = atoi(buffer);
  buffer[0]=EEPROM.read(2);
  buffer[1]=EEPROM.read(3);
  m = atoi(buffer);
  buffer[0]=EEPROM.read(4);
  buffer[1]=EEPROM.read(5);
  s = atoi(buffer);
}

I see. But what's I'm supposed to do? Should I change the atoi() part? I'm a bit confused.

I updated my answer to show a solution to the overflow problem. (There are other problems in your code, too, like a lot of 3000ms delays where nothing can happen; not even keypad presses)

I've changed the changealarm() part according to your solution. And I've tried to change the delays to 1000ms. But still, the same display occurs. So, I'm guessing, there's something wrong at the if(key == '#') ... part?

How long after the sketch starts does the junk display occur? Does it occur if you press no keys at all?

After I changed the delays to 1000ms, the junk display occurs a second after the lcd.print("TIMeProject"); display. It keeps on blinking the junk display automatically. And yes, it occurs if I press no keys at all, right after I uploaded the code to the board.

The weird letters displayed problems are solved! It turns out that the keypad pins were connected differently with the code uploaded.


text:
Changing parameters in Arduino without the IDE
I’m installing Arduino-based well monitors in my local community.  Each well is different and has slightly different parameters and several hardware variations.  Currently, when I need to make a program change I have to uninstall the Arduino, bring it back to my computer, reprogram it, then reinstall it.  I’m developing these units as I go so there are various refinements that arise as well. I’d love to be able to reprogram a unit in place.  It seems like it could be done with another Arduino but I don’t currently have the skills for that.  The second, less flexible, method would be to use dip switches to select various options.  This option is attractive but would limit me to only the options that I know of at programming time.  Is there a third option I haven’t thought of?  Has anyone else tried programming one Arduino from the other?
Edit: I’m primarily using Unos but I’m working on a low power version that will use a Mini Pro. The units are accessible as far as USB cables and such. However I don’t own a laptop.

Please tell us what arduino board you use. Can you connect a (usb) cable to it? Can you connect a laptop to the arduino without removing it from the well? Perhaps you can write a command line interface and store values in eeprom. Then you can connect a laptop to the arduino and change values. Update your question with the extra information please.

You could maybe adapt this: https://www.gammon.com.au/bootloader

i would use an esp8266's SPIFFS to store the config; then you can program it from your phone.

Sounds like you need a Standalone programmer. I offer one, it loads the target device from a program you select on SD card.  Up to 256 programs can be stored on 1 card.
Check it out here  www.crossroadsfencing.com/BobuinoRev17/Programmer.html


text:
Avrdude verification error after months of successful use
I have a 2560 that I've been working with for a while (over a year for sure), programming it with an avrisp mk2. No issue this whole time, then suddenly, a couple of days ago it starts failing with
avrdude: verification error, first mismatch at byte 0x0002
         0x01 != 0x95
avrdude: verification error; content mismatch

And very obviously not flashing (there's logic that blinks the LED on boot, and the LED isn't blinking anymore).
The first time this happened, the board appeared completely dead - the programmer wouldn't recognize it, and refused to flash it. After a few days and magic it started recognizing it again, and going through the motions of flashing my firmware, but the verification error persists. The location of the error hasn't changed, nor has the two values (0x01 vs 0x95).
Any ideas what this could be?

I have seen this myself. It turned out that coms were a little distorted. If you have access to one, use an oscilloscope to view the waveforms of the 4 ISP pins.

Similar to: https://arduino.stackexchange.com/q/44965/19409 https://arduino.stackexchange.com/q/30946/19409 https://arduino.stackexchange.com/q/52798/19409

@sa_leinad why would the coms get distorted after such a long time? i'll scope it tonight when i can.

Track corrosion, static damage, dry joint just to name a few.

I am running into the same program with Arduino Uno when using avrdude from the command line. Burning the bootloader before uploading my code similarly solves the problem.

Still don't know why, but now have a fix. Re-running the 'Burn bootloader' command from Arduino allowed me to then burn my firmware. Not sure if the issue is with fuses somehow being changed, or what, but this seems to have fixed the issue.
One more fun fact - I tried the same thing on a brand new Mega - same effect. First trying to burn my firmware resulted in a verification error (at a slightly different address), then burned bootloader and re-burned my firmware successfully. Wondering if an update to boards.txt or avrdude came through and changed something.

Had the same problem. Did the same thing: burn bootloader then burn my sketch. It worked.

TLDR: Make sure that -D flag is not used when calling avrdude to upload your app using the ISP programmer.
After burning the bootloader on a bare ATmega328p chip using the Arduino IDE and an Arduino Uno as ISP, I am running into the same problem that the OP mentioned with this message:
avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0094
         0x68 != 0x6a
avrdude: verification error; content mismatch

Right after burning the bootloader, I can upload an application using this avrdude command (yours would vary slightly due to port name, etc.):
avrdude -C/etc/avrdude.conf -v -patmega328p -cstk500v1 -b19200 -P/dev/ttyACM0 -D -Uflash:w:main.hex:i

However, if I change the application code, recompile, and rerun the same avrdude code again, then I get the verification error mentioned by the OP.
In my case, I have confirmed that the -D flag is the problem. In fact, if I remove the -D flag in the avrdude command above, then I can change, compile, and upload my code as many times as I want.
Note that this is different when using the Arduino IDE to program an Arduino Uno directly (using serial communication through the bootloader), where the -D flag is used
avrdude -C/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:main.hex:i

since you wouldn't want to erase the bootloader on the Arduino Uno. Somehow using the -D flag is OK in that case.


text:
How do I choose a battery to power my Arduino Nano project?
I was wondering if anyone would be willing to teach me how to logically choose/calculate which battery I should/can use to power my Arduino nano project (so I don't have to keep it connected to my computer to use it)? I am interested in learning, not just being given an answer because my goal is to be able to figure this out on my own for my next project. (Also, I got this far by myself because of a lot of trial and error in addition to reading as much as possible, but I don't want to buy an assortment of batteries for my trial and process of learning.) Thank you kindly.
If you are willing to teach, I have included all of the details about my project in the code below or at least I think I did.
Before I get to my code, one problem (I think) is that the two digit seven segment LED display that I bought for my project does not have a data sheet. However, even if it did, I am not sure that I would understand how to use it. I looked up other similar LED displays and if I understand what I am looking at, they seem to use between 2-3 V and 20-30 mA.
I thought that because I saw 2-3 V on the similar looking LED displays, I would be able to use a 3V battery to power my project. However, when I tried the following two batteries to power my project they did not work:

3V CR2032 lithium cell battery (for LilyPad) - this was enough power to dimly turn the power light on the nano, but not enough to turn the lights on for my project.
E-Textiles Battery 3.7 V - 110mAh (2C Discharge) - this was also enough to dimly turn the power light on the nano, but not enough to turn the lights on for my project.

Because those did not work and it's all I had left, I tried a 9V battery:

9V battery - this powers the project just fine, but I was hoping to calculate the actual voltage and/or current because I was hoping to use one of the tiny lithium ion batteries from SparkFun.com (or elsewhere) to power my project if this is possible.

Here is my code (Sorry that the code is a bit long. I couldn't figure out how the SevSeg library worked, so I just wrote my own code):
/************************************************************************************************************************
Rebecca Wilson
12/17/18

This program is for using an arduino nano to run a 2 digit 7 segment LED display. I made it as a life counter for
MTG, so it displays "20" to start and there are two buttons that can be used to change the life total by +/- 1.

These are the pieces I used:

1x Nano 3.0 Controller compaitible with arduino nano CH340 USB driver (taydaelectronics.com; SKU A-2864)
    *You must select "ATmega328P (Old Bootloader)" for the processor (otherwise it can't upload the file to the nano).
    *This also works with an arduino UNO, but I prefer to change the negativeButtonPin to 13 for the arduino Uno (I don't
     think pin 13 works on my nano because it is connected to the practice LED that comes attached to the board).

1x LED Display 7 segment 2 digit 0.28 Inch common anode HI RED (taydaelectronics.com; SKU A-1701)

2x Tact switch 6x6mm 5mm through hole SPST-NO (taydaelectronics.com; SKU A-5127)

2x 330 Ohm 1/4W 5% carbon film resistor (taydaelectronics.com; SKU A-2067)

breadboard and jumper wires

This is what I understand about the LED display:
  LOW means that the segment is turned on
  HIGH means that the digit is turned on and when that digit is turned on all segments are set to LOW (turned on)
*****************************************************************************************************************************/

//declare constants
int tensDigit = 10; //330 Ohm resistor between digit pin and nano pin
int onesDigit = 11; //330 Ohm resistor between digit pin and nano pin

int pinA = 2;
int pinB = 3;
int pinC = 4;
int pinD = 5;
int pinE = 6;
int pinF = 7;
int pinG = 8;
int pinDP = 9;

int positiveButtonPin = 12; //and the other side of the button is connected to the GND pin next to D2
int negativeButtonPin = A0; //and the other side of the button is connected to the GND pin next to D2

//declare variables
unsigned long lastPositiveDebounceTime = 0;
unsigned long lastNegativeDebounceTime = 0;
unsigned long debounceDelay = 100;
unsigned long previousMillis = 0;

int currentPositiveButtonState = HIGH;
int currentNegativeButtonState = HIGH;
int lastPositiveButtonState = LOW;
int lastNegativeButtonState = LOW;
int trueLastPositiveButtonState = LOW;
int trueLastNegativeButtonState = LOW;
int buttonPushCounter = 0;
int startingValue = 20;
int currentValue = startingValue;

//declare functions
void delayTime(unsigned long milliseconds);
void setDigit(int place, int number);
void setNumber(int number);

void setup() {

  pinMode(tensDigit, OUTPUT);
  pinMode(onesDigit, OUTPUT);
  pinMode(pinA, OUTPUT);
  pinMode(pinB, OUTPUT);
  pinMode(pinC, OUTPUT);
  pinMode(pinD, OUTPUT);
  pinMode(pinE, OUTPUT);
  pinMode(pinF, OUTPUT);
  pinMode(pinG, OUTPUT);
  pinMode(pinDP, OUTPUT);

  pinMode(positiveButtonPin, INPUT_PULLUP);
  pinMode(negativeButtonPin, INPUT_PULLUP);

  Serial.begin(9600);
}

void loop() {

  setNumber(currentValue);

  //read the current button state
  currentPositiveButtonState = digitalRead(positiveButtonPin);
  currentNegativeButtonState = digitalRead(negativeButtonPin);

  //if the positive button state has changed then record the new current time
  if (currentPositiveButtonState != lastPositiveButtonState)
  {
    lastPositiveDebounceTime = millis();
  }

  //if the button state did not change during the debounceDelay time, then consider it a true state change and...
  if ((millis() - lastPositiveDebounceTime) > debounceDelay)
  {
    //if the last true button state has changed then...
    if (currentPositiveButtonState != trueLastPositiveButtonState)
    {
      trueLastPositiveButtonState = currentPositiveButtonState;

      //if the button was pressed then increment the button pressed counter
      if (currentPositiveButtonState == LOW)
      {
        currentValue++;
        setNumber(currentValue);
        Serial.println(currentValue);
      }
    }
  }

  //change the last button reading to the current button reading
  lastPositiveButtonState = currentPositiveButtonState;

  //if the negative button state has changed then record the new current time
  if (currentNegativeButtonState != lastNegativeButtonState)
  {
    lastNegativeDebounceTime = millis();
  }

  //if the button state did not change during the debounceDelay time, then consider it a true state change and...
  if ((millis() - lastNegativeDebounceTime) > debounceDelay)
  {
    //if the last true button state has changed then...
    if (currentNegativeButtonState != trueLastNegativeButtonState)
    {
      trueLastNegativeButtonState = currentNegativeButtonState;

      //if the button was pressed then increment the button pressed counter
      if (currentNegativeButtonState == LOW)
      {
        currentValue--;
        setNumber(currentValue);
      }
    }
  }

  //change the last button reading to the current button reading
  lastNegativeButtonState = currentNegativeButtonState;

}

void setNumber(int number) {

  int onesPlace = number % 10;
  setDigit(1, onesPlace);
  delay(5);
  int tensPlace = number / 10;
  setDigit(10, tensPlace);
  delay(5);
}

//place is 1 if setting the ones place and 10 if setting the tens place
void setDigit(int place, int number) {
  switch(place)
  {
    case 1:
      digitalWrite(onesDigit, HIGH);
      digitalWrite(tensDigit, LOW);
      break;
    case 10:
      digitalWrite(onesDigit, LOW);
      digitalWrite(tensDigit, HIGH);
      break;
  }

  switch(number)
  {
    case 0:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, LOW);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, HIGH);
      digitalWrite(pinDP, HIGH);
      break;
    case 1:
      digitalWrite(pinA, HIGH);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, HIGH);
      digitalWrite(pinG, HIGH);
      digitalWrite(pinDP, HIGH);
      break;
    case 2:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, HIGH);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, LOW);
      digitalWrite(pinF, HIGH);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
    case 3:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, HIGH);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
    case 4:
      digitalWrite(pinA, HIGH);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
    case 5:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, HIGH);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
    case 6:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, HIGH);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, LOW);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
    case 7:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, HIGH);
      digitalWrite(pinG, HIGH);
      digitalWrite(pinDP, HIGH);
      break;
    case 8:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, LOW);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
    case 9:
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, LOW);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, LOW);
      digitalWrite(pinDP, HIGH);
      break;
  }
}

Your post seems to have two questions.  One, battery power, is well documented and you can find the answer on the Arduino website.  The other is to do with understanding the 7-seg display, which is not apparent in the title of the question.  Did you use current-limiting resistors?  Google "7 segment display resistor" and there are plenty of tutorials (including video) on how to use.

How are you attempting to connect the various batteries you have tried?

Stackexchange works best one question at a time.  The assumed goal is to build a searchable data base of questions and answers for others with similar questions.  Multiple questions and long discussions make this goal difficult to realize.  That said, batteries are chosen for a number of reasons.  Some, like cost and weight, you may not even care about.  And more then not, several different batteries can be used for the same application.  So, it may come down to opinion.  Yet another format which stackexchange uses normally avoid...

(1) Yes, as I stated in my code, I used a 330 ohm resistor between each of the two seven segment digit pins and the Arduino nano pin.

(2) I connected the positive terminal of my battery to pin 30 which is labeled as VIN on the Arduino Nano and the negative terminal of my battery to pin 29 which is right next door and labeled as GND.

(3) Sorry, my question may not have been clear because I was/am so confused. I don't understand how my computer is powering my project and I thought that when I added a different power source that there was some kind of calculation I needed to do to determine what voltage I should use depending on what I put in my circuit. I am now guessing there is no calculation. There are an overwhelming number of batteries to choose from and I thought this calculation would narrow it down. However, I guess I should just use any battery between 7 and 12 V and it doesn't matter what I put in my circuit.

Consider the length of time needed with out external power and the average current the project demands.  Multiply these two giving Amp-Hours.  Then, given the Amp-Hours are reasonable, choose a battery with twice the Amp-Hour capacity.  Battery ratings are usually ideal.  In that the slower the power is pulled from the batteries the larger the battery capacity will appear.
It goes without saying you need enough cells to generate the specified voltage.  Cell voltage varies by chemistry.  Consequently note the exact voltage of a cell or pack of cells.  Especially when building your own serial battery packs where slight differences add up to significant voltages.
Lastly consider if primary or secondary batteries are to be used.  Primary cells such as alkaline batteries are long lasting and generally safer.  Secondary batteries such as Lithium-ion offer good power density but are difficult to care for.

Thank you for your help. I attempted to follow the directions that came with my multimeter and measured the current of my circuit as 28 mA. If I understand correctly, if I want my project to run for 4 hours at a time then I should buy a battery with at least 224mAh.

Concerning the voltage, I feel really stupid. For some reason, I was imagining that I should use ohm's law (or something else) to do some kind of calculation (which I was not grasping) to determine the proper voltage of the battery to use. However, would I now be correct to assume that there is no calculation that I should do? Instead, I just need to use between 7 and 12 V because that is what the instructions say that the nano needs and it doesn't actual matter what pieces I put in my circuit.

I believe both of your comments are correct.  Most batteries are have better than 224mAh so it should be easy to find even small batteries that satisfy this minimum.  Processors current demands can vary depending on what the processor is doing.  And over engineering battery life by an order of magnitude rather than double may be prudent.  When using any on board regulator, inferred by the wide range of acceptable voltages, be careful and double check you are connecting to the proper power pins.  Directly powering a 3 or 5 volt processor with these higher voltages can damage the processor.

I should add that managing portable processor based devices to extend battery life is not trivial.  Professional developers spend hours if not days selecting and configuring processors to operate as expected while only "sipping" nAmps and uAmps of current 90% of the time.

I don't think this will be a fully fledged answer, but I want to tell you a useful alternative to batteries you already used. I usually power my projects through a 5V "powerbank" that I do myself. All you need is a step-up board like for example 134N3P and any Li-Po/Li-Ion 3,7V cell. The 134N3P is very small and it contains a undervoltage and overcurrent protection circuits so you won't destroy the cell. It also allows to safely charge that cell using any USB charger. The Li-Po/Li-Ion cells come in all shapes and sizes. For miniature projects you can find one in size of a two coin batteries, but for regular size projects I suggest 18650 cells as the cheapest option.

Thank you. This is very interesting. I was not aware of this option.


text:
Guideline in library creation
According to this example, creation of an Arduino library is quite understandable.
But a few things I would like ask (mostly regarding to what to be defined where) when a library is not that simple:

Where to put additional libraries (such as <Wifi.h>) in .h or .cpp, since it works when defined in each one of them?
What is the purpose of defining variables in the :private section? Since they can be defined inside constructor, and as far as I know/tested, it works as well.
In a .cpp file, does it matter when instances or variables are defined outside a class (at the beginning of code ), since again, it works the same?

Where to put additional libraries (such as ) in .h or .cpp, since it works when defined in each one of them?

It doesn't really matter as long as the parts of your library that need to see the headers can see them.  Personally I put all headers in the master .h file and then that gets included in the .cpp file(s). It just keeps it all in one place and is easier to manage.

What is the purpose of defining variables in the :private section? Since they can be defined inside constructor, and as far as I know/tested, it works as well.

You need to understand "scope".  Defining a variable inside the constructor means that it's only available within that constructor.  This is "local" scope.  Defining the variable in the class, within the "private" section makes that variable available to every function within the class.  Putting it in "public" makes it available to anyone anywhere.

In a .cpp file, does it matter when instances or variables are defined outside a class (at the beginning of code ), since again, it works the same?

Again this is a matter of "scope".  A variable declared outside the class is in "global" scope. There is only one copy of each of these variables, and all instances of the class share the same physical variable. It is the same as declaring a class variable as "static" - it makes it common to all instances of the class.  If the data you need to store is specific to a class instance (which most of the time it is), you do not want to use global variables. In general it's bad form using global variables if you don't have to.
Incidentally, you may see variables defined both in the class and at the top of the CPP file.  This is a special case where you have static variables in your class, which don't have any storage space allocated to them (normally a variable has its storage space allocated when you create an instance of the class, but that doesn't happen with static variables for obvious reasons), so you have to manually provide the storage space with a separate entry in the CPP file.

Thank you very much. Now it is clearer. Regarding include external libraries in .h file : As far as I understand, this file only defines the structure of a class, and not for actual coding, right? If so- why should I define libraries in .h file?

Another thing: I was not aware that a library can hold more than one class, so that explain the locale of variables more clearly, but as far as I understood- lib file and class had to be the same, isn’t?

A header file is not a library. It is just a file. It gets included verbatim wherever the #include is. Including a library's header file does not get you the library code, only the header. It's down to the IDE to then find the CPP files and compile them for you. The name of a header file does not have to match the name of the class. It's not like Java. You can have as many classes as you like in a header file. Or none if you so wish.

Where to put additional libraries (such as <Wifi.h>) in .h or .cpp, since it works when defined in each one of them?

Any library can reference any other library. So including another library in your library is the same as including in the sketch. They should be on standard locations.
Include the other libraries .h in the file where you need it. If you use something from the other library in your .h, include it there. If you need it only in .cpp include it there.

What is the purpose of defining variables in the :private section? Since they can be defined inside constructor, and as far as I know/tested, it works as well.

With declaring a class member as private, the author of the class tells: don't use it, it is for internal use and can change in future versions.

In a .cpp file, does it matter when instances or variables are defined outside a class (at the beginning of code ), since again, it works the same?

If the variable is not a member of the class, then if you create two instances of the class they will share the variable. A variable in constructor is restricted to the constructor's scope.

thank you, 1) but where should it be placed ? .h or .cpp ? 2) the basic meaning of private I understand, but variables ( private) can be declared inside .cpp file also... so what is the difference ?

where should be placed your library or the libraries it uses? the libraries it uses should be placed the same way as for sketch. installed with Library Manager or copied in libraries subfolder of the sketches folder

how inside .cpp?

I know where to place to folder containing .cpp and .h file. My question is where is declare the use of a certain library ( such as <Wifi.h>'), in .hor.cpp`

you use it. nothing more. the user of your library should have them installed

I guess I don’t explain we’ll- let’s say that in my library I wish to use external, installed library (which operates as needed in a sketch ). Now I wish it will be declared in my library, so where should I WRITE ‘#include <lib.h’ ? In ‘.h’ file ? Or in ‘.cpp’ file ?

where you need it. if you need it only i cpp, pu it there. if you need it in .h put it there

Regarding 1: prefer to add it in the sketch/.cpp file only. If this is not possible (because you need the class to be known in the header file, only than add it in the header.
Reason: a header file is typically included by many other files and adding an include results in more coupled code, making later maintenance more difficult.
Regarding 2/3: See also the somewhat related answer of me in why-to-store-a-function-parameter-value-in-a-class-private-variable.


text:
RTC DS1307 VCC not getting connected to 5V of Arduino Uno
I am using RTC DS1307 with "TINY RTC I2C modules" written on it.I had downloaded RTClib library from adafruit and using the example code. I connected GND->GND, VCC->5V, SDA->A4 and SCL->A5. However after connecting the VCC to 5V the "ON" Led does not lights up and the code is not getting uploaded. I tried connecting the VCC to 3.3 V the code gets uploaded but does not shows any output on the screen.

It seems an hardware problem on Arduino Uno board.
Try to connect the 5V pin of Arduino Uno to a digital pin (e.g D7) and write a program for read a digital pin.
int inPin = 7;     // digital pin 7
int val = 0;       // variable to store the read value

void setup()
{
  pinMode(inPin, INPUT);        // sets the digital pin 7 as input
}

void loop()
{
  val = digitalRead(inPin);     // read the input pin
  Serial.println(val);          // print read value on serial
}

If you're not able to load this sketch on your Arduino, most likely it's an hardware problem on Arduino.

But 5V of Arduino is drawing current to VCC of bluetooth HC05 module

You remove temporary the HC 05 module and try it.

I had tried that and I think there is some hardware problem with my RTC.

Soldering was not done properly. The vcc and ground got "short" that's what the shopkeeper said. We again soldered it on the other side. Now its working

Just another point,
From my experience, any module that uses a serial connection can disrupt the sketch uploading process to the Arduino.
The best is to upload to Arduino when all serial connections are dis-connected.


text:
Distance measuring utilizing (1 or 2) Arduino Nano's
I would like to develop a small-distance measuring device that will be primarily used in indoor scenarios to measure a distance with cm accuracy (mm if possible). The device would be in a small form factor and would calculate the distance it has moved in reference to the starting position. However, upon doing more research I have found that this is a bit harder than I thought it would be. My initial idea was to utilize an accelerometer and take the double integral to determine displacement, however, I learned that this is primarily impossible with consumer grade accelerometers.
My current idea for implementation would utilize a small stationary external device that sends signals constantly back and forth measuring the difference in time it takes the wave of information to be received. I have looked online to find similar projects to this, but could not find any. Perhaps I haven't looked hard enough, but does anyone know if projects like this exist (preferably Arduino based)? If not then, would a simple consumer-based IR sensor work for this situation? Maybe I'm overthinking it and there's an even easier solution for measuring small distances with an external device. I could use some guidance on this. Thank you.

please delete the wifi and bluetooth tags .... those two technologies are not for measuring distance and are not related to your question

the wifi and Bluetooth tags are there as they are possible means of wireless communication that I would have liked to explore to coming to the solution for the specification I am outlining here. Bluetooth and wifi can and have been used to measure the distance between two objects. However, I have not found one to the spec I have mentioned

people researching wifi or bluetooth problems will get your question as containing a possible solution ... do you honestly believe that an accepted answer to your question will actually be of use to them?

No, you're right that people searching for wifi or bluetooth problems will probably not have any use with this topic. However, the topics of wifi and bluetooth are related to this topic, and is that not what tags are for? Because I imagine people researching wifi or bluetooth problem are likely not going to find answers in a majority of the topics tagged with those subjects here (briefly looking through the list of tagged questions that is).

maybe you could use an optical sensor from a mouse  ..... it appears that you want to measure the total distance traveled ..... note: distance in reference to starting point is different from distance traveled, if the travel path is curved

Alright, thanks for the tip about optical sensors, I will definitely look into that. Yes, you're right displacement is the definition for my specification I gave in my opening question rather than total distance traveled. I should have been more clear on that, my apologies.

Try to take a look to Lidar sensors.
Here an interesting guide by SparkFun.

Look at Ping sensor also. Ultrasonic, way less expensive than Lidar.

Ultrasonic ranging module HC - SR04 provides 2cm - 400cm non-contact
  measurement function, the ranging accuracy can reach to 3mm.

https://www.digikey.com/product-detail/en/sparkfun-electronics/SEN-13959/1568-1421-ND/6193598&?gclid=EAIaIQobChMIs4Ltisap3wIVD4zICh0mkwyfEAQYAiABEgILqfD_BwE
Give it a shot, see if the $4 solution meets your needs.

Thanks for the suggestion, however, my specification would require the object in question to work reliably without any nearby walls to reflect the ultrasonic sensor back to it.

So sound won't bounce back - will light (LIDAR?) Are you looking for some mechanical means of measurement?

Light wouldn't work unless it was targeted to the device in question (ultrasonic would work in such a manner as well, but i'm not sure if either is capable of this). Ideally, the object being used to measure the distance should be operatable without the reliance of any external walls. I was thinking of having a device that could move in any direction within a 3-axis plane and the displacement would be measured in reference to an external object that is within line of sight. So more like a transmitter-receiver scenario where the transmitter and receiver are each connected to different devices.

Maybe you could use call back method with a beacon. Target sends out a request, beacon sends it back. Target calculates how far away based on time.  Have the target send it out in several directions while rotating in place to determine where the shortest direction is.  Course, radio waves travel at the speed of sound.  So sound may work better, give you a chance to measure more than just the response time of the beacon.  Or put the Tx unit on a servo and pan it around so you're not changing the target's orientation all the time.

Yes, that sounds like it might be possible, any recommendations/ideas on specific hardware?

Ping sensor as mentioned above, your choice servo panning. Any microservo should do. Send out one code, look for a different back as a response.


text:
HTTP get request using Arduino Uno and ESP8266
I have an Arduino Uno and an ESP8266 and I want to send a HTTP get request to google.com and print the response.
Please help me thanks.

if you have AT firmware in esp8266, use AT commands or WiFiEsp library. the library has examples. for AT commands you can google may examples.

You can use ESP8266Wifi Arduino Library.
Here an example:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void setup () {

  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);
    Serial.print("Connecting..");

  }

}

void loop() {

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

    HTTPClient http;  //Declare an object of class HTTPClient

    http.begin("http://www.google.com");  //Specify request destination
    int httpCode = http.GET();     //Send the request

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

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

    }

    http.end();   //Close connection

  }

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

}

but this is for coding directly on esp8266 I want to upload the code to arduino uno

Ok, do you want to use AT commands? See this post: https://arduino.stackexchange.com/questions/32567/get-data-from-website-with-esp8266-using-at-commands


text:
Most efficent way to adjust value
I am working on a system that starts a process based of a set time value (startHour). The user sets the start hour and can only select values from 00-23. I have been asked to start the same process at 6 hour intervals so that it occurs 4 times during the day.
My initial though is to add three more variable, secondStartHour, thirdStartHour and fourthStartHour. secondStartHour would be assigned a value 6 hours ahead of the startHour, thirdstartHour a value 12 hours ahead of startHour and fourthStartHour would be assigned a value 18 hours ahead of start hour. I could then use any of the startHour variables to trigger the process.
I wrote some code (below) that will work but I'm wondering if there is a better, more efficient way of doing it.
//set up secondStartHour 6 hours ahead of startHour
if (startHour <= 5)
{
    secondStartHour = startHour - 18;
}
else
{
    secondStartHour = startHour + 6;
}

//set up thirdStartHour 12 hours ahead of startHour
if (startHour <= 11)
{
    thirdStartHour = startHour - 12;
}
else
{
    thirdStartHour = startHour + 12;
}

//set up fourthStartHour 18 hours ahead of startHour
if (startHour <= 17)
{
    fourthStartHour = startHour - 6;
}
else
{
    fourthStartHour = startHour + 18;
}

I had to write the code in the way I did above because I am working with a 24 hour clock so in some cases adding time to a startHour will actually reduce the value. By this I mean if startHour is 23 (23:00) and I need to add 6 hours to it to get secondStartHour the result will be 5 (05:00) so I can't simply write code to say secondStartHour = startHour + 6. The code just seems too long winded and messy but I cant think of a better way to write it. I could use a switch case statement but then I would have 24 cases with assignments for each of the new variables in each case so that seems worse, any ideas would be appreciated.

If you think about it - if it happens 4 times during the day at regular intervals, you actually can only have 6 start times...

Hi Majenko, thank you for the reply but this is not the case as the user selects the time period at which they want the first process to occur

But that's the opposite of what you say in your question: "I have been asked to start the same process at 6 hour intervals so that it occurs 4 times during the day."

Yes it is every 6 hours but it is based on the fact that  "The user sets the start hour and can only select values from 00-23" So it is every 6 hours but changes based on the selected time

Yes, but what is the difference between them entering 4 and entering 10?

Instead of comparing, you can use the modulo operator:
 secondStartHour = (startHour +  6) % 24;

And similar for the others:
 thirdStartHour  = (startHour + 12) % 24;
 fourthStartHour = (startHour + 18) % 24;

While xxxStartHour >= 24, 24 will be removed until it is within range [0, 24).
If you need an offset, you also can add some hours of course after the module (I don't fully understand your example which can have values >= 24.
Also, if you need to do the same task every 6 hours, you can use with one time and 'restart' it every 6 hours (and maybe taking summer/winter time into account).

thank you so much Michel, the mod operator is exactly what I am after, it will make the code much shorted and cleaner. Thanks again

You are welcome. You can use it in many cases which involves something periodical.

If you think about it logically you actually only have 6 start hours. Things can only start at a time between 0 and 5 am inclusive.  Everything else is a multiple of 6 hours on from that start.  Any time provided that's past 5am is actually a future time of an earlier start time.
So you can just "modulus" the given time so it is one of the first 6 hours of the day:
startHour = startHour % 6;

And then add 6 each time for the other hours:
secondStartHour = startHour + 6;
thirdStartHour = startHour + 12;
fourthStartHour = startHour + 18;

So your hour arrangements can only be:
0  6  12  18
1  7  13  19
2  8  14  20
3  9  15  21
4 10  16  22
5 11  17  23

If you provide the hour 15 as a start time, 15 % 6 is 3 (divide 15 by 6, you get 2 with 3 remaining), so you are in the time pattern "3 9 15 21".


text:
Emulating a generic Mifare USB peripheral device with RFID-RC522
Hardware
Dev Board: Arduino Nano V3.0

Module: RFID-RC522 13.56 MHz

Cable: USB A - USB Mini B

Configuration
Physical

Code
/*
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read data from a PICC to serial.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 *
 * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
 * Reader on the Arduino SPI interface.
 *
 * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
 * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
 * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
 * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
 * when removing the PICC from reading distance too early.
 *
 * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
 * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
 * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
 * keep the PICCs at reading distance until complete.
 *
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9               // Configurable, see typical pin layout above
#define SS_PIN          10              // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);       // Create MFRC522 instance

void setup() {
    Serial.begin(9600);                 // Initialize serial communications with the PC
    while (!Serial);                    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();                        // Init SPI bus
    mfrc522.PCD_Init();                 // Init MFRC522
    mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
    Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    // Dump debug info about the card; PICC_HaltA() is automatically called
    mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

See: https://github.com/miguelbalboa/rfid/tree/master/examples

Goal
Generic USB-Compatible Mifare NFC Read/Writer
So, you can get these devices that just plug directly into your regular computer via USB, and basically function as an ordinary HID or peripheral device. I have various different ones from when I was investigating the security implications associated with CRYPTO-1 & MiFare Classic access control cards. They all basically work the same, and produce/dump the same standard output.
The thing is, I have little experience with Arduino, and hardware development in general. The Arduino USB Port is obviously used for serial communication with the IDE for programming the MEGA328P, and I can use the IDE's serial interface, plotter, etc. But it doesn't seem to want to play with any of the other applications (MiFare Classic Universal tooKit, etc.) that "just work" with the (unaffiliated) commercial/store-bought devices.

I would guess, that the commercial products expose a different interface to the USB host (the PC). On the Uno/Nano there is an extra chip, that exposes a virtual serial interface over USB. On the Uno it is possible to reprogram that chip, to on the USB interface, what you tell him (On Nano it might be impossible to connect to the correct pins because of the size. Haven't done this ever). Or you use an Arduino/Chip, which already has native USB support, like the Leonardo. Though I don't know, if you really would be able to imitate the Mifare interface

You have to use Arduino Mini and Keyboard.h library which comes with arduino IDE. Arduino Nano does not have HID capable processor.
Try this with mini:
#include <Keyboard.h>

void setup() {
 // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
 // connected to ground:
 pinMode(2, INPUT_PULLUP);
 Keyboard.begin();
}

void loop() {
 //if the button is pressed send the message
   if (digitalRead(2) == LOW) {

     Keyboard.print("Hello!");

   }
}

I will build same thing now, just tested Arduino Mini and will add rc522 to it.

did you try it? how'd it go?


text:
How to use map function
if(pin10==HIGH)
  val=analog.read (potpin);
  val=map(val,0,1023,0,180);
  servowrite(val);
else
  val=map(0,1023,0,90);
    servo.write(val);}

That looks vaguely sensible. You'll need to find a way to write the complete code clearly in the question to get useful help I think.

The question doesn't really make sense. Best post what you have and we can try to see the problem.

https://www.tutorialspoint.com/cplusplus/cpp_if_else_statement.htm

It looks like you're using pin 10 to indicate whether sweep your servo through 180-degrees or through 90-degrees. Is that correct? Then you only need the if/else statements to select one of the two 'map()' calls. I see several problems:

Your indentation suggests you tried to select 3 statements with your 'if', but an 'if' only refers to one following statement or block of statements. If you want it to control a block of statements, you need to surround those statements with braces: '{' and '}'.
In this case, you need everything but the 'map' calls to be outside the 'if' statements.
Statements (except 'if' and 'else' by themselves) need to end with a semi-colon.

I think you meant to write:
val=analog.read (potpin);     // read the pot

if(pin10==HIGH)               // pin 10 selects servo range
  val=map(val,0,1023,0,180);  // map the pot value ...
else                          //   into one of
  val=map(0,1023,0,90);       //   the servo ranges

servowrite(val);              // drive the servo

Update:

I had try every thing , but there is some shaking and vibration when
  if condition is satisfied.

Was the shaking near rotation limits? Most servos, especially the inexpensive hobby ones, get unstable near each end of their travel. Some will move smoothly to the limit, others get shaky within a few degrees of the limit. Each one is a little bit different.
Update 2:
Here is a complete, working example based on the Arduino Servo-example and your specifications. There were two bugs above:

I left out the 'val' argument in one of the map commands. This cause a compile error and should have prevented you from testing it. It could not have run, properly or improperly.
In your code example, if(pin10==HIGH) doesn't read any input pin! It just reads some (unseen!) variable named 'pin10' - unless you did read the pin in some code you didn't show us? Which is why we ask for a minimum, complete, & verifiable example.

This code runs and rotates my sg90 servo through 90 degrees, if pin 10 is low, or 180 degrees, if pin 10 is high.

You need a (val,... in the second map function:  https://www.arduino.cc/reference/en/language/functions/math/map/  Also, maybe a val = map(val,0,1023,0,90+90*pin10) would be sufficient.

"These code r not working" - Please be specific: What were you expecting? What happened instead? What code did you use this time? Edit this into the question. "I use sg90 was there any prblm with this" - Nothing wrong with it. sg90 is an inexpensive, light-duty servo so just know that most of them will 'jitter' or shake near either end of their travel. If you keep them between 10 and 170 degrees, you should have no trouble. Or if you need the most range you can get, test each one to find its useful limits,


text:
Arduino Uno vs Arduino MKR1000 analogRead discrepancies
I'm using an Arduino to control a BLDC motor connected with the motor driver. It is just a simple control which I'm using a PWM as a signal. Before this, I'm used Arduino Uno pin 5 to control BLDC motor, the analogue value starts from 80. Now, I'm changed to Arduino MKR1000 board with the same pin 5 to control BLDC motor. But, for MKR1000 to rotate the motor, analogue value start from 125. My question is, why two of this board using a different PWM value for rotating the BLDC motor.

The Adruino Uno is running off 5V, while the MKR1000 is 3.3V.  This means you need a bit more on-time to get the same power output.