text:
How to reset arduino Mega 2560 code automatically?
I am working on the temperature project using arduino to collect temperature. But sometimes arduino hang there so I have to unplug cord and plug it back in to restart the arduino. I do not when it is going to hang up again. So I decide to do some research on the internet but no luck for that. Here is the article I read about resetting arduino code with watchdog timer library.(unfortunately, it only work for arduino uno) If someone has any idea how to reset arduino mega 2560 code. Please help !!

You can still use the watchdog without the library.

@IgnacioVazquez-Abrams  Do I need to wire anything to my arduino or other like what they called bootloader (I do not know what is that) ? The watchdog is a library, right ?  how to define it without the library ? I am guessing it is going to give me an error.

The watchdog is a MCU peripheral. You enable it by setting the registers appropriately. See the ATmega2560 datasheet, "System Control and Reset" section, "Watchdog Timer" and "Register Description" subsections.

avr-libc already has the appropriate functions created for you. Just include <avr/wdt.h>.
Sample usage
#include <avr/wdt.h>

void setup()
{
   wdt_enable(WDTO_8S);
   ...
}

void loop()
{
   wdt_reset();// make sure this gets called at least once every 8 seconds!
   ...
}

how to know the aruduino is resetting. I have it run for 10 mins. no sign see the display is resetting .

You can detect resets using the MCUSR register. But it's probably easier to add a Serial.print('startup') to the setup function and keep the serial console open. If 'startup' appears more than once a reset has occurred. Alternatively add a buzzer that beeps on startup(/reset).

I add Serial.print('startup')  at the setup. It did not reset the program .

@Yang: It won't reset unless the code fails to reset the watchdog.

I tried Gerben's suggestion with a display:
#include <avr/wdt.h>

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println (F("Code starting ..."));
  wdt_enable(WDTO_8S);
  }  // end of setup

void loop()
{
//   wdt_reset();// make sure this gets called at least once every 8 seconds!
}

That does indeed print "Code starting ..." every 8 seconds or so.

But sometimes arduino hang there so I have to unplug cord and plug it back in to restart the arduino.

You are better off working out why. There is probably a bug. Fix the bug rather than just restarting the Arduino.

let me tried to run the code for several weeks to see if there temperature go off. By the way, i think the code has no problem but maybe somehow the temperature hit "0" or even crazier "99999", I still cannot figure that out is the hardware problem or something else. So that is why I tried to reset my code automatically.

You could also use an external circuit to reset the arduino when 'heartbeat' pulses are missed. You can even detect when a reset has occured and report accordingly. See here for an example

What is the advantage of this circuit over the build-in watchdog timer?

You can know when it's happened and record the event which is difficult if not impossible to do using the internal watchdog

You can check the MCUSR register (The MCU Status Register provides information on which reset source caused an MCU reset.).

Yes (and I'm admittedly getting out of my depth here) doesn't the boot loader also use the internal watchdog so you wouldn't know if it was caused by the reset switch/power on or a watchdog event


text:
Save Leading Zero HEX into String RFID RC522 Arduino
I'm using RC522 to read RFID card. All is until if the HEX leading by 0 then i can't save it into String. But if i print it to Serial all is well. Here is my code:
#include <SPI.h>
#include <MFRC522.h>
#include <stdlib.h>

#define RST_PIN         9
#define SS_PIN          10

String inStringHex = "";

MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
}

void loop() {
  // Look for new cards
  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial())
  {
    //Serial.print("Card UID:");
    for (byte i = 0; i < 4; i++) {
      Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? "0" : "");
      Serial.print(mfrc522.uid.uidByte[i], HEX);
      inStringHex += String(mfrc522.uid.uidByte[i], HEX);
    }

    Serial.println();
    Serial.println(F("Hex normal"));
    Serial.print(inStringHex);
    Serial.println();
    Serial.println();

    inStringHex = "";
    delay(5000);
  }
}

Here is what displayed in serial monitor:

What i want is the String under "Hex normal" would be "04292e5a" not "4292e5a"
Please anyone help me.
Thank You.

String(mfrc522.uid.uidByte[i], HEX) means you want to convert number into hexadecimal string repesentation, if you pass 4 as input parameter, it will convert it into "4", not "04". You need to apply similar approach as you have used when printing the value through UART. For example:
if (String(mfrc522.uid.uidByte[i] < 0x10)
  inStringHex += " ";
inStringHex += String(mfrc522.uid.uidByte[i], HEX);

Personally, I would recommend switching from Strings into static buffers (because arduino has too small memory to use dynamic allocation and there could be issue with running out of memory due to memory fragmentation):
char id[16];
sprintf(id, "%02x%02x%02x%02x", mfrc522.uid.uidByte[0], mfrc522.uid.uidByte[1], mfrc522.uid.uidByte[2], mfrc522.uid.uidByte[3]);

Hi, i need to save into string because i will it convert it again to decimal. If i use your recommendation, can i still convert it to decimal?

Yes of course, you will get the same string and for conversion you can use strtol with radix 16. But if you only want to convert four bytes into one long int, there is much simpler way

I will try your suggestion. Thank you sir.

unsigned long result = 0; result |= (long)mfrc522.uid.uidByte[0] << 24;  result |= (long)mfrc522.uid.uidByte[1] << 16; result |= (long)mfrc522.uid.uidByte[2] << 8; result |= (long)mfrc522.uid.uidByte[3];

Is d[0] taken from char id[16]?

I edited the code to match your situation

Thank you sir. your recommendation worked as what i want.

you can try ;
for (byte i=0; i < uidLength; i++)
{
  Serial.print(uid[i] < 0x10 ? " 0" : "");
  Serial.print(uid[i], HEX);
  if (uid[i] < 0x10) inStringHex += "0";
      inStringHex += String(uid[i], HEX);
} Serial.println(); Serial.println(inStringHex);

source: Stack Exchange

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

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

sort: votes


text:
delete the memory or re-upload a program
At the moment I am following the instructions of this project https://github.com/JoernL/LimiTTer. Besides the peripheral parts like a Bluetooth module and an NFC module, the central unit is an Arduino Pro Mini.
I am a bloody novice with Arduino and just taught myself how to solder stuff. So far, I successfully uploaded the program from the project above to the Arduino Mini Pro and will continue as soon as the other parts arrive.
Anyhow, since I am strictly following the instructions I have some serious knowledge gaps and hope you can help me out. So, for instance.

How do I know, how much storage capacity is available on the Arduino board before and after I uploaded something?
How can I delete a program from the Arduino board?
When I upload a program, will the program that is already on the Arduino been overwritten?
Is an Arduino generally used to execute one specific program and not to hold a set of totally different programs?

The arduino work like the way you think it does regarding-when a new program is uploaded - it replaces or deletes the previous one when uploaded. This is because the arduino is a general stored program computer -though it doesnt hold a set of programs in memory just the last one that was uploaded last. You may need to clear the EEPROM with code though.

How do I know, how much storage capacity is available on the Arduino board before and after I uploaded something?

In yellow is how much bytes does your program take.
In purple is how much bytes are available on your board.
In green is how many bytes does your global variables take.
In orange is how many bytes are left for local variables.
In blue is how many bytes are available for all of your variables.
In red is the general specs of your board and to which COM port it is connected to.

How can I delete a program from the Arduino board?

Once  a new program is uploaded, the old one is deleted (somewhat). Still, you get all your bytes back and it is like if you start from scratch

When I upload a program, will the program that is already on the Arduino been overwritten?

Yes.

Is an Arduino generally used to execute one specific program and not to hold a set of totally different programs?

An Arduino can only execute 1 program at the time. It doesn't usualy hold on to any other programs, but can store 1024 bytes in it's EEPROM. This lets your write in the EEPROM with a program and access that data with an other.

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


text:
Use Mac for memory & processing
I understand that each model of Arduino has limited cpu, ram, etc.
However, I have this very powerful Mac that it’s hooked up to.
Am i able to use my Mac for expensive computation and just pass results to my arduino in real-time?
Basically arduino takes in sensor data - passes it to Mac. Mac computes and returns an output to arduino.

Sure, if you want to write software for the Mac to do stuff, yes.

Majenko - good to know it’s possible. Can you provide more details? (Eg an example, documentation, etc)

You basically send information over the serial connection. There's millions of examples around. What you send and how you send it depends on what it is you are wanting to do.

Got it - can you link me to an example / suggest something to google? Arduino to Mac have unrelated sites

You need to know two things: 1. how to deal with serial on the Arduino, and 2. how to program the Mac to work with serial. Neither is related to the other. Serial on the Arduino is the same for Windows, Mac, Android, Linux, BeOS, Unicos, QNX.... whatever.

This blog describes the author's open-source, cross-platform library in C to talk to an Arduino via serial. The library is available on GitHub. A C project on your Mac can use it to communicate with your Arduino. You'll probably want to create a simple command protocol to keep the two in sync, as serial is pretty "barefoot" by itself, being just a stream of bytes with no markers, packets, or check-sums unless you impose such structures on your data, yourself. It probably doesn't need to be very complex, depending what your application needs.
I have found similar projects in Python and in Java for the Mac/Windows/Linux/<whatever> side; there's plenty of work already done for you.


text:
What happens if you supply too much voltage to an LED?
Say I have an LED that requires 3.5v. What happens if I power it with more voltage?
For example, my Arduino Uno has a 5v pin. If I power the 3.5v LED from the 5v pin, what will happen?

It depends on if there is a resistor in the circuit, and what the impedance of your voltage source is.

I decided to make a video of this: https://youtu.be/Auuisr9sL-8

In the most simple terms: it will kill the LED.  However things are really not that simple.
First off, an LED is a current driven device, not a voltage driven device. That is, it doesn't really care what the voltage is, but it does care what the current is.  Of course, too much voltage will kill it - but too much current, regardless of the voltage, will kill it.
It's important to understand that an LED is what is known as a non-linear component.  Things like resistors are called linear because they have a linear relationship between voltage and current. Increase the voltage, and the current increases by the same proportion. Increase the resistance and the current decreases by the same proportion.
However an LED is not like that. A typical Voltage-vs-Current graph for an LED looks like this:

Once the voltage reaches the "forward voltage" of the LED the current flowing through it rapidly increases. As you can see it very quickly gets towards infinity. Above a certain point and an increase in voltage has no real difference in the current. In that example the difference between 3V and 5V would be both infinite and zero. In other words, it's pretty meaningless.
But we're still over-simplifying, and that's because we've assumed an ideal power supply. That is, one that can supply a fixed voltage, but infinite current. In other words, a power supply with zero impedance.
No such thing exists, though.
Every fixed-voltage power supply can be seen as an ideal voltage source with an in-line (series) resistor. That resistor limits the amount of current that the supply can provide before the voltage drops too low.  In schematic terms, it looks like this:

simulate this circuit – Schematic created using CircuitLab
If the voltage of the source is above the forward voltage of the LED it will try and draw an infinite amount of current from the source.  That current will lead to a voltage drop across the resistance RZ, which results in the output voltage of the source being reduced.
It will reduce to be the same as the forward voltage of the LED.
We can, of course, calculate the current that would come out of the supply if we know the impedance of the source, but that's not something that is often known.  So you assume it's low and take precautions.
For example, if we happen to know the impedance of the source is 1Ω (maybe it's stated in the datasheet for the power source...) and the voltage is 5V, and we have an LED that has a forward voltage of 2V (I like nice round numbers), we can work out that:

The voltage drop caused by the impedance is 3V (5-2)
The current that causes that drop is 3A (I=V/R, 3/1=3A)

3A is way off the scale for an LED, and it will basically melt internally.
So we add an extra resistance to drop more of the voltage at a lower current.
Now if we take the example of powering an LED directly from an Arduino's GPIO pin without a resistor, we can do the same kind of calculations.
We know that we mustn't draw more than 40mA from a pin (absolute maximum), so if we take that as the current that can come out of a pin before it drops below an acceptable level we can work out an estimate of the impedance. Since the datasheet tells us the output level it shouldn't drop below is 4.2V when powered by 5V, we know that the maximum voltage drop at the maximum current would be 0.8V (5-4.2).  So:

R=V/I = 0.8/0.04 = 20Ω.

There. That's an approximation of the output impedance of a GPIO pin on an Arduino.  So we can plug that into our formulae and connect an LED, and we get:

The voltage drop caused by the impedance is 3V (5-2)
The current that causes that drop is 150mA (I=V/R, 3/20=0.15)

150mA is not massive. It's more than an LED typically wants (20-30mA tops), so the LED won't be happy, but it won't instantly blow at that level. It will be brighter than normal, get hotter than normal, and its lifetime will be much much shorter than normal.
That's not the worrying thing though.  The worst thing is the power dissipation from the impedance:

P=I²R = 0.15²×20 = 0.45W.

That's almost half a watt of heat being generated by the GPIO pin's drivers. If you consider that a half-watt resistor is pretty chunky, if you can picture that power being crammed into the tiny space of a single MOSFET within a silicon chip, you can see how that may become a problem.
It's really not capable of dealing with that level of heat, and the GPIO pin's driver MOSFET goes belly up.  Bye bye MOSFET, bye bye GPIO pin.
As an aside, you would probably also see other strange things happening as the chip tries in vain to deliver large currents to a single GPIO pin. Other areas of the chip get starved of power, power rails drop in voltage, code crashes, etc. All from just one little LED being connected without a resistor.

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


text:
Infrared frequency recorded with saleae
i'm trying to decode infrared signal recorded with the saleae. It makes me wonder why saleae shows so low values for the frequencies from 0.1kHz to 0.8kHz. I found that standard for the IR is around 38kHZ. Is there something wrong with my record? Or did i misread the sample?

If you are using an IR receiver with 3 pins that is designed for a carrier frequency of 38kHz, then your will receive the logic signal only. If you use a photo transistor with 2 pins, then you should be able to see the carrier frequency along with a lot of noise.

What you are looking now is NOT the IR frequency, but the de-modulated signal.
Here is what I'm talking about:

(image taken from http://www.electronicwings.com/sensors-modules/ir-communication)
As you can see, the various pulses are made of smaller pulses.
In your case you are seeing what is here called "Serial data", which is different from the carrier frequency. What the saleae board is telling you is that the width of the high part is 1.625ms, while the width of the low part is 0.631 ms; as you can see, the waveform is NOT periodic, so the "frequency" is meaningless (it's the reverse of the time marked on the view, which is the sum of one large high value and one low value).
Your plot resembles the NEC protocol (see for instance here). A logic '0' is a 562.5µs pulse followed by a 562.5µs space, while the logic '1' is a 562.5µs pulse burst followed by a 1.6875ms space (this is similar to by 0.631 ms and 1.625 ms measurement)


text:
Arduino Standalone construction
In tutorial - https://www.arduino.cc/en/Main/Standalone , they have used voltage regulator. Can we able to do without Voltage regulator ?(to compact the circuit), If so what should the voltage & current value in Atmega328?

That's actually quite an involved question to answer. The short answer is "Yes, you can do without the regulator as long as you get the voltage right".
And that is where it gets tricky.
The datasheet states:

Operating Voltage:

1.8 - 5.5V

So you can power it from two or three AA batteries, for instance (3V - 4.5V). However, that is not the whole story.
The voltage you provide it with dictates what frequency the chip can reliably run at. Later in the datasheet is this nice little graph:

Since the normal Uno-like arrangement runs at 16MHz you're looking at a minimum voltage of around 3.8V - 4V (it's actually quite hard to work out from that graph).
But if you are willing to reduce your clock speed to 8MHz (which is what the 3.3V Arduino "Pro" boards run at) then you can drop right down to about 2.5V.
At a 2.5V lower limit with 3 AA batteries it would equate to a minimum voltage of 0.83V per cell, which is below the normal minimum accepted "flat" voltage of 0.9V per cell.
So powering from 3 AA batteries with a clock speed of no more than 8MHz would give you probably the best run-time.  Note, also, that a decrease in clock frequency decreases the current consumption as well - the slower you run the chip the less current it needs. You can see that in this graph in the datasheet:

And yes, as you can see, the lower the supply voltage the lower the current as well. So as the batteries run down and the voltage drops so does the current, reducing the speed at which the batteries will run down.
As you can see, if you don't mind the supply voltage changing (which of course will affect everything else in the circuit, so you need to check those out first), running directly from batteries without a regulator can actually have advantages. But as I say, you need to check what else you are running in the circuit to make sure it doesn't mind if the power supply voltage drifts.
And don't forget, also, that the supply voltage affects the ADC readings, since they are referenced to that voltage as well.

so yu are recommending not to use ? @Majenko

voltage is b/w 1.8 to 5.5v, what about current?

My understanding is that the frequency-voltage graph is made of two linear parts, below and above 10 MHz. Then, working out the required voltage from the operating frequency is easy: 2.4 V @ 8 MHz and 3.78 V @ 16 MHz.

@EdgarBonet No, it's just one (roughly) linear guide (not precise numbers, just a guide). The 10MHz is just shown as an example.

@sankar As I say - it can be good to not use a regulator, but check the rest of your components to make sure they are happy.  The current depends on the voltage and the frequency as I showed with the second graph. It also depends on the rest of the components in your circuit. There is no answer "It is X milliamps".

so can i give 5v-1Amp ? 'm connecting a ADXL335 sensor & one serial device

No, it's not just a rough guide, these are actual specs. Quoting the datasheet: “the Maximum Frequency vs. Vcc curve is linear between 1.8V < Vcc < 2.7V and between 2.7V < Vcc < 4.5V.”

If the 5V supply is regulated internally (say a USB power adaptor) then that would be perfect and a regulator is not needed (the power supply already has one). It would be exactly the same as running with a 9v battery and a regulator.

@EdgarBonet Oh right, must have missed that bit.


text:
SIM808 module restarting repeatedly
I have bought SIM808 module, everything working fine. All AT commands are giving expected response, i'm accessing it through hyperterminal. My problem is that whenever i make or receive a call or SMS , GSM gets restarting.(I can able to make/receive call, getting ring/alert for small period of time and then interrupt). But there is no Under or Lower voltage power down or warning.
I have tried with DC power supply of 5V/500mA , 5V/1A and 5V/2A.  What might be the reason ? Please help.
extra info : It has one LM2576S voltage regulator in-built.

Check the datasheet and I think you will find you need 3 amps peak.  It requires this peak current when you make a call or send a text/sms.
Use a 5A power supply and that should solve the problem.
I have never tried it but "super capacitors" might work, providing the extra power when its needed, it depends how long you need the 3A for.

Thanks Matt for reply. I dnt have datasheet for that module. Bt according to SIM808 datasheet, it's peak current is 2A and voltage is 3.4 to 4.4. so i dnt know for module, how much input should be given

does the module withstand with 5A current ? @Matt

I got the solution for my problem. With 12V-1.5A power supply, it works fine.

I too faced the same problem and solved it.
Just use a 3.3V logic converter or a 3.3V interface, as the 5V causes the device to restart.


text:
Do we really need to upload Arduino bootloader for new Atmega IC
I am using Atmega328p in my circuit. I will be programming this IC using Arduino. But because this is a PCB, so I will programming using USBasp programmer. So before uploading code as upload using programmer, I will select my arduino board in board select menu and then I will select USBasp as my programmer. But I want to know that is it really necessary to burn bootloader on a new Atmega328p IC. On some page, they say you do not require it. But some say, its necessary because you will be using Arduino functions like Serial.Begin() etc.
So I want to know what does this bootloader contains. Do I really need it. Can I directly upload my code using programmer. Can anyone please explain this to me.?

The bootloader is used to allow flash "self-programming" by the MCU, though USB. If you program the MCU through ISP, you don't need it. If you want to recover bootloader bytes though, you'll have to change some fuses (can't remember which ones, it also depends on the MCU, but you can google for it).

In fact, the bootloader is used to program a board through serial, not USB. So you may want to flash a bootloader on the 328p with an USBasp, then you just need to use the serial interface to download new sketches. On the other hand, you can gain a bit more space and faster boot times without a bootloader

You don't need to, but it has the side effect of setting the fuses. You you could just run it once. Then when you program your sketch, it will overwrite the bootloader, but keep the fuses. You could also manually set the fuses, which is preferable but a bit more complicated.

IIRC, at least the BOOTRST fuse should be programmed differently depending on whether you are using a bootloader or not.

No, you do not need the bootloader for your chip to function.  The bootloader is merely a convenience.
If you are programming through USBasp you don't even need it on a "normal" Arduino board.
All it does is allow you to program through the UART interface (or USB interface in the case of ATMega32U4 boards). If you don't want to do that then you don't need the bootloader.
If you do not provide a UART interface to the user that can be connected to then the bootloader would be pointless anyway since you cannot communicate with it.


text:
Iterating an array of relays
Bear with me as I'm fairly adept at C# but I am having a problem understanding how to get an array iterated.
I am writing a program to test relay boards, it will eventually have an input mechanism to select the number of relays on the board. For now, i just need to get an array iterated to move on with the code.
The biggest relay board I've seen has 16 relays, so....
#define Relay1  2  // Arduino Digital I/O pin numbers for UNO R3
#define Relay2  3
#define Relay3  4
#define Relay4  5
#define Relay5  7
#define Relay6  8
#define Relay7  9
#define Relay8  10
#define Relay9  11
#define Relay10  12
#define Relay11  13
#define Relay12  A0
#define Relay13  A1
#define Relay14  A2
#define Relay15  A3
#define Relay16  A4

int relays[]{ Relay1,Relay2,Relay3,Relay4,
    Relay5,Relay6,Relay7,Relay8 };
int maxRelayCount = 8;
char rx_byte = 0;

void setup()   //Initializes all variables and settings
{
  Serial.begin(9600);
 // create an input for the amount of relays on the board
//hardcoded for now

//Set pins to OFF & declare pins as OUTPUTS
 for(int i = 0; i < maxRelayCount; i++)
 {
   digitalWrite(relays[i], RELAY_OFF);
   pinMode(relays[i], OUTPUT);
   //How to convert i to a string in c++?
   //Serial.print("Relay " +[i] + " set HIGH and as OUTPUTS");
 }

 //Check that all relays are inactive at Reset
 delay(4000);

}

So there are two issues. If I remove the loop and just hard code 8 times to set HIGH and OUTPUT it works fine, but the loop does not and won't upload to the Arduino, thus the reason I believe it is wrong. Secondary question is how to convert the counter i to a string to concatenate the message

Why not break the print statement into three parts; Serial.print("Relay["); Serial.print(i); Serial.print("] set HIGH and OUTPUT");

As noted earlier, RELAY_OFF needs a defined value.
Note, rather than using clumsy list of #define statements to define a bunch of integer constants, you can use C's enum declaration to define them, as shown in the following sketch, which produces the output
Relay 1 should be OFF
Relay 2 should be OFF
Relay 3 should be OFF
Relay 4 should be OFF
Relay 5 should be OFF
Relay 6 should be OFF
Relay 7 should be OFF
Relay 8 should be OFF

when it is run.
#include <Streaming.h>

// Arduino Digital I/O pin numbers for UNO R3
enum { Relay1=2, Relay2=3, Relay3=4, Relay4=5, Relay5=7, Relay6=8,
       Relay7=9,   Relay8=10,  Relay9=11,  Relay10=12,  Relay11=13,
       Relay12=A0, Relay13=A1, Relay14=A2, Relay15=A3,  Relay16=A4};

int relays[] = {Relay1,Relay2,Relay3,Relay4,Relay5,Relay6,Relay7,Relay8};
// Number of relays in the array
enum { maxRelayCount = sizeof relays / sizeof relays[0] };
enum { RELAY_OFF = HIGH };  // Set LOW or HIGH as appropriate
char rx_byte = 0;

void setup() {          // Initialize variables and settings
  Serial.begin(9600);
  //Set pins to OFF & declare pins as OUTPUTS
  for(int i = 0; i < maxRelayCount; ++i) {
    digitalWrite(relays[i], RELAY_OFF);
    pinMode(relays[i], OUTPUT);
    // Serial.print("Relay " +[i] + " set HIGH and as OUTPUTS");
    Serial << "Relay " << i+1 << " should be OFF" << endl;
  }

 // Check that all relays are inactive at Reset
 delay(4000);
}

void loop() {}

Note, the Streaming.h library adds some “syntactic sugar” to Arduino C. At compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  You can install it by unzipping Streaming5.zip from arduiniana.org in your sketchbook/libraries directory.

I didn't put the RELAY_ON and RELAY_OFF defines in the question, but I like the usage of enum and the streaming library

the loop does not and won't upload to the Arduino

Most likely because RELAY_OFF has never been defined anywhere. Change that to HIGH (if that is what your relays need to turn off), or define it somewhere.
Also there is no loop() function - is that just you being economical with the paste?

Secondary question is how to convert the counter i to a string to concatenate the message.

Simple: don't.  There's no need.
Serial.print("Relay ");
Serial.print(i);
Serial.println(" set HIGH and as OUTPUT");


text:
Proper error logging using Arduino
Coming from a C# background where I do logs for every application, and given that I will be using the Mega for most projects and therefore have the memory available to do so, I want to incorporate error logging in my projects.
What is the best way to do so? Writing to an SD card? Writing via Wi-Fi or Ethernet to a networked storage or PC? Writing to a USB thumb drive?
The current project I am working on uses the Adafruit Music Maker shield so has the SD card reader incorporated into it, so the easy choice there would be to use that but I like creating solutions that are portable to multiple projects so writing via Wi-Fi or Ethernet seems to be the preferred method?
Since I am not fully up to speed with C++, and I see there are various ways to write to text files in C++, are there any preferred ways to do so depending on which storage route I take?

What you ask is difficult to answer in generic way, because not all the Arduino boards have the same HW options and even if you were to require a certain interface (ex: WiFi), that will introduce other side effects:

it will use certain pins/buses (SPI) that one might want to reserve for other purposes (yes you can have multiple peripherals on the SPI bus, but it will require additional code)
it might significantly alter the execution timing in certain cases

What most people use - and seem to be happy with - is the serial port:

it is not too difficult to setup
the ide already has a serial port monitor
it can produce information that is immediately human-parsable
there is no need to retrieve it afterwards (an SD card has to be extracted, mounted, etc.)

I would advise you to consider this at least as option, if not the only option.
Of course each option has drawbacks: the serial port can also cause delays in the execution, might not be too good if you have lots of stuff to log, etc.
The serial port could be seen as a intermediate step toward wireless logging: modules like the esp8266 do rely on serial communication.
Which means you could have wired logging while in the early phase and wireless logging later on, assuming you can afford to have something constantly listening to your project.
I would consider the SD card only for cases where the device will run unattended for long periods of time and there might be some hard to reproduce event that you want to track.
You could also consider the onboard flash, if you have to log events that happen seldom.

I should've been a little clearer. In general I log errors to an array and infrequently write them to the log file , which is more appropriate here so as not to tie up execution with a lot of Serial... statements

In C it's typical to use a log() macro which is configured to do whatever is needed, when logging is enabled. When logging is disabled, the macro is empty.

Normally, because Arduino is meant to be easy to understand and use, C++ is only used (extensively) in the libraries.  Perhaps someone knows more about the Mega, but, in general, the Arduino platform does not contain many complex built in features.  For instance, before even thinking about how best to write to an SDCard, you need to do some research into how to load and use the Arduino SDCard library.
This appears to be what you eventually want to do.

already fully versed on how to write to an sd card, or to network for that matter. the question was about best practices

Embedded systems typically use UART for logging, and Arduino is no exception. Logging to UART is as easy as calling Serial.begin() in the setup() and Serial.println() in the loop(), it works on all Arduinos, doesn't require any additional hardware and consumes much less resources than the SD card or networking library. Of course, you're limited in bandwidth (115200 kbit/s, sometimes more), so you won't be able to log in the fast-running cycles.
If you don't like the Serial Monitor feature of Arduino IDE, you can install one of the many terminal programs which will happily write the data from serial port to a log file. Some of these tools also have nice analysis features, including plotting of logged signals, formatting, data conversions etc.
If you're good with command line, creating a log file is as simple as
cat /dev/ttyUSB0 > log.txt

in Linux or
type COM1 > log.txt

in Windows.

In my Arduino project, I wrote communication sub protocol between a Raspberry Pi (or a PC).
I simply added some commands to duo vars or arrays into memory.


text:
Digital input signal to be converted to analog signal
Hello and a very good day.
I am currently doing my final year project which involving Arduino KY-031 Knock Sensor as my input signal and it is apparently a digital type of sensor. So, my question is can the digital signal be converted to analog signal ?
The reason I need it to be analog signal because I wanted it to be classified into 3 type of stages (low,medium,high).
p/s: I am using Arduino Uno as my controller.

Yes, there is a Digital-to-analog converter. it is apparently a digital type of sensor - what is this sensor? Please read How do I ask a good question?.

The Arduino is a digital device. You are getting a digital input. How will it help to convert it to analog?

@NickGammon It's a KY-031 as per the question :-)

Oh yes, sorry. If you want loudness then you need a different sensor, like a small microphone where you could detect the level of output from it.

You can create an analogue representation of any signal - but you can't add in information which wasn't previously there.  The KY-031 doesn't give you any more information than "knock" or "no knock", so there's no way to get further detail out of it.


text:
GPS not display
so im currently trying to do a a project whereby if my sensor is active, it will display my location. but, it seems that when the sensor is active, it only display location of lat: 0.00 , long: 0.00 on my LCD display.
help me to solve this problem.
#include <LiquidCrystal.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(9,10);
char msg;

int knockPin = 7;                   // Use Pin 7 as our Input
int knockVal = HIGH;                // This is where we record our shock measurement
boolean bAlarm = false;
int knockValue = digitalRead(6);
unsigned long lastKnockTime;        // Record the time that we measured a shock
int knockAlarmTime = 500;           // Number of milli seconds to keep the knock alarm high

static const int RXPin = 13, TXPin = 8;
static const int GPSBaud = 9600;
TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup ()
{
  mySerial.begin(19200);   // Setting the baud rate of GSM Module
  delay(20000);
  ss.begin(GPSBaud);
  Serial.begin(115200);
  Serial.println("GSM SIM900A BEGIN");
  pinMode (knockPin, INPUT) ;       // input from the KY-031
  pinMode (6, OUTPUT);
  lcd.begin(16, 2);
  String latitude = String(gps.location.lat(),6);
  String longitude = String(gps.location.lng(),6);
      lcd.clear();
      lcd.setCursor(2,0);
      lcd.print("VeCAS System");
      lcd.setCursor(3,1);
      lcd.print(">>Begin>>");
      delay (5000);

}

void loop ()
{
  knockVal = digitalRead (knockPin) ; // read KY-031 Value

  if (knockVal == LOW)                // If we see a knock
  {

    lastKnockTime = millis();         // record the time of the shock
                                      // The following is so you don't scroll on the output screen
    if (!bAlarm)
    {

      Serial.println("KNOCK, KNOCK");
      bAlarm = true;
      digitalWrite (6, HIGH);
      Serial.println(knockVal);
      delay(100);

      while (ss.available() > 0)
    gps.encode(ss.read());
    if (gps.location.isUpdated())
       lcd.clear();
      lcd.setCursor(4,0);
      lcd.print("KNOCK!");
      lcd.setCursor(3,1);
      lcd.print("Detected");
      delay (5000);

          lcd.clear();
          Serial.print("Latitude= ");
          Serial.print(gps.location.lat(), 6);
          Serial.print(" Longitude= ");
          Serial.println(gps.location.lng(), 6);

          lcd.setCursor(0,0);
          lcd.print("LAT:");
          lcd.setCursor(5,0);
          lcd.print(gps.location.lat());
          lcd.setCursor(0,1);
          lcd.print("LON:");
          lcd.setCursor(5,1);
          lcd.print(gps.location.lng());
          delay(1000);
          lcd.clear();

    }
   }

 else
  {
    if( (millis()-lastKnockTime) > knockAlarmTime  &&  bAlarm)
    {
      Serial.println("no knocks");
      bAlarm = false;
      digitalWrite (6, LOW);
      delay(100);
    }
   }
  }

void gpsTrack()
{
      lcd.clear();
      lcd.setCursor(4,0);
      lcd.print("KNOCK!");
      lcd.setCursor(3,1);
      lcd.print("Detected");
      delay (5000);

          lcd.clear();
          Serial.print("Latitude= ");
          Serial.print(gps.location.lat(), 6);
          Serial.print(" Longitude= ");
          Serial.println(gps.location.lng(), 6);

          lcd.setCursor(0,0);
          lcd.print("LAT:");
          lcd.setCursor(5,0);
          lcd.print(gps.location.lat());
          lcd.setCursor(0,1);
          lcd.print("LON:");
          lcd.setCursor(5,1);
          lcd.print(gps.location.lng());
          delay(1000);
          lcd.clear();
}

If you put the GPS on Serial (pins 0 & 1) and the GSM on AltSoftSerial (pins 8 & 9), it could work.  You will have to disconnect pin 0 to upload new sketches over USB.  I assume that you have an UNO or Nano, because you didn't say which Arduino you are using.
Like Majenko said, this will never work with two SoftwareSerial ports.  SoftwareSerial is very inefficient, because it disables interrupts for long periods of time.  This can interfere with other parts of your sketch or with other libraries.  And it cannot send and receive at the same time.  This answer provides complete details.
You may also want to take a look at my NeoGPS library.  It is smaller, faster, more reliable and more accurate than all other GPS libraries.  Even if you don't use it, you should read the page about choosing a serial port.  There are also many tips on the Troubleshooting page.
NeoGPS, AltSoftSerial and NeoSWSerial are available from the IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.
BTW, you can't use delay like that.  You must constantly read and decode the GPS characters.  The sketch will lose many, many GPS characters, preventing it from ever getting complete GPS information.  You have to do something like this:
#include <LiquidCrystal.h>
#include <NMEAGPS.h>
#include <AltSoftSerial.h>

AltSoftSerial gsmPort; // receive pin 8 to GSM TX, transmit pin 9 to GSM RX

char msg;

int knockPin = 7;                   // Use Pin 7 as our Input
int knockVal = HIGH;                // This is where we record our shock measurement
boolean bAlarm = false;
int knockValue = digitalRead(6);
unsigned long lastKnockTime;        // Record the time that we measured a shock
int knockAlarmTime = 500;           // Number of milli seconds to keep the knock alarm high

static const int GPSBaud = 9600;
NMEAGPS gps;
gps_fix fix;
#define gpsPort Serial // RX pin 0 to GPS TX, TX pin 1 to GPS RX

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup ()
{
  gsmPort.begin(19200);   // Setting the baud rate of GSM Module

  gpsPort.begin(GPSBaud);
  //Serial.begin(115200);  // gpsPort *is* serial
  //  Serial Monitor has to be set at 9600 (lower right
  //    corner of Serial Monitor window)
  Serial.println("GSM SIM900A BEGIN");
  pinMode (knockPin, INPUT) ;       // input from the KY-031
  pinMode (6, OUTPUT);

  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(2,0);
  lcd.print("VeCAS System");
  lcd.setCursor(3,1);
  lcd.print(">>Begin>>");
  delay( 1000 );
}

void loop ()
{
  // Check for GPS characters (always!)
  if (gps.available( gpsPort )) {
    fix = gps.read(); // save the latest GPS fields in one structure
    gpsTrack();       // show the latest GPS fields
  }

  // Check for knocks

  knockVal = digitalRead (knockPin) ; // read KY-031 Value

  if (knockVal == LOW)                // If we see a knock
  {

    lastKnockTime = millis();         // record the time of the shock
                                      // The following is so you don't scroll on the output screen
    if (!bAlarm)
    {

      bAlarm = true;
      digitalWrite (6, HIGH);

      Serial.println("KNOCK, KNOCK");
      Serial.println(knockVal);

      lcd.clear();
      lcd.setCursor(4,0);
      lcd.print("KNOCK!");
      lcd.setCursor(3,1);
      lcd.print("Detected");
    }
  }
  else
  {
    if( (millis()-lastKnockTime) > knockAlarmTime  &&  bAlarm)
    {
      Serial.println("no knocks");
      bAlarm = false;
      digitalWrite (6, LOW);
    }
  }
}

void gpsTrack()
{
  Serial.print("Latitude= ");
  if (fix.valid.location)
    Serial.print( fix.latitude(), 6);
  Serial.print(" Longitude= ");
  if (fix.valid.location)
    Serial.println( fix.longitude(), 6);

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("LAT:");
  lcd.setCursor(5,0);
  if (fix.valid.location)
    lcd.print( fix.latitude() );
  lcd.setCursor(0,1);
  lcd.print("LON:");
  lcd.setCursor(5,1);
  if (fix.valid.location)
    lcd.print( fix.longitude() );
}

Notice that it also checks the location validity flag before using the lat/lon values.  Your GPS may not know the location, perhaps due to bad satellite reception.

Thank you for ur answer. i am using board Uno. so i try to use ur code, but it wont work since it is board Uno.

Oh, yes, you must run your Serial Monitor at 9600, not 115200 (I edited that line above).  Then it will work on an UNO IF you connect the GPS to pins 0 & 1, as described.  It does not send/receive anything to the GSM, so that doesn't matter.  Read the link on "choosing a serial port".

I get this error message. Error compiling for board Arduino/Genuino Uno. why ? huhu

haha sorry i forgot to download the library.

You have two SoftwareSerial ports. You can't reliably use two of them at once. Only one can be set to receive data, and that one is the first one you define. You can switch between them with the listen() function, but it's not recommended.  If you never want to receive on one of them then it's (almost) fine, but when sending on any of them nothing can be received anywhere (not even on the hardware Serial port).
Adding to setup() after ss.begin(GPSBaud):
ss.listen();

may make it work for the time being, but as soon as you start doing anything more with mySerial you could run into trouble.
If you need more than one serial port in your design then you really should be looking at using a more capable board with more hardware UART ports.

yeah i try to put ss.listen(); after ss.begin(GPSBaud) but it error.


text:
Arduino Mega Serial2 seems to stop functioning mid-sketch
thanks in advance for the advice.
I've got an Arduino Mega talking to a Cavro XL-3000 pump. After a lot of time I got the arduino successfully controlling the Cavro. However, the big problem I have now is after my Mega sends about a dozen commands, communication breaks down between the two. The Arduino sends commands and gets no response back from the Cavro. I've written code that, when the Arduino gets no response, it tries twice more before terminating the program.
For a while I thought the problem to be pump related. After all, my test code (the vast majority of my code is in a library I created to have the Mega talk to the Cavro pump) simply tells it to move the Cavro between two different positions interminably. But when I reset my arduino, it starts working again. Not when I reset the pump.
Finally, I hooked my logic analyzer up. It turns out that, when I get no response from the pump, it's because no command is reaching the Cavro. I am definitely successfully creating a command packet and sending it using Serial2.write(packet,packet_length).  And though the Arduino is calling these lines of code and thinks data is going out, nothing is actually going out on the TX line. It's like Serial2 gets tired after about a dozen calls and stops shifting out data even though I'm calling Serial2.write.
I'm pretty stumped. I'm clearing the receive buffer after each response, so no overflow there. Each time I send a command I wait until it is fully shifted out before moving on, so no overflow on the write buffer either. If I get no response back from the pump I try two more times. On the last try, I shut down Serial2, begin it again, and wait until it is connected (while(!=Serial2)). But even after I do all this, Serial2.write isn't actually sending out data. My logic analyzer isn't picking anything up.
A simple reset of the Arduino and commands are actually going out again. Logic analyzer picks them up immediately. After about a dozen or so commands (it seems fairly random but never lasts very long), the same thing happens. I swapped out Arduino megas and the same thing occured.
So.

It seems to be a code issue (repeatable on multiple arduino megas)
It does not seem to concern the pump or the rs232 converter
A push of the reset button fixes it temporarily
My logic analyzer snoops in between the arduino and rs232 converter.
Serial2.write(packet, packet-length) is definitely being called.
I have no idea what's happening.

Here is a schematic. Any advice would be appreciated!

Here is my test code:
#include <Hydro.h>

Hydro pump;
void setup() {
  Serial.begin(9600);
  Serial2.begin(9600);
  pump.InitComm(0,true,"right");
  Serial.println("Communication initialized");
  delay(5000);
}

void loop() {
//  Serial2.begin(9600);
  //long mil = millis() - 10000;
//while(true){
  //if(millis() > mil + 10000){
    //Serial.println("Sending command...");

    //byte datastuff[10]={0x02, 0x31, 0x31, 0x41, 0x35, 0x30, 0x30, 0x52, 0x03, 0x27};
    //Serial2.write(datastuff,10);
    //Serial.println("Sending command...ONE");
    pump.AbsoluteMove(0,4000);
    delay(10000);
    //Serial.println("Sending command...2");
    pump.AbsoluteMove(0,9000);
    delay(10000);
    //Serial2.write(new byte[10] {0x02, 0x31, 0x31, 0x41, 0x35, 0x30, 0x30, 0x52, 0x03, 0x27}, HEX);
    //mil = millis();
}

Here is my library.
/*
Hydro.c - Library created for OEM communication with Cavro XL-3000 Pump.

11/23/2016
Written for Mega using Serial2, can we tweaked.
*/

#include "Arduino.h"
#include "Hydro.h"

Hydro::Hydro(void){}

const byte LineSynch = 0xFF;
const byte StartByte = 0x02;
byte seq = 0x31; //confirm this
const byte ETX = 0x03;
const byte EX = 0x52;
int length_total = 0;

//Initializes communication and then sets it to Fine (12000 steps) Control.
void Hydro::InitComm(int addr, boolean fc, String initdir){
    Serial2.begin(9600);
    Initialize(addr,initdir);
    delay(2000);
    FineControl(addr,fc);
}

//Top Level Send Command. First Queries the pump to make sure it's ready for a command.
//If Pump is ready, passes along actual command to MidCommand.
void Hydro::SendCommand(int addr, String command){
    byte status = Query(0);
    while(status==false){
        Serial.println("Query: Stat Error: Wait till Pump No Longer Busy.");
        delay(10000);
        status = Query(0);
    }
    Serial.println("Query: Pump Not Busy.");
    MidCommand(addr, command);
    ReadData(false);

}

//Executes the actual command by calling command.
//If no response received (command != true), tries again twice.
void Hydro::MidCommand(int addr, String command){
    bool response = Command(addr, command);
    if (response == true){}
    else if (response == false){
        //resend
        Serial.println("Command Failed. Resending.");
        bool response2 = Command(addr, command);
        if (response2 == false){
            //shut off
            Serial.println("Second Command Failed.");
            Serial2.end();
            delay(2000);
            Serial2.begin(9600);
            while (!Serial2){
                Serial.println("Waiting for S2 to Connect.");
                delay(1000);
            }
            Serial.println("Connected.");

            bool response3 = Command(addr, command);
            if (response3 == false){
                Serial.println("Final Command Failed.");
                while(true){}
            }
        }
    }
}

//Send a Command.
//Returns True if a response is received from the pump.
bool Hydro::Command(int addr, String command){
    command.concat("R");
    byte address = 0x31+ addr;
    int length = command.length()+1;
    byte dat[length];

    Serial.print("Command: The string command is: ");
    Serial.println(command);
    command.getBytes(dat,length);

    //Serial.println("Data----");
    //for (int i = 0; i < length; i++){
        //Serial.print("i equals: ");
        //Serial.println(i);
        //Serial.println(dat[i], HEX);
    //}
    //Serial.println("----");
    //Serial.print("Dat Length is: ");
    //Serial.println(length);

    //line sync, stx, add, seq, etc, checksum. 6. 6 + (length.data) == length.
    //Decided to ignore Line Sync. Pump seems to have no problem without it. So 5+length.data.
    length_total=5+(length-1);
    byte packet[length_total];
    int p = 0;

    //packet[p++] = LineSynch;
    packet[p++] = StartByte;
    packet[p++] = address;
    packet[p++] = seq;

    for (int i = 0; i<(length-1); i++){
        //Serial.print("i equals: ");
        //Serial.print(i);
        packet[p++] = dat[i];
        //Serial.print(".  Inserting Data: ");
        //Serial.println(dat[i], HEX);
    }

    packet[p++] = ETX;
    byte checksum = StartByte;

    for (int i = 1; i<length_total-1; i++){
        checksum = checksum^packet[i];
    }
    packet[p++] = checksum;
    int x = Serial2.write(packet,length_total);
    Serial.print("bytes written: ");
    Serial.println(x);
    seq++;

    //print out packet to verify.
    Serial.println("Packet----");
    for (int i = 0; i < length_total; i++){
        Serial.println(packet[i], HEX);
    }
    Serial.println("----");

    //Waits for packet to be fully shifted out.
    //Serial.flush could be used instead.
    while(Serial2.availableForWrite() != 63){
        Serial.println("Command: Waiting to finish sending command...");
        delay(1000);
    }
    Serial.println("Command: Finished Sending.");

    unsigned long time = millis();

    //looks for a response from the pump.
    //returns true if received.
    while(Serial2.available()==0){
        Serial.println("Waiting for Response...");
        delay(1000);
        if (millis() > (time+5000)){
            Serial.println("Resend Command.");
            return false;
            }
    }
    Serial.println("Command: Response Received.");
  return true;
}

//Both initialize at half force.
//Init with volve output to Right or Left.
void Hydro::Initialize(int addr, String dir){
    if (dir == "right"){SendCommand(addr,"Z1");}
    else if (dir == "left"){SendCommand(addr,"Y1");}
}

//If Fine Control is True (active), Resolution is 0-12000.
//Else If Fine Control is False (deactivate), 0-3000.
void Hydro::FineControl(int addr, boolean control){
    if (control==true){SendCommand(addr,"N1");}
    else if (control==false){SendCommand(addr,"N0");}
}

//See Fine Control for Integer Values
void Hydro::AbsoluteMove(int addr, int move){
    String mc = "A";
    mc.concat(move);
    SendCommand(addr,mc);
}

void Hydro::Execute(int addr){
    SendCommand(addr,"R");
}

//Sends a Query for Status.
//Returns true if Status byte is 60, ready for command.
bool Hydro::Query(int addr){
    MidCommand(addr,"Q");
    if ((ReadData(true)) != 0x60)return false;
    else return true;

}

//True to print out data, false to not.
//Grabs and returns the Status Byte.
byte Hydro::ReadData(bool print){
    byte status;
    int i=0;
    if (print == false){
        while(Serial2.available()){
            if (i==3){
                status = Serial2.read();
            }
            else Serial2.read();
            i++;
        }
    }

    else if (print == true){
        while(Serial2.available()){
            if (i==3){
                status = Serial2.read();
                Serial.print("i is: ");
                Serial.print(i);
                Serial.print(". Reading (s): ");
                Serial.println(status, HEX);
            }
            else {
                Serial.print("i is: ");
                Serial.print(i);
                Serial.print(". Reading: ");
                Serial.println(Serial2.read(), HEX);
            }

            i++;

        }

    }
    return status;
}

I'd start with moving string literals into the Flash memory. Who knows how much memory it uses.

Difficult to say, but if your last trace is "Final Command Failed." , you are probably stuck in the following infinite loop.
if (response3 == false){
    Serial.println("Final Command Failed.");
    while(true){}
}

as @Jack says, you might as well have problems with your bound arrays. You have a lot of "length+1, length-1" scattered everywhere, this is really hard to follow.

I'm not a C++ guy, but I have looked at the code and fail to find where some of the index's are set to the proper values (whatever that is.) Some of it may occur during instantiation, but...  Most of these I've seen are index related (out of bounds), so.. As an example, the code sequence of
for (int i = 0; i < (length - 1); i++)
    packet[p++] = dat[i];

Seems to me, if the bytes (length) of 'dat' is 6 assuming 6 bytes, then the loop will run from 0 to 4.  That would seem to lose 2 bytes? Some of the array indexes are difficult to track for their value, not knowing what you were thinking.
My suggestion is
1.) ensure indexes stay within bounds
2.) ensure every function call (related to problem) is checked for it's expected return status
3.) attempt to ascertain the number of operations that occur before failure.  This may give you a clue about indexes or lead to discover of other problems.
I don't think you have a hardware problem. Intermittent hardware doesn't do this either. This is a software bug, and it's sounds repeatable. Step three may be useful.
Best of luck :)


text:
4.7v as HIGH on digital output instead of 5v
I'm new to Arduino, just got my starter kit, and I noticed that digital outputs 3 & 4 have 5v as HIGH level while 5 to 13 have 4.7v as HIGH level.
Is it as it suppose to be?

Datasheet says?

Please add your code so that we can check that there isn't a problem there.

Also depends on what your driving via this output. Standard TTL is:

But CMOS will be a bit different:

The Arduino is connected to USB port of MacBook pro. I wrote simple code to check HIGH level on digital pins:
`void loop() {
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, HIGH);
digitalWrite(13, HIGH);
}`

Are those pins output? @d.a.  Please amend your question to post your entire code. You may also want to read up on how to make a loop.

@NickGammon as a point there.
Instead of putting that in loop(), of that in setup() and do the same readings to see if you have the same voltages.

I should point out, that after I tested, I noticed you omitted pin 9 from your list. A loop wouldn't have had that issue.

Yes, that's perfectly fine.
According to the datasheet, at 5V, the minimum voltage you can expect on a HIGH output (AKA VOH) is 4.2V. 4.7V is above that, so it's fine.

Thanks. That was weird for me, because 1 hour ago it was showing 5v to me. And I do not understand what changed.

Maybe the battery in your meter is running out?

Also if it is set to INPUT_PULLUP it will look HIGH but maybe with a lower voltage (depending on the impedance of your meter)

Some of the answers here suggest that a reading of 4.7V is in spec (which it is). As Majenko says, 4.2V is the minimum output high voltage, at an ambient temperature of 85°C, with a load of 20 mA, and Vcc = 5V.
However with no load, and at room temperature, I measured 4.99V on all of those pins, when set to OUTPUT and HIGH on my Uno. Test code:
void setup()
{
for (int i = 3; i <= 13; i++)
  pinMode (i, OUTPUT);
}
void loop()
{
for (int i = 3; i <= 13; i++)
  digitalWrite (i, HIGH);
}

That was weird for me, because 1 hour ago it was showing 5v to me.

Right. What were you doing an hour ago? Did you have LEDs connected to those pins? If so, what value resistor did you have in series with them? Or were you driving a motor from the pins perhaps?

Thanks everybody for help, I forgot to set pin 5 as OUTPUT. When I dit it, I got 5v on it.


text:
Brushed ESC won't move slowly
I'm trying to control the brushed motor in a Traxxas Slash RC car with the built-in XL5 ESC using the Servo library on Arduino. I previously had success controlling this car with a Pololu Micro Maestro, but it died on me, and so, while waiting for a replacement to arrive, I thought I'd give a more manual approach a try.
The problem is, the motor moves way too fast. My understanding is that, for this ESC (which allows for reverse driving), 90 degrees / 1500 ms should be the neutral point, with anything above this leading to progressively faster forward speed; and, below, reverse.
But, while it seems there is some speed modulation, the motor just abruptly begins with a very high speed at an angle (Serial.write(95)) of 95 or so, and then gets even faster from there.
A minimal version of my code is pasted below; my circuit has the signal pins of the steering and ESC servo connectors (white wires) attached to pins 2 and 9, respectively on a Pro Micro, their two 5V pins connected to each other (since the ESC supplies its own 5V), and their grounds connected to the Arduino's ground pins.
While it's possible that I need a special arming sequence to get this ESC to work properly (I do operate in the three-blink "training" mode, which is supposed to be slower), I would expect that problem to manifest as no motion at all, not too much motion.
I've tried powering the ESC with the original 9.1V battery (nominal 8.4V), and with a 8.4V regulated supply attached to a ~15V battery.
What could I be doing wrong here?
#include <Servo.h>

Servo throttle;

void setup(){

    Serial.begin(115200);

    throttle.attach(9);
    // throttle.write(91);
    // delay(300);

    int first = 90;
    for(int angle=first; angle < first+20; angle++) {
        Serial.println(angle);
        throttle.write(angle);
        delay(10);
    }

    // This doesn't work any better.
    // int first = 1500;
    // for(int us=first; us < first+10; us++) {
    //     Serial.println(us);
    //     throttle.writeMicroseconds(us);
    //     delay(50);
    // }

    throttle.write(90);
}

void loop() {
}

according to the documentation, you have to "teach" it the neutral, forward and reverse signals ........... your question has nothing to do with the Arduino

@jsotola After some more digging, you appear to be correct. After going through the   limit-setting sequence and also disabling or enabling the low-voltage detection (depending on power source), it works. However, I didn't have to do this with the Pololu driver, hence my original confusion. If you have a suggestion for where to move this question, I'm open to that. But I'll write an answer myself.

i  am unsure if the question fits anywhere in stackexchange , because it appears to be a device usage question

@jsotola So should I delete it?

just accept your own answer

Per @jsotola 's suggestion, I looked more closely at the manual (see the section "XK-5 Setup Programming"):

XL-5 Setup Programming (Calibrating your ESC and transmitter)
Read
through all of the programming steps before you begin. If you get lost
during programming or receive unexpected results, simply unplug the
battery, wait a few seconds, plug the battery pack in, and start over.

Disconnect one of the motor wires between the XL-5 and the motor. This is a precaution to prevent runaway when the speed control is
turned on before it is programmed.

Connect a fully charged battery pack to the XL-5.

Turn on the transmitter (with the throttle at neutral).

Press and hold the EZ-Set button (A). The LED will first turn green and then red. Release the button.

When the LED blinks RED ONCE, pull the throttle trigger to the full throttle position and hold it there (B).

When the LED blinks RED TWICE, push the throttle trigger to the full reverse and hold it there (C).

When the LED blinks GREEN ONCE, programming is complete. The LED will then shine green or red (depending on LowVoltage Detection
setting), indicating the XL-5 is on and at neutral (D).

I wrote a short program to send specified servo angles in [0, 180] interactively. The manual says to apply "full throttle" and "full reverse", but I wasn't exactly sure what these translated to in terms of servo angle/pulse width milliseconds. I gather that these are often given as 45° and 135° (1.25 ms and 1.75 ms), respectively, but that setting the limits to [0, 180] during this training period also worked. It's valuable to get the full range, so I can get finer gradations in speed. Since I don't expect to ever reach full speed in my application, and will only use the near-90 part of the range, this will be particularly helpful.
I'm still perplexed about what caused the original problem--the Pololu servo controller never needed this tuning process. Perhaps the limits were set to [45, 135], and I mistakenly sent 180, which put the ESC into some state not described in the manual. And I don't know whether I'll need to repeat this in the future, or
whether my new [0, 180] limits will prevent the above mistake from being a problem. For that matter, I don't know how non-volatile the non-volatile memory is on the ESC in which these limits are stored. Does it require periodic battery power to refresh?
Finally, while it might be even more particular to the XL-5 ESC and my power supply setup, another useful note is that the low-voltage detection mode might prevent movement independent of the setup process.


text:
Use the TCS3200 color sensor without the included LEDs
just a quick question. I want to know if it is possible to use the TCS3200 color sensor without the 4 LEDs included on the breakout board. I want to get the sky colors. Is that possible?

The photodiodes in the device itself have filters so it should theoretically be possible to use it without auxiliary light sources. Note, however, that the green and blue sensors have two sensitivity peaks and so using it outdoors without an infrared filter is not advised.

So how could I use the sensor without LEDs? I want to operate it using solar power and can't waste any energy. Can I just bridge them? Will I damage anything by doing that? Also is there any DIY infrared filter that I could build use with materials normal people have at home?


text:
Arduino nano getting powered through analog input?
I noticed something today. I am powering the Arduino Nano from a battery and a 5v step up converter. That works just fine and I'm getting a stable 5v output. I have a second cable coming out from the battery which plugs right into analog input A0 set as input so I can measure the battery voltage. However when I disconnect the battery from the usb plug and leave the voltage sensing cable connected to the analog input the power led stays on. I want it to shut down and be disconnected from the power source and have the voltage sensing cable still connected.
How can I fix this?

Power is flowing from the analog pin, through the internal clamping diodes, to the Vcc line. Those diodes are however not designed to handle that much current, so don't continue doing this.
Either also disconnect the ground wire from the battery, or simply add a resistor between the battery and the analog pin. Something like 10k. That way less than a mA of current will be clamped, and the arduino will stay off.

But how high of a voltage drop will I have then? I can't have any if I'm measuring battery voltage which needs to be precise

Negligible. The analog pins are high impedance inputs. The ADC is optimized for analog signals with an output impedance of approximately 10k or less.

Thank you. Another question: Do you know any transistors/FETs with a very low voltage drop which I need for switching off a sensor?

@qwertz That is a completely different topic. Don't ask it in a comment.  Instead that question is best asked in http://electronics.stackexchange.com since it has nothing to do with Arduino.

Ok so I'll create a new topic for that, thanks

Any (MOS)FET will do. They don't have a voltage drop, like regular transistors do. They only have a very low resistance. Like e.g. 50mΩ. Which would create a voltage drop of 50mV if 1A of current is passed.

This addresses a subset of your question which was covered in your added comment-question. I've addressed use of a 20V full scale input range to make the answer more general. The results would be "even better" for your 5V input case. Note that is Vin ~= 5V you would want a measurenet range somewhat above 5V max so that you can handle typical voltage variations.

Do you know any transistors/FETs with a very low voltage drop which I need for switching off a sensor?

If you used a say 10k resistor in the upper leg of a voltage divider and added a MOSFET switch with an on resistance (Rdson) of 2 Ohms (a terrible spec) between Vin and the divider then the error introduced would be about 2/10k = 1:5000. If measuring a say 12V  battery and using a Vinmax voltage of 20V the error in voltage measurement would be in the order of 20V/5000 = 4 mV. If using an Arduino Nano with a 10 but ADC the resolution (not accuracy) is 1 in 2^10 = 1:1024 or 20V/1024  = about 19 mV for a 20V input range. ie the resistor introduces an error of about 1/5th of a bit of available measuring accuracy.
Worse (or better) - if you use 1% resistors they will swamp errors caused by ADC resolution. Even use of say 0.1% resistors or calibration is liable to produce a result where ADC resolution is not the main limiting factor.
Even with no resistive divider, getting accuracies that are doinated by the 1:1024 ADC resolution and not other factors takes care and effort. At 5V in ax ADC resolution of 1:1024 means that a variation of 1 part in 2048 could cause an erroneous reading. Input offset voltages, thermal effects, board and connector resistances and ground voltage dropsm and offsets can easily provide greater error magnitufes.
Test: Take a working design. Set meter to lowest voltage range such that 1 mV can easily be seen. (Ideally 200 mV range. 2V range marginally OK). Measure ground voltages between various "ground" points at various locations in the system. Differences ofm mV to 10's of mV can often be found. Differences are poptentially higher if power current are present - say 10's of mA or more.


text:
Use Arduino to detect low battery state and shut it down
I wanted to know if it is possible to monitor a battery that is driving the Arduino and check its voltage. When the voltage drops below a certain level (i.E below 3.0V) it should shutdown and disconnect itself from the battery by using a relay or something. When the battery is full enough again it should power up again. Is that possible without any external sensors just by using the Arduino's inputs?

After it has "disconnected itself from the battery", how would it know that the battery is full enough again?

I don't really know, that's why I'm asking here. Maybe use a programmable attiny45 which controls the voltage and the relay? If that is not possible just shutting down is enough for me

Have a look here
http://wp.josh.com/2014/11/06/battery-fuel-guage-with-zero-parts-and-zero-pins-on-avr/
It is for bare metal Atmel chip, but applicable to Arduino as well probably.
Step one in getting longer battery life is to move to a bare metal Atmel chip, choose ATMEGA or ATTINY depending on how many pins you need.
Also see my answer here
What are (or how do I use) the power saving options of the Arduino to extend battery life?

You also probably do not need a relay to disconnect the chip. Assuming you have the chip connected directly to the power supply with no regulator (which you do if you are running off battery), then you can just have your software put the chip into sleep mode which uses a negligible amount of power (micro amps). You can even set things up so that the chip will wake itself when the battery is reconnected to a charger. He is an example circuit and software using an ATTINY that does just that... https://github.com/bigjosh/Vibe-V2

I'm assuming Arduino is powered directly by the battery, and not via a voltage regulator. In that case you van measure VCC by first measuring the internal 1.1v voltage reference (in relation to Vcc). Since the internal 1.1v is constant and VCC will lower over time, the reading (0-1023) will increase.
See this article:
http://jeelabs.org/2012/05/04/measuring-vcc-via-the-bandgap/


text:
Choose the correct solar panel and battery for solar use
I am planning to build a weather station powered by solar power. I want to use an Arduino Nano because it's low power requirement. I want to connect some basic sensors to it (temperature, humidity…) as well as an anemometer, a wind vane and a rain gauge. The weather data should be sent wireless via 433 mhz to a raspberry pi, which acts as a web server. I do not have power cable access to the Arduino so solar is the only option.
Which solar panel should I use? I was planning to use 2 2.5W 5.5V panels which charge a Lithium-Ion battery which powers the Arduino using a step up converter. Assuming I have 2-4h of direct sunlight per day and I want to query the sensors every 5 minutes, how big of a battery should i choose? I don't want it to go out of power and want it to last a couple of days without sun.

How large is the load?

I don't know. I heard the Arduino nano draws very little power so I would say about 40-60mA under max load once every 5 minutes. It takes very little in sleep mode like 5mA. I dont own one yet so I am just assuming this based of data I read on the internet

I think 2 panels is way overkill. With 8 hours of daylight and 50% efficiency that will result in 4Ah. That's 166mA you'll have available constantly. With that amount of power available you wouldn't even have to consider putting the arduino to sleep.

I don't have 8 hours of daylight. The direct daylight ranges between 1h in the winter to 6 hours in the summer and I also want it to be substainable in the winter. Also the lithium charger accepts input voltage from 4.5V to 5.5V .

I won't be able to tell you which solar panel or battery to use, but I can tell you how to figure that out.
Battery
For the battery there are a few different ways to figure this out:

The most common way to do this at the professional level is to build the device and run it attached to an energy meter and measure it for an hour or two performing its usage, and use that to calculate how much it will use over a 48 hour period. That being said that type of test equipment is not really a hobbyist piece of equipment and probably not something you are wanting to obtain for this project.
You can try and use the datasheets for all of your components to determine their idle and active current draw is, add them up for idle and active, adjust the values based upon the efficiency of your step up converter (so if it only 75% efficient, divide them by .75), guesstimate how long your sensor read process will take, multiply your active current draw times the voltage and times the time it will take (in hours, so if this is a few seconds, it will be a really small decimal), multiply your idle current draw times the voltage and times .083 hours (5 minutes), add those two together multiply it times 12 (12 - 5 minute periods per hour) and then by 48 (two days) and that will be an estimate of your energy usage for two days. Now this will be a very rough estimate as the datasheets only provide nominal values, and their actual usage in practice may be different, which leads me to the final option...
A hybrid between the two above solutions. Set up your device and have it read the sensors and transmit continuously. Then use a multi-meter to measure the current usage of it actively being used. Repeat the measurement again but this time with it running on an indefinite timer to simulate being idle. Then take those two numbers and use the above formula substituting the datasheet estimates with your actual measurements to get a much more accurate picture of what your energy usage will be.

Once you have your energy usage (this will be in milli-Watt-Hours or mWH) pick a battery voltage you will be using (this is based on the charge circuit you are using, typically, single cell lithium ion batteries are 3.7 or 4.2, with multi-cell batteries being multiples of those), divide your energy by the voltage to get the power (in milli-Amp-Hours or mAH) and you'll want to pick a battery greater than that. You'll also want to double check the data sheet of your step up converter and see what the drop out voltage is, and then compare that to the datasheet for the battery and see at what capacity it hits that voltage. You'll want to make sure that it is at least 80%. Otherwise you'll have to pick a different battery with a larger capacity, or a different step up converter with a lower dropout voltage.
Solar Panel
For the solar panel, what you will want to do is get a battery charger designed specifically for use with solar panels. This is because when it says 5.5v solar panel, that is it's nominal voltage in full sunlight, however, it most often will not be that and will vary greatly throughout the day. What this means is that solar panels are basically on unregulated power supply, and most battery chargers require a regulated power source. With a solar specific batter charger, it is designed such that it can handle voltage variation and sudden dropouts. Usually these chargers come with a recommendation as far as voltage and current requirements and those specifications should form the basis of your solar panel selection.
So for example, if you have a battery, on the datasheet it will list what its charge current is, and you'll want to make sure you have a charger circuit that can supply that amount of current. Then you'll want to take a look at the datasheet for the charger circuit, see what current it requires and then make sure that the solar panel can provide that current.

Wow thank you very much for this detailed answer. So I guess I'll have to calculate all the power draw of each component and figure out the battery size depending on it. About the solar panel: I found a lithium-Ion chargin circuit for it which requires an input of 4.5V to 5.5V, which is perfect for the solar panel I guess. How can I then figure out the solar panel power I need? Basically I have 1-5h of direct sunlight per day.

You will be unhappy if you attempt to connect the solar panel directly to the charger. You need a MPPT regulator, which will allow you to maximize the power drawn from the panel.

I've made an edit, see the bottom. I hope you are catching the general theme here: check the datasheet. Electronics work, especially power design, is more math than it is design. You just need to make sure that at each stage of power that you are providing enough current for the next device and that you are leaving enough extra room for power loss. Things like going from one voltage to another or charging a battery are not 100% efficient, so you have to add in some extra for tolerances.

Also to reinforce what I mentioned at the beginning of the Solar Panel section, and echo what Ignacio commented, you really should use a charging circuit designed specifically to work with solar panels. Here is one as an example https://www.sparkfun.com/products/12885 (this does not constitute an endorsement of this product). They can be a little more expensive than regular chargers, but not too much and totally worth it.


text:
How to change LDR output in simulator 123D Circuits?
I used simulator 123d.circuits.io to create simulation of basic circuit with LDR: LDR is connected to 5V and via 10K resistor to GND. Wire between LDR and resistor is connected to analog pin where I read ADC values and display them using serial monitor. This works fine. But I would like to how to change lighting level of LDR in simulation because this way LDR shows still the same value. I tried putting LED or light bulb near LDR but it doesn't seem to have any influence. Any ideas?

Ok, so I found it myself. You can click on LDR during simulation and bar to adjust lighting appears above it.

Please use the edit link on your question to add additional information. The Post Answer button should be used only for complete answers to the question.

It is complete answer to the question.


text:
Can I connect TFT LCD screen to Arduino Leonardo same way as it's recommanded for Arduino Uno?
I want to connect the Arduino TFT LCD 1.77" screen to an Arduino Leonardo. Acording to this tutorial I should connect some pins on LCD screen to ICSP pins on Leonardo but I don't have equipment to do it. Can I just connect LCD screen to Leonardo in the way it't recommanded for an Arduino Uno (same tutorial above) using only digital and power pins. And then use sketches for Uno. Will it work?
Also, is it safe for LCD screen?

Datasheet where?

I think it could work, but not easily. I.e. you would need to tweak the code and anyway you will end up with really low performance.
This is the reason:

SPI: on the ICSP header. These pins support SPI communication using the SPI library. Note that the SPI pins are not connected to any of the digital I/O pins as they are on the Uno, They are only available on the ICSP connector. This means that if you have a shield that uses SPI, but does NOT have a 6-pin ICSP connector that connects to the Leonardo's 6-pin ICSP header, the shield will not work.

Source: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo

The screen can be configured for use in two ways. One is to use an Arduino's hardware SPI interface. The other is to declare all the pins manually. There is no difference in the functionality of the screen between the two methods, but using hardware SPI is significantly faster when drawing.
  If you plan on using the SD card on the TFT module, you must use hardware SPI.
  All the examples are written for hardware SPI use.

Source: https://www.arduino.cc/en/Guide/TFT#toc4
In the end I think it would be better to get the equipment needed...
Edit: You can try with this constructor:

When not using hardware SPI, you can use any available pins, but you must declare the MOSI and SCLK pins in addition to CD, DC, and RESET.

#define SCLK 4
#define MOSI 5
#define CS   6
#define DC   7
#define RESET 8

TFT myScreen = TFT(CS, DC, MOSI, SCLK, RESET);

Source: https://www.arduino.cc/en/Reference/TFTLibrary

You can hook up the "Adafruit_ST7735" or from what i later learned after getting my Esplora. Thats when i had my adruino-epiphany. Okay so IF your wondering why im including this super rad Controller shaped arduino, the answer is, its a leonardo. well its just a different flavor of the Atmega32u4 whis is the chip that made ext serial programmers kinda obsolete and makes the uno and megas so unique as well. so with that being said the Esplora has a native language when refering back the tft libraries, but its not too far from a simple (ctrl+F) and replace Esplora references with actual defines and references. and in this case the Leonardo would need to have the icsp header used by the corresponding pins on the display (for this instance of using an SPI connection with the serial display we will not swap the Miso and Mosi  like we would a nother instance.just connect miso to miso and mosi to mosi i usually plug up the whole icsp header and then that wwill leave you with the two pins you MUST DEFINE to make it work which would be :
// Pins SCLK and MOSI are fixed in hardware, and pin 10 (or 53)

// must be an output
//#define sclk 13    // for MEGAs use pin 52
//#define mosi 11    // for MEGAs use pin 51
define cs 10   // for MEGAs you probably want this to be pin 53
define dc 9
define rst 8  // you can also connect this to the Arduino reset
// Pins SCLK and MOSI are fixed in hardware, and pin 10 (or 53)

// must be an output
//#define sclk 13    // for MEGAs use pin 52
//#define mosi 11    // for MEGAs use pin 51
define cs 10   // for MEGAs you probably want this to be pin 53
define dc 9
define rst 8  // you can also connect this to the Arduino reset
// Color definitions
define BLACK           0x0000
define BLUE            0x001F
define RED             0xF800
define GREEN           0x07E0
define CYAN            0x07FF
define MAGENTA         0xF81F
define YELLOW          0xFFE0
define WHITE           0xFFFF
include
include
// Option 1: use any pins but a little slower
//ST7735 tft = ST7735(cs, dc, mosi, sclk, rst);
// Option 2: must use the hardware SPI pins
// (for UNO thats sclk = 13 and sid = 11) and pin 10 must be
// an output. This is much faster - also required if you want
// to use the microSD card (see the image drawing example)
ST7735 tft = ST7735(cs, dc, rst);
float p = 3.141592; // value for pi
int tft_width = 128;
int tft_height = 160;
int x1 = 60;
int y1 = 60;
int x2 = 20;
int y2 = 80;
int ballx = 60;
int bally = 60;
int deltay = 1;
int deltax = 1;
int ball_speed = 24;
int left_score = 4;
int right_score = 4;
int background_color = 0x00;
void setup(void) {
  tft.initR();               // initialize a ST7735R chip
tft.writecommand(ST7735_DISPON);
  tft.fillScreen(background_color);
  delay(700);
  for(int i = 0; i < 9; i++){
    pinMode(i,OUTPUT);
  }
  for(int i = 0; i < 9; i++){
    digitalWrite(i,HIGH);
  }
  delay(500);
}
void loop() {
  for(int i = 0; i < left_score; i++){
    digitalWrite(i,HIGH);
  }
  for(int i = 0; i < right_score; i++){
    digitalWrite(i+4,HIGH);
  }
  int cur_r = random(20,32);
  int cur_g = random(55,64);
  int cur_b = random(10,32);
  int color = cur_r  | (cur_g << 5) | (cur_b << 11);
  int radius = 4;
  draw_paddles();
  draw_ball(color);
  delay(ball_speed);
}
void draw_input_text(){
  int cur_x2 =  analogRead(2);
  int cur_y2 =  analogRead(3);
  String xs = String(cur_x2);
  String ys = String(cur_y2);
  char cx[4];
  cx[0] = xs.charAt(0);
  cx[1] = xs.charAt(1);
  cx[2] = xs.charAt(2);
  cx[3] =0;
  char cy[4];
  cy[0] = ys.charAt(0);
  cy[1] = ys.charAt(1);
  cy[2] = ys.charAt(2);
  cy[3] =0;
  tft.fillRect(10,20,40,40,background_color);
  tft.drawString(12,22,cx ,YELLOW);
  tft.drawString(12,40,cy ,YELLOW);
}
void draw_paddles(){
  int cur_x =  analogRead(0);
  int cur_y =  analogRead(1);
  int hval = 620;
  int lval = 350;
if ( y1 < tft_height - 20  && cur_y > hval) y1++;
  else if ( y1 > 0 && cur_y < lval ) y1--;
int cur_x2 =  analogRead(2);
  int cur_y2 =  analogRead(3);
if ( y2 < tft_height - 20 && cur_y2 > hval ) y2++;
  else if (y2 > 0 && cur_y2 < lval ) y2--;
  tft.fillRect(2, y1-3, 5, 27, background_color);
  tft.fillRect(3, y1, 3, 20, YELLOW);
  tft.fillRect(tft_width-3, y2-3, 5, 27,background_color);
  tft.fillRect(tft_width-3, y2, 3, 20, YELLOW);
}
void draw_ball(int color){
   int bradius = 6;
    tft.fillCircle(ballx, bally, bradius , color);
    ballx += deltax;
    bally += deltay;
    if ( ballx < 7 && bally > y1 && bally < y1+20) deltax *= -1;
    else if ( ballx > tft_width-7 && bally > y2 && bally < y2+20) deltax *= -1;
    else if ( bally <= bradius || bally >= tft_height - bradius ) deltay *= -1;
    if (ballx <=  0 ) {
      left_score--;
      tft.drawString(2,42, "Right Won!" ,~background_color,2);
      tft.drawString(2,62, "Get Ready!" ,CYAN,2);
      for (int i = 0; i <250; i++){
        delay(10);
        draw_paddles();
      }
      int cur_r = random(0,26);
      int cur_g = random(0,30);
      int cur_b = random(0,18);
      background_color = cur_r  | (cur_g << 5) | (cur_b << 11);
      tft.fillScreen(background_color);
      ballx = 64;
      bally = 80;
      if (ball_speed > 1) ball_speed--;
      digitalWrite(left_score,LOW);
    } else if (ballx >= tft_width  ) {
      right_score --;
      tft.drawString(2,42, "Left Won!" ,YELLOW,2);
      tft.drawString(2,62, "Get Ready!" ,GREEN,2);
      for (int i = 0; i <250; i++){
        delay(10);
        draw_paddles();
      }
      int cur_r = random(0,26);
      int cur_g = random(0,30);
      int cur_b = random(0,18);
      background_color = cur_r  | (cur_g << 5) | (cur_b << 11);
      tft.fillScreen(background_color);
      ballx = 64;
      bally = 80;
      if (ball_speed > 1) ball_speed--;
  digitalWrite(4+right_score,LOW);

}

}
enjoy getting that code to fudge around with  i  stole it right form  here http://lucidtronix.com/tutorials/7
 but the point i had to bring up is that i believe the guy before mentioned that it is a muchslower connectionor process than if it were.....were you saying softwareserial was the option then?
 because im not an explert or novice or maker by any means. but i have picked up along the lines that hardware serial will always trump software serial compilation any day once you get your head wrapped around the brevity of what ports and pins are actually what are used or have the data displayed on the serial ports. and like software is a necessity im afraid, but its as simple as reasigning pins and when that gets too hard going out and just bbuying a mega, haahah hope i sorta helped. id say go out and snag an esplora whilst their like toing a fire clearance sale on the originallt 50$+ boards. but their reference and prebuilt array of sensors is a bit underwhelming for the newbies in what it alll does, but kinda overwhelmine and difficult to transistion onece having looked at some code as it is, but the language is more forg9ving, but i believe their also officially retiring the leonardo espolora and micro series so good luck this tft display kicks bum man and is the only one that hsnt broke


text:
12V from Arduino Uno
I don't think it's possible, but I want to drive my 433 MHz transmitter (FS21000A) from a 12V 'supply', to get more power (and thus more range).
However, I don't have an external power supply. I can add an adapter (12V/1A) to my Arduino with the barrel input, but I wonder where to get 12V from? I only see 5V or 3.3V outputs.
And as far as I know all GPIO output 5V ... so how can I get 12V (or maybe a bit less but more than 5V) out of an Arduino? (and what safety measurements I should take to not ruin my Arduino?)

VIN is the barrel jack less one diode drop.

So VIN is more like an output (to give power to external components)?

It is neither input nor output. It just is. Power has no concept of in or out.

Ok clear,  going to use it now

What transmitter is it?

It shows RF-5V, but it looks like the small right component in http://uploads.avc-shop.de/uploads/ebay/bilder/mhzsender-1402092733-21335.jpg

Oh, one of those. They're pretty naff really. Have you tried adding a 1/4 wavelength dipole to it?

@Majenko ... not yet ... I think I'm going to try it with two ... also ordered some (cheap) antennas for it to solder on ... I just bought these 433MHz to check, I hope in my project I can use nRF24L01 2.4 GHz, which are much faster (and hopefully more range). But if I get these to work to like 10 meters or so I can find some nice use for it later (and it's all part of learning about RF/electronics too)

I have got hundreds of meters from the nRF24L01+ modules with build in LNA and power amplifier. They work well.

@Majenko ... I ordered long time ago a cheap set of 5 ... still haven't received them but no problem to wait ... However, yesterday I ordered two with antennas and PA+LNA, think that is what you mean? https://www.aliexpress.com/item/1sets-Special-promotions-2-4G-wireless-modules-1100-Meters-Long-Distance-NRF24L01-PA-LNA-wireless-modules/32787846044.html?spm=a2g0s.9042311.0.0.97LZRv

Yep, that's the ones.

I think I will get the ultra-cheap ones first, so I can already experiment with those (in close range, like max 50 cm), I hope to get error-free communication with some speed with the PA+LNA ones.

@Downvoter, can you instead of downvoting all my posts, explain WHY you downvoted, so I may improve the post.

In crude terms the power supply of the Arduino is along these lines:

simulate this circuit – Schematic created using CircuitLab
It's actually more complex than that, especially concerning the USB power input, but that doesn't matter here.
As you can see the barrel jack (your 12V supply) first goes through a diode. Then it gets fed to the 5V regulator. The VIN pin also goes to the same pin of the 5V regulator, so it will see 12V minus the voltage drop of the diode (~0.7V).
So you can provide 12V to the barrel jack and use the VIN pin as an 11.3V supply.

It worked, thanks... however, I don't see any range increase (and also noticed I cannot upload a sketch while both USB and adapter are plugged in at the same time.
But I learnt something (again).. thanks again!

I want to drive my 433 MHz transmitter (FS21000A) from a 12V 'supply', to get more power (and thus more range).

that only works if the transmitter works at 12v and isn't powered through a regulator.
if not, applying 12v to it does nothing but generating some heat or damage, worse yet.

The transmitter is indeed able to work from 2-12V, and I according the scheme of Majenko the regulator is not going out of VIN (unless the regulator is in de adapter itself).
I checked, it worked, however, I don't see any noticeable gain.


text:
Use PWM to play notes on ATMega328
I have old speaker which I want to use to play sound. I chose to use PWM mode on ATMega328 (which is in turn on Arduino Uno R3 board) in order to do it.
For signal on the speaker I chose rectangular wave because it does not require any additional setup. To generate this signal I chose timer1 because it is easy to change PWM frequency just by changing ICR1 value. For duty cycle I chose 50%. So my program looks as follows:
#define     CLK_FREQ 16000000   //clock frequency on ATMega328
#define     PRSCLR   1024       //chosen prescaler of timer1

//duration of one note
unsigned int halfDur = 200;
//number of notes in the melody
const int notesSize = 32;
//frequencies of notes in the melody:
unsigned int notes[notesSize] = { 220, 277, 329, 277, 220, 277, 329, 277,
                                  207, 277, 329, 277, 207, 277, 329, 277,
                                  184, 277, 369, 277, 184, 277, 369, 277,
                                  220, 293, 369, 293, 220, 293, 369, 293 };
//method to play one note
void PlayFreq( unsigned int freq );

void setup()
{
    //PB1 pin in OUTPUT mode
    DDRB |= ( 1 << DDB1 );

    TCCR1A = 0b0;
    //non-inverting mode of PWM
    TCCR1A |= ( 1 << COM1A1 ) | ( 1 << COM1B1 );
    //Fast mode PWM with ICR1 as TOP:
    TCCR1A |= ( 1 << WGM11 );
    TCCR1B = 0b0;
    TCCR1B |= ( 1 << WGM12 ) | ( 1 << WGM13 );
    //prescaler = 1024
    TCCR1B |= ( 1 << CS12 ) | ( 1 << CS10 );
}

void loop()
{
    for ( int i = 0; i < notesSize; i++ )
    {
        PlayFreq( notes[i] );
        delay( halfDur );
    }
}

void PlayFreq( unsigned int freq )
{
    //claclulate TOP according to note frequency
    ICR1 = CLK_FREQ / PRSCLR / freq - 1;
    //50% duty cycle
    OCR1A = ICR1 / 2;
}

Problem is only several first notes are playing and then there is no sound, then again I hear some notes then there is no sound and so on. It seems that tempo is OK. It just skips some notes. What it could be?

Why not use the built-in tone() function?

@Majenko, I will try it now. Thx.

Yes, it works perfectly. But what's wrong with my code?

Just a couple of remarks, unrelated to your problem: 1. There is a macro named F_CPU which is already defined and holds the clock frequency. No need to define CLK_FREQ yourself. 2. You would get a better frequency resolution by setting the prescaler to 64. Actually, if your frequencies are always higher than 31 Hz, you could even set the prescaler to 8.

@EdgarBonet, Thank you for your remarks. Useful.