text:
What is actually an IC (Integrated Circuit)?
They say that you must know what IC your board has before loading a new program from the Arduino IDE and that the information is available on the top of the IC, but where is it exactly and what is an IC?

https://en.wikipedia.org/wiki/Integrated_circuit

IC stands for integrated circuit, which is a generic term encompassing any class of devices that has multiple electronic components (transistors, and possibly capacitors, resistors, diodes, and more) encased and interconnected within. The opposite of an integrated circuit is a discrete component, which is a single electronic component in its own package that relies on wiring (or a circuit board) to connect to other components.
Taking a look at the Arduino Uno R3 below (click for larger image), the long rectangular black thing is the primary IC. You can see the ATMEL logo on it, followed by a short series of numbers (a date code if I'm not mistaken). Below is the chip model itself; in this case, "ATMEGA328P-PU". With respect to the Arduino IDE, it's sufficient to know that the chip is an ATmega328P, which is sometimes incorrectly called ATmega328 in the Arduino world.

If you look closely, there are also several other ICs on the board. To the right of the ATmega328P is a small 5-pin package; if I'm not mistaken it's an LP2985-33DBVR, which is a low-dropout voltage regulator. On smaller packages like this they often have more cryptic legends printed on them, in this case if you squint at the full-size picture you can make out "LPFL". Fortunately for most Arduino development purposes, knowing the model of these auxiliary ICs is generally not necessary. Just below that, above the crystal (the metal oblong can marked SPK16.000G) is an 8-pin package marked 09TI R5R, which I believe is a LMV358IDGKR dual op-amp.
Another IC of note on this board is the small square 32-pin package below the crystal; this is an ATmega16U2. In the case of the Arduino Uno R3, rather than being the primary microcontroller, this serves as the USB-to-serial converter.
Note that to the right of the crystal is a small three-pin package marked "340"; this is a FDN340P MOSFET. While this model of MOSFET (as with many others) contains an integrated diode across its drain and source and could thus technically be classified as an integrated circuit, most would still consider it a discrete component.

@per1234 thanks for the corrections :)

It's funny that you have a picture of one in your profile pic. :)

The arrow points to the most obvious integrated circuit or chip in you pic, there is another square one to the left of the TX and RX markings.  There are lots of different types of ICs -- most are black and come in different shapes and sizes, different number of legs, but most have some form of writing on the back that Google can use to locate the data sheet, or general help.  Have a quick look on Wikipedia for a more authoritative description.


text:
Problem with the Frequency meter code
I am trying to build a frequency meter using Interrupts and Timer1, which works as if the system receives an Interrupt it would get the timer's data and would calculate

Signal's Frequency = 1 / (Counter * Timer's Period) => F_s = F_t/TCNT

but the result is way off, and it does not even make sense. I have had altered my code to look that if the timer's data is not valid or sth, but the number that the timer counter has counted is sth that I expect.
Here is my code:
int f=0;
char msg[50];

void setup()
{
  Serial.begin(115200);
  noInterrupts();           // disable all interrupts
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  TCCR1A = 0;
  TCCR1B = 0;
  OCR1A = 0;
  OCR1B = 0;
  TCCR1B |= (0<<CS12)|(1<<CS11)|(0<<CS10);    // Clock 2MHZ
  TCNT1  = 0;
  TIMSK1 = 0; // disable timer overflow interrupt
  interrupts();
  attachInterrupt(1,pin_ISR,RISING);
}

void pin_ISR(){
  //digitalWrite(13,!digitalRead(13));
  f = 2000000/TCNT1;
  TCNT1=0;
}

void loop()
{
  sprintf(msg,"Humidity:%d \n",f);
  Serial.print(msg);
}

Your code works for me but, as @Jot noted, it would be more robust if you make f volatile and read it with interrupts blocked.

As stated in my comment, your code is kind of fine. Id mostly works,
but it looses a few microseconds on each iteration. If you are looking
at multi-kHz frequencies, you probably want to avoid loosing
microseconds. The solution is simple: never reset the counter. I
changed you ISR as follows:
uint16_t previous_counter;

void pin_ISR(){
    uint16_t counter = TCNT1;
    f = 2000000/(counter - previous_counter);
    previous_counter = counter;
}

and now it gives the correct frequency... on average. There are some
variations though, dues mostly to delays caused by other interrupts.
Edit 1: If you want to avoid the fluctuations caused by other
interrupts, your best bet is probably to use the input capture feature
of Timer 1.
Edit 2: Here is why your measurement was somewhat off. Your original
ISR essentially does something like this:
void pin_ISR() {
    uint16_t temporary_value = TCNT1;
    loose_some_time();
    TCNT1 = 0;
}

The time you loose in the ISR is the part of the signal period you are
not measuring, which means you are underestimating the period by that
much. In the ISR you posted, this is mostly the time taken by a 32-bit
division, which is quite significant. A simple improvement would be to
clear TCNT1 right after reading it:
void pin_ISR() {
    uint16_t temporary_value = TCNT1;
    TCNT1 = 0;
    loose_some_time();
}

and now the average period you measure is almost right. It is not
perfect though, as the whole reading and writing of TCNT1 takes
8 CPU cycles.
The alternative I am suggesting, where you never clear the timer, is
the correct way of measuring a period with a timer interrupt: you don't
loose a single CPU cycle. The best way is to use input capture: you get
rid of the software-induced jitter.
Note: You should also take care of the very valid points raised in
Jot's answer, about making f volatile and reading it with interrupts
disabled.

This worked perfectly. Thanks! But I don't get it, my timer was ticking on a 2Mhz clock, and the number of TCNT is usually around 297, 298 if I change the code to display that, and with the way you told me to change it, it still remains very much the same. I don't know why this is happening! Although I must say that I am simulating my program in Proteus.maybe it's a bug.

Did you find an example that works that way ? Is it, for example, allowed that the TCNT1 is cleared in an interrupt routine? The TCCR1A is cleared, but not set to a value ?
[edit] Clearing TCCR1A is okay. Clearing TCNT1 is also okay, but can be improved as @EdgarBonet shows.
The calculation uses a long of 2MHz, but the others are 16 bits. Could you force that calculation with long ? f = int( 2000000L / long( TCNT1));
[edit] It is not needed to force the compiler into a 'long' calculation, it already does so.
The 'f' variable is used in an interrupt and outside that interrupt. It must be made 'volatile': volatile int f=0;
The 'f' is used in the loop, but the interrupt could happen when 'f' is only half read or half written. The ATmega328P is a 8-bit microcontroller and 'f' is a 16-bits variable. I suggest to disable the interrupts and make a copy.
noInterrupts();
int fcopy = f;
interrupts();
sprintf(msg,"Humidity:%d \n",fcopy);

What is the range that you want to measure ?
Do you know that there are good libraries to measure a frequency ? They are the FreqMeasure Library and the FreqCount Library.
[ADDED]
Try to slow down the loop with a delay. If you fill the transmit buffer of the Arduino Uno TX, then the Serial.println wait for each character if there is a place in the transmit buffer.

You wrote: “Is it, for example, allowed that the TCNT1 is cleared in an interrupt routine?” Of course, why not? “The TCCR1A is cleared, but not set to a value?” It is set to zero, which is a perfectly valid value. “Could you force that calculation with long?” That's exactly what the compiler already does as part of the usual arithmetic conversions.

I'm measuring a frequency between 5khz to 7khz, it is showing me 8-9 khz for signals in the ranges of 6500~6600 hz.  I knew about the libraries but the code was so simple that I thought it would be a piece of cake, which was not.

That's not way off, it's actually kind of OK. You are just loosing about 50 µs.

@EdgarBonet, you are correct. The compiler did make a 'long' calculation, but I like to force a long calculation in code. I like to tell the compiler what to do, instead of letting the compiler think about it, because it's so easy to make a mistake in the code. The result of clearing TCNT1 depends on the frequency range, that's why I asked.

@EdgarBonet It's way off because the number of TCNT and the division does not make sense. I usually get about 297~307 in the TCNT on the interrupts and if you divide it by hand it should not give you 8000!

Your approach is basically a reciprocal counter and it can work, if you start and stop the timer in the isr. The logic is essentially this:
If timer is on stop the timer and save the timer count.
Else initialize the timer and start counting.
For counting a wide range of frequencies, you may need to consider timer over flow.
Edit: any solution that reads a multi byte counter while it is running will produce the wrong results. Google atomicity to understand why.

So I have had asked this question on the Arduino forum and some one has fixed my code which gives me the accuracy that I expect. The problem was that the division was better not to be in the ISR routine but in the main loop. Here's the link to that answer because that guy should be credited as he helped me big time.
https://forum.arduino.cc/index.php?topic=486573.0
Thanks to all who replied to me, I have learned many things about ISR's and their limitations.

Note that the answer you got in the forum is almost good. See my expanded answer for why it's still not as accurate as it could be.

@EdgarBonet Yeah I merged his code with yours and it works very accurate, and error about 4~6 Hzs which is awesome. Thank you thank you so much.

source: Stack Exchange

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

sort: votes


text:
mega2560- Interrupts reading digital input
Hi I am very new to Arduino, with very little programming experience.
I am using mega 2560 and trying to understand how interrupt works.
I have a code written, it is very similar as the example code Memsic2125, so i am gonna use that in here.
For my case, I am reading from my hardware, 5x5 array of sensors.
What I would like to do is to have it --   print out x and y using interrupts   , I want to print outputs the x and y every 10ms. Instead of printing it continuously right now.
I will be sending it out in 16 bits. I tried some other example and read a lot of material. but still couldn't get it to work.
Any idea, suggestion, help, comment is appreciated.

const int xPin = 2;
const int yPin = 3;

void setup() {

  Serial.begin(9600);
  pinMode(xPin, INPUT);
  pinMode(yPin, INPUT);
}

void loop() {

  int pulseX, pulseY;

  int x, y;

  // read pulse from x- and y-axes:
  pulseX = pulseIn(xPin, HIGH);
  pulseY = pulseIn(yPin, HIGH);

  x= ((pulseX / 10) - 500) * 8;
  y= ((pulseY / 10) - 500) * 8;

  // print x,y
  Serial.print("x,y= ( ");

  Serial.print(x);   Serial.print(,);
  Serial.print(y);   Serial.println(")");

  delay(100);
}

You are already printing every ~100 ms.

You can’t truly have an interrupt within the code (it’s a hardware thing) but you can simulate an interrupt through an ISR which you don’t have

There isn't any interrupt code in what you posted. What exactly is the problem?  One important note is that you shouldn't try to print to Serial line in the interrupt handler as serial is itself driven from interrupts which are switched off during your handler code.  If all you really want to do is to print something every 10ms then you don't need any interrupt.  Just use the "Blink Without Delay" style of timing and keep the other code from blocking.

The simplest would-be to read the data and loop around for your desired time.
Alternatively, time stamp the events and onkybread the data if the desired time has elapsed.
Or to use a timer interrupt for that.

What does  “onkybread the data” mean?

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

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


text:
Oscillating Analog Readings
I am using a JIC 139 UV Sensor (datasheet) with an Arduino Mega 2560 and should be reading smooth curves as I bring a UV source to towards the sensor. Instead, my curves are increasing and oscillating. How can I remove the oscillations and what is the cause of these oscillations?
Code:
float mapfloat(long x, long in_min, long in_max, long out_min, long out_max)
{
    return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + out_min;
}

int averageAnalogRead(int pinToRead)
{
    byte numberOfReadings = 8;
    unsigned int runningValue = 0;

    for(int x = 0 ; x < numberOfReadings ; x++)
        runningValue += analogRead(pinToRead);
    runningValue /= numberOfReadings;

    delay(100);

    return(runningValue);
}

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

void loop() {

   float pinRead0 = averageAnalogRead(0);
   float pVolt0 = pinRead0 / 1024.0 * 5.0;

   // In mW/m^2
   Serial.println(pVolt0);
   //  Serial.println(mapfloat(pVolt0, 0.0, 5.0, 0.0, 15.0));

   delay(100);
}

`
Here is a sample screenshot from the Serial Plotter at 3 different distances from the UV Source:

Would post cicuit but don't have enough reputation. Will post as response.
edit: I added a very large capacitor(3300 uf) between the output pin and ground which seemed to smooth the values a little bit but the noise still exists
edit: The x-axis is number of readings and the y-axis is voltage(0-5v) calculated from analogRead()

It is not your sketch, the sketch is okay. How stable is the 5V of the Arduino Uno ? It is most likely the analog circuit.

5 volt is stable at 5.01, any ideas as to what may be wrong with the analog circuit?

What is the x-axis scale?  (Eg, is it reading number, time, etc)?  [Please edit  reply into your question]

Without seeing circuit and construction details and oscilloscope traces, it's difficult or impossible to say what the problem is.  It may be due to op amp instability due to a large capacitive load.  It may reflect a beat frequency between some sensor and MCU signals, or aliasing between 60-Hz noise and your data-conversion rate.
Regarding op amp instability, see for example the article Op Amps Driving Capacitive Loads, by Grayson King.  Here is a quote from that article:

Q. How does capacitive loading affect op amp performance?
  A. To put it simply, it can turn your amplifier into an oscillator. Here's how: [...]

Rather than just connecting that big 3300 μF capacitor to the output pin, perhaps instead try attaching an Active Low Pass Filter to the output, or a unity-gain op amp followed by a Passive Low Pass Filter; etc.  Put big capacitors across power into the UV source and power into the sensor, instead of on the sensor output.
Regarding beat frequencies and aliasing, low-frequency oscillation like that seen in the trace may occur as a difference of two higher-frequency signals, or as a sampling artifact.  To check this out, attach an oscilloscope to the UV source and see if its power consumption oscillates; and/or try a more-rational sampling scheme than that shown in your code.
For example, instead of taking 8 readings within one millisecond in averageAnalogRead() and then waiting 100 ms, perhaps add a delay(1) inside the loop so that readings are spread out slightly more.  Remove the delay(100) from within averageAnalogRead().  Compensate by changing the other delay(100) in loop() to, for example, delay(191) or delay(193).  Try various delay amounts to see if they have an effect on the waveform.


text:
Connect Arduino Uno RX/TX to 3.3v NEO-M8N gps module
I'd like to connect an M8N gps module to an Arduino Uno. From what I understand

the Arduino pins 0-RX/1-TX work on 5V
the M8N RX/TX work on 3.3v
the sensor-TX sending to the Arduino-RX should work (3.3v is “good enough” to drive the Arduino-RX-pin)
the Arduino-TX sending to the sensor-RX is problematic because of the 5v (could break the sensor)
During USB-programming, the Arduino-RX sensor can be at 5v (so suddenly the current flows in the "wrong direction"- which could break the sensor)
A level-converter could be used to “translate” the voltages in each direction.

Assuming we don’t use a level-convertor

Could we use a schottky-diode (which as I understand blocks current in 1 direction) to block the 5V from the ArduinoRX going into the sensor?
But then the 3.3V from the sensor-TX would pass (correct direction ), but the diode will drop the voltage "a bit more"… is this still enough to drive the arduino RX-pin?
And it works, why not also use a schottky-diode to also protect the Arduino-TX to sensor-RX connection ( just to be safe, since some people were saying one some Arduino they needed to connect RX-RX and TX-TX to get the communication to work.. ? ).

As an alternative to the schottky ( or maybe in addition to it)
- Could we simply take 2 voltage dividers (for one for both RX-TX and TX-RX) ?
We can use a “resistive voltage divider” to lower the Arduino-TX 5v to 3.3 V
- I understand to get from 5V to 3.3V we need “x” and “2 * x” resistors-values, so e.g 1K Ohm and 2K Ohm… but how do I know which values would be appropriate ( I mean, we could also take 10K Ohm and 20K Ohm, would also lead to 5V to 3.3v) but at a different current (Amps)… ?

And what about a voltage-divider with a resistor and a capacitor (see https://en.wikipedia.org/wiki/Voltage_divider, low-pass RC filter)?
What would be appropriate values for that solution for the resistor and capacitor?

Please be patient, electronics-beginner here trying to make sense of this…

Buy some of these, it's a simple hardware solution to your problem then.
https://www.amazon.co.uk/gp/product/B0148BLZGE/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1
I know you said you don't want to use a level converter but it's the simplest way around the problem.
You stated that you're an electronics beginner AS AM I, which is exactly why when I came up against the same problem i just spent the money.
It was only £3.99 for 5 of them and as far as I'm aware you should be able to buy single ones off amazon too, haven't searched but i'd have thought you'd be able to.
Or if you need to do it with resistors you can use this calculator here
http://www.ohmslawcalculator.com/voltage-divider-calculator

I actually already purchased those as that's surely the safest solution for starters. But in the process of figuring out the "magic component needed" the above questions arose. For the voltage divider, try your link enter 5v, 100Ohm, 200Ohm -> 3.3v... But if you enter 5v 1000Ohm, 2000Ohm you also have 3.3v... so there must be something "missing"... And the other part which worries me is the occasional 5v on the RX pin.

In the Arduino forums related to 5v to 3.3v we have this link here, http://forum.arduino.cc/index.php?topic=16846.0 someone uses 1K8 and 3K3, but here https://forum.arduino.cc/index.php?topic=22570.0 someone suggests using 270R and 470R and either of those end up close to 3.3... So what's the difference (it must be sth with current)... or could we just as well use 10M and 20M resistors and it really doesn't matter?

You can use something along the lines of this:

simulate this circuit – Schematic created using CircuitLab
When the 5V Rx is driven to 5V D1 protects the 3.3V Tx pin.
When the 5V Rx is driven to 0V R1 protects the 3.3V Tx pin from excessive current draw.
When the 5V Tx is driven to 5V D2 protects the 3.3V Rx pin and R2 pulls the pin to 3.3V.
When the 5V Tx is driven to 0V D2 pulls the 3.3V Rx pin to ~0.2 V
Resistor values are rough guidelines, lower values will put more strain on the parts and increase power draw but will also increase the maximum UART speed that will work reliably.

How can it be that RX is driven ... ? It's an 'R' port and as I suggest it stands for Receive. So wouldn't it be that the TX 3v3 port is driving the RX 5V so the RX 5V needs a pull-up? The whole thing does not make any sense this way (for me).

UART Rx ports idle high. This means there is a high probability the Rx pin will contain pullup to 5V. So not actively driven but a passive low strength pull to an excessive voltage. The protection diodes internal to the 3.3V part could probably cope with that, especially if there is a series resistor, but this reduces the strain on the 3.3v part.


text:
How do I choose proper diodes for a 74HC595 shift register with a wired OR connection?
I want to use a wired OR connection to connect some pins of the 74HC595 shift register to an Arduino Digital Input Pin. How do I choose proper diodes for this situation?

Maximum rated forward current has to be higher than whatever current a single pin of the 74HC595 produces.
The V_F forward voltage drop has to be as low as possible to make sure that a HIGH from the shift register has still a voltage high enough to result in a HIGH at the Arduino pin after passing through the diode.
Switching time has to be low enough to match the shift register's frequency.

So far, so good? What did I miss?
By the way, I haven't decided on the voltage for VCC, yet. Most likely, either 5 V or 3.3 V.

Why?? Your "requirements" are contradictory; RTL went out of vogue in the early 1960s precisely because it was slow (among other problems). You have not specified the frequency, but it is unlikely to be so high that you need to worry. This also is not an Arduino question?

@Milliways Thank you for your comment. :-) You seem really taken aback by my question. I'm just getting started with electronics and Arduino, so it's fairly probable that I'm approaching something the completely wrong way. With RTL, do you mean Register-transfer_level? I'm having problems understanding the correlation. Could you elaborate, please?

Concerning the relevance towards Arduino, I was thinking that the microcontroller on hand plays a part in choosing the proper diode. Despite the diode's voltage drop, I still have to reach the HIGH logic level for exactly this microcontroller. Isn't this dependent on which microcontroller is being used?

For this, almost any diode will work.  Searching, it turns out that the 1N4148 is a popular ubiquitous choice.  But don't go out of your way to obtain this particular diode.

Maximum rated forward current has to be higher than whatever current a
  single pin of the 74HC595 produces.

You should turn your thinking around.  Consider the nominal high voltage of the 74HC595, subtract the forward bias diode voltage drop (usually  0.7V for a silicon diode) and divide that by the resistor you pick.  That will be the current passing out of the 74HC595, through the diode and resistor.  Only a small amount of current will pass into the Arduino.  It should be negligible for most applications.  You should pick a resistor high enough to only allow milliamps of current to pass through this circuit.

The V_F forward voltage drop has to be as low as possible to make sure
  that a HIGH from the shift register has still a voltage high enough to
  result in a HIGH at the Arduino pin after passing through the diode.

Check the voltage margin allow for a logical high input to the Arduino (Atmel processor).  I think 3V - 0.7V = 2.3V is still considered a logical high.  However, if you think this is too close, then switch to the 5 volt Arduino where the 0.7 volt drop will make less difference.

Switching time has to be low enough to match the shift register's
  frequency.

I doubt this will be a problem.  That is, I doubt the CMOS logic will surpass the speed at which the diode can turn on / off.

Isn't there a very short period of time, when a diode in front of a former HIGH pin (now LOW) is still conducting and now allows for a short into this now LOW pin?

There might be.  But I believe it will not be noticeable relative to the time it takes for a CMOS device to charge up and start conducting or discharge and stop conducting.  Almost all logic chips use CMOS like technology these days.

Aah, I might be getting somewhere now. You're saying the shift register needs some time to switch from LOW to HIGH as well - and this time is enough time for the diode to switch to reverse biased?

That almost right.   A computer designer is interested in something called propagation delay.  Every "gate" (which is made up of transistors and in some cases diodes) contribute to the over all propagation delay.  There are dozens of gates in the shift register.  So there is significant delay between the shift register's clock input changing and the shift register's outputs changing.  The software program you write for the Arduino and hard ware you are designing will have to work in harmony to pull this off.  Adding diodes as you have done will add an insignificant amount of propagation delay.

After reading about propagation delay, this seems important to explain that the additional diode won't "affect the signal". (So thank you very much for introducing me to this technical term!) However, I feel terrible for suggesting this, because your answer helped me so much already - is it possible you misunderstood my follow-up question? There is a short period of time which the diode needs to switch from forward bias to reverse bias. Isn't it possible, that current flows through this still forward biased diode (during its switching time) into the (now LOW) output pin, and harm the IC?

You are now asking questions that are dealt with in introductory college level logic classes.  I can not imagine how including a Wired Or Gate using diodes and a properly selected resistor can cause damage.  Nor can I image how the diode switching bias delay is significant with respect to charging the capacitance load naturally found at the input of CMOS based logic chips and processors. As such you may ask why the circuit you added is not more common.  Power consumption.  When any of the shift register's outputs are high, a current flows through the resistor and that power is wasted as heat.

"Only a small amount of current will pass into the Arduino. " Yes, only 1uA max per the datasheet.

That is not the current that is wasting power.  The current that is wasting power occurs when any of the shift register output pins are pulled high.  Then the current flows through the diode connected to that pin and through the resistor to ground.  That said, you can reduce power loss by choosing a larger resistance.  But a larger resistance will allow more noise which can affect the input to the Arduino in unexpected ways.

I should add that the amount of current (likely a couple of mA) we are talking about here doesn't make all the much different in a plug in project.  But it starts to affect battery life a in portable project.


text:
Possible ArduinoJson bug on ESP8266?
I'm making a small IOT project using the ESP8266 in which I make 2 API calls:

api.openweathermap.org for weather data
api.timezonedb.com

The request logic is the same for both calls, the only difference being how I parse the response string. The first response is parsed fine, while the other isn't.

I print the String responses to Serial, they look fine.
Tried both Dynamic and Static buffers to no avail.
Making the request only to the second API, still not being parsed.
If I make a test and just make the response a String, char[] or char*, it parses fine.

Parsing logic [works]:
StaticJsonBuffer<1000> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(response);
float raw = root[String("main")][String("temp")].as<float>();

Parsing logic: [does not work]
StaticJsonBuffer<500> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(response);

String data = root[String("formatted")].as<String>();

The response object looks like this:
{
  "status": "OK",
  "message": "",
  "formatted": "2017-06-30 11:34:13"
}

Request logic:
String RequestAPI::performRequest(String url, char* host){
WiFiClient client;
if (!client.connect(host, port)) {
    lcd -> clearScreen();
    lcd -> drawText("Failed to connect to API", 0, 0, this -> randomUint16());
    delay(5000);
    return "";
}

char endOfHeaders[] = "\r\n\r\n";
client.print(
String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n"
);
// Skiping HTTP headers from the response
client.find(endOfHeaders);

unsigned long startTime = millis();
while(client.available() == 0){
    if(millis() - startTime > this -> timeout){
        lcd -> clearScreen();
        lcd -> drawText("API request failed", 0, 0, this -> randomUint16());
        delay(5000);
        return "";
    }
}

String response = "";
while(client.available()){
    response += client.readStringUntil('\r');
}
Serial.println(response);

return response;
}

Now I'm thinking, could the empty message be causing a bug? Or am I doing something wrong?

You say that the 2 responses are parsed differently, but only show one method.  Also the line  String data = root[String("formatted")].as<String>(); doesn't look right. From the examples I think it should be String data = String(root["formatted"]);

@CodeGorilla Updated answer with the working parser.

@CodeGorilla Your suggestion ends up with: 'String(ArduinoJson::JsonObjectSubscript<const char*>)' is ambiguous

Strange - I was just looking at the examples, https://github.com/bblanchon/ArduinoJson/blob/master/examples/JsonParserExample/JsonParserExample.ino, sorry I couldn't help.

very helpful, I'm working a similar problem. Any chance you could share your entire code? Especially more details on the section on handling the Get request timeout. unsigned long startTime = millis(); while(client.available() == 0){ if(millis() - startTime > this -> timeout){ lcd -> clearScreen(); lcd -> drawText("API request failed", 0, 0, this -> randomUint16()); delay(5000); return ""; } }

This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. You can also add a bounty to draw more attention to this question once you have enough reputation. - From Review

@micromet am planning to create a repo for this, don't have the time to refactor out my hardcoded API string and passwords. The timeout handling seems pretty self explanatory.

The issue was caused because of: https://en.wikipedia.org/wiki/Chunked_transfer_encoding
Was not obvious as the data printed to the serial looked completely fine. Fixed with the below code:
client.print(
  String("GET ") + url + " HTTP/1.0\r\n" +
  "Host: " + host + "\r\n" +
  "Connection: close\r\n\r\n"
);

Dunno why it worked for one API but not the other though.


text:
Synchronising LEDs
Say I have 3 LEDs. I want LED1 to blink 5 times. At its third blink, LED2 should start blinking as well, also 5 times. While LED2 is at its 3rd blink, LED3 should start blinking. How do I do this in Arduino?
Here's what I have.
int timeStep = 200; // delay time
int myPins[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; // array with Pins
int myPinsSize = sizeof(myPins) / sizeof(myPins[0]); // Length of my array
int counter = 0;

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  for (int i = 0; i < myPinsSize; i++) {
    pinMode(myPins[i], OUTPUT);
  }
}

// the loop function runs over and over again forever
void loop() {
  LEDsequence();
  if(counter >= 9) {
    counter = 0;
  } else {
    counter++;
  }
}

void LEDsequence() {
  if(counter < 5) {
    switchOn(0);
  }
  if(counter >= 2 && counter < 7) {
    switchOn(1);
  }
  if(counter >=4 && counter < 9) {
    switchOn(2);
  }
  delay(timeStep);
  switchAllOff();
}

void switchOn(int index) {
  digitalWrite(myPins[index], HIGH);
}

void switchOff(int index) {
 digitalWrite(myPins[index], LOW);
}

void switchAllOff() {
  for (int i = 0; i < myPinsSize; i++) {
    digitalWrite(myPins[i], LOW);
  }
}

Building on Michel's answer (this is a bit long to put in a comment):
Rather than using a 2 dimensional array or an array of strings (which is also a 2d array) it would be far more efficient to use a bitmask system.
const uint8_t TIME_PERIODS = 20;
const uint8_t NR_LEDS = 3;
const uint8_t ledStates[] = [1,0,1,0,3,0,3,0,7,0,6,0,6,0,4,0,4,0,4,0];

and then the loop becomes:
  for (int period = 0; period < TIME_PERIODS; period++)
  {
    for (int led = 0; led < NR_LEDS; led++)
    {
      switch(led, ledStates[period] & 1<<led ); // set the led on or off
    }
    delay(500); // 0.5 s
  }

How this works:
1<<led will be 0001 in binary for led=0, 0010 for led = 1, 0100 for led = 2.
So if ledStates[period] was 3 (0011 in binary) then ledStates[period] & 1<<led will be non-zero for leds 0 and 1 and zero for led 2. The way the switch function is written any non zero value turns the LED on, 0 turns it off.
Why do it this way? Mainly size. Memory is always important, this uses 1 byte per state rather than 3. It could even be expanded to up to 8 LEDs without increasing the amount of memory used.

Since you have 3 leds, make a 2 dimensional array, first index for the leds (3), second for the period in which you want to have the led on or off.
E.g.
const uint8_t NR_LEDS      = 3;
const uint8_t TIME_PERIODS = 20;

uint8_t period[NR_LEDS][TIME_PERIODS] = [
// Time  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17, 18, 19
        {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // Led 1
        {0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, // Led 2
        {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 }}; // Led 3

This means over 18 time periods, each state shows which led is on and off.
You can use HIGH or LOW, but that makes the lines too wide.
Now you can easily create a loop:
void loop()
{
  for (int period = 0; period  < TIME_PERIODS; period ++) // Time
  {
    for (int led = 0; led < NR_LEDS; led++)
    {
      switch(led, states[led, period ]); // set the led on or off
    }
    delay(1000); // 1 s
  }
}

void switch(uint8_t led, uint8_t state)
{
  digitalWrite(led, state == 0 ? LOW : HIGH);
}

So instead of switchOn and switchOff, use the switch and set it on or off by a parameter.
Also, this way it is very easy to change the schema (you can always visually see it in code). If you want longer schemes you can change the array into strings, like:
char* period[NR_LEDS] = [
 // Time 0         10
 // Time 012345678901234567890
        "10101010100000000000", // LED 1
        "00001010101010000000", // LED 2
        "00000000101010101010", // LED 3

And check the index within the correct string and check for '0' and '1' instead of 0 and 1.
Since blinking is done for all leds 'in sync' (meaning during blinking leds change at the same time), you can also define a '1' as blink and '0' as off.
Than change:
char* period[NR_LEDS] = [
 // Time 0         10
 // Time 012345678901234567890
        "10101010100000000000", // LED 1
        "00001010101010000000", // LED 2
        "00000000101010101010", // LED 3

to
char* period[NR_LEDS] = [
 // Time 0         10
 // Time 012345678901234567890
        "111110000", // LED 1
        "001111100", // LED 2
        "000011111", // LED 3

And change the loop in
void loop()
{
  for (int period = 0; period < TIME_PERIODS; period ++) // Time
  {
    for (int led = 0; led < NR_LEDS; led++)
    {
      switch(led, states[led, period]); // set the led on or off
    }
    delay(500); // 0.5 s

    for (int led = 0; led < NR_LEDS; led++)
    {
       switch(led, '0');
    }
    delay(500); // 0.5 s
  }
}

(use a constant for 0.5 s delay) and optionally create a function for the two small for loops above)

How do I do this in Arduino? Here's what I have.

easy:
1) write a routine that blink a pattern on a given pin;
something like this would work
void myblinking(uint8_t pin, uint8_t *ptrn, uint8_t steps) {
  uint8_t index;

  pinMode(pin, OUTPUT);  //set pin as output
  for (index=0; index<steps; index++) {
    digitalWrite(pin, !digitalRead(pin)); delay(ptrn[index]); //flip pin, waste sometime
  }
}

then all you need is to call that routine, like this:
myblink(LED_PIN0, led_ptrn0, 10); //blink led_pin0, per led_ptrn0, for 10 steps
  myblink(LED_PIN1, led_ptrn1, 20); //blink led_pin1, per led_ptrn1, for 20 steps
  ...

That would only blink 1 LED at a time, it wouldn't allow you to run 2 different patterns on two different leds at the same time.


text:
Arduino Mega 2560 with SIM808 module - Incomplete SMS response
I have this code to read a SMS:
String read_SMS(int index)
{
  Serial.println("--START READ SMS POSITION" + String(index) + "--");
  delay(400);
  sendATcommand("AT+CMGF=1", "OK", 1000);    // sets the SMS mode to text
  delay(2000);
  String tmp;
  tmp = readATcommand("AT+CMGR=1", 4000);
  Serial.println("Content: " + tmp);
  Serial.println("--END READ SMS POSITION" + String(index) + "--");
}

String readATcommand(String ATcommand, unsigned int timeout)
{
  char response[800];
  unsigned long previous;
  memset(response, '\0', 800);    // Initialice the string

  int x = 0;

  GSMSerial.println(ATcommand);
  delay(3000);
  previous = millis();
  do {
    if (GSMSerial.available() > 0) {
      response[x] = GSMSerial.read();
      x++;
    }
  } while ((millis() - previous) < timeout);   // Waits for the asnwer with time out

  return (String) response;
}

// sending AT commands to the Sim808 module
int8_t sendATcommand(String ATcommand, char* expected_answer, unsigned int timeout) {

  uint8_t x = 0, answer = 0;
  char response[200];
  unsigned long previous;

  memset(response, '\0', 200);    // Initialice the string

  delay(100);

  // Clean the input buffer
  while (GSMSerial.available() > 0 ) GSMSerial.read();

  if (ATcommand[0] != '\0') {
    // Send the AT command
    GSMSerial.println(ATcommand);
    //Serial.print(F("AT Command: "));
    //Serial.println(ATcommand);
  }

  // Waiting for the answer
  x = 0;
  previous = millis();

  do {

    // if there are data in the UART input buffer, reads it and checks for the asnwer
    if (GSMSerial.available() > 0) {

      response[x] = GSMSerial.read();
      x++;
      // check if the desired answer (OK) is in the response of the module
      if (strstr(response, expected_answer) != NULL) {
        answer = 1;
      }
    }

  } while ((answer == 0) && ((millis() - previous) < timeout));   // Waits for the asnwer with time out

  //Serial.println(F("START RESPONSE:"));
  //Serial.println(response);
  //Serial.println(F("END RESPONSE"));
  //if (answer == 0) {
  //  Serial.println("Could not get the expected answer!");
  //}
  //else {
  //  Serial.println("Found expected answer!");
  //}

  return answer;
}

What can be wrong in the readATcommand function as it replies with an incomplete response:
--START READ SMS POSITION1--
Content:
AT+CMGR=1

+CMGR: "REC READ","+407245402XX","","17/06/29,10:
--END READ SMS POSITION1--

But, when I run it from a terminal, the AT+CMGR=1 replies with:
AT+CMGR=1

+CMGR: "REC READ","+40724540234","","17/06/29,10:03:06+12"
Salut

OK

As you can see the message body is not there + the time of the SMS is also incomplete.
Thank you!

What is GSMSerial?

@Majenko #define GSMSerial Serial3

My guess is that your gratuitous use of the delay() function is making the serial buffer overflow. There is never any call to use delay() when reading from serial. The AT protocol has proper handshaking signals that you should use, such as looking for "OK". There is no need to delay() while waiting for them, that's just silly.

Works now. At first I got to reply so I put the delays. After the delays I got the partial messages. Now without any delays .. I get the full messages. Thanks!

Don't delay.
In the three seconds that you wait between sending the AT command and reading the response the entire response has arrived and been placed in the serial RX buffer - which has overflowed because there's more than 64 bytes in the response. So you lose data.
You should never use delay() when reading from serial, it's dangerous (as you see).
Instead you should be just immediately reading until you see the correct response from the command you sent - which will either be "OK" or "ERROR". Everything before that is the content of the response to your command.


text:
Recording and playback sound
I'm working in an art project, is some kind of loop between contact microphones and walkie talkies. I want to create some kind of noisy feedback.
I'm putting one walkie-talkie inside of a bottle, and in front of the speaker/microphone from the walkie I want to put another contact microphone attached to an Arduino, and record the sounds of the walkie talkie and played with some delay in some buzzer in front of another contact microphone attached to an amp with three speakers. To sum up, I have like 3 parts linked between them, the first one the walkie, the second one with an Arduino and the third one a simple mic whith an amp and three speakers.
Only the second part will be working with the Arduino and I want it to record sound and play it simultaneously with some delay.
I worked with a friend with some servo motors and music shields and I've been doing some research. I found 3 very interesting projects one is this, that it's practically what I want to do Space Replaybut there's so little information about it, and the other two are Arduino Audio Input and Arduino Audio Output
So, my questions are:

If I use a music shield I don't need a DAC or/and an amp? or only an amp if my speakers are too loud?
In the project Space Replay they only use this music shield so with only one music shield I can record and play music simultaneously? or I need two music shields?
That Adafruit Wave Shield is only for Arduino uno, but it will be better or easier to work with DUE or Arduino Mega and another music shields or making my own circuits like in the instructables Arduino Audio Input and Output?

I don't care too much about the quality of the audio, as I said the purpose is make some noise. The only thing is I want to create some kind of echo, or some kind of cannon, between the first sound of the walkie and the others pick up sounds.
Any other comment or advice will be much appreciated and welcomed.
Thanks

Try using this shield from Adafruit. I believe it can record and play audio, and they have versions with and without amps.
I do not know about near-simultaneous playback, so read up a bit before buying.

@user173724 Hello, thank you for the answer. I found an example project with the adafruit waveshield, which is realtime voice changer more information here, also  in the waveRP library includes a folder with how to connect a mic to the wave shield, so I'm working with the wave shield but I'll take a look to the Music Maker shield.


text:
Controlling an MCP41HV31 Digital Potentiometer
I need to control a 10kOhm digital potentiometer in rheostat mode in 256 steps. I found an Arduino tutorial, which works with an MCP41010 (I added a viper resistance according to the datasheet). This works fine - I can send values from 0 to 255 to the CS pin an the resistance between output pin A and B changes from 0 to 10kOhm.
The problem is, that my application requires 16V to go through this resistance, which the MCP41010 can't handle.
I tried to go with a MCP41HVX1 high voltage digital potentiometer (which I soldered on a TSSOP-to-DIP Breakout board) and assumed it would work the same way. Turns out it doesn't... My connections are:
Arduino nano -> MCP41HVX1

10 -> CS
11 -> SDI
13 -> SCK
5V -> VL
GND -> DGND

With the MCP41010 I connect a 115Ohm viper resistor between output pin A and wiper terminal and measure resistance between output pin A and B (pink connectors). I noticed, that the MCP41HVX1 has a different description for the rheostat modus but I can't get that to work either.
This is my circuit that works with the MCP41010

And here is the respective code (which sets the MCP41010 to 255 i.e. 10kOhm)

#include <SPI.h>
byte address = 0x11;
int CS= 10;

void setup()
{
  pinMode (CS, OUTPUT);
  SPI.begin();
}

void loop()
{
  digitalPotWrite(255, CS);

}

int digitalPotWrite(int value, char Port)
{
  digitalWrite(Port, LOW);
  SPI.transfer(address);
  SPI.transfer(value);
  digitalWrite(Port, HIGH);
}

Has anyone ever done this or has a clue what's going on?

I was not allow to post all necessary links in the original post. Here is the tutorial for the MCP41010 and it's datasheet.

Well, for a start your wiring is wrong. Look at the pinout of the HV version. You're not connecting to the pot pins with your pot wires (or not all of them) and you aren't providing the proper V+ and V- voltages.

Pin 14 should go to +16V, pin 10 to GND, and 11-13 are your pot pins.

Sorry, I got it wrong in the graphic, of course the outputs are pin 11 and 13. Connecting pin 14 to +16V didn't change much. Right now I'm not even trying to run 16V through the resistance but measure it with an oscilloscope.

I realize that this thread is old. I am providing an answer for anyone else who may end up here like I did a while back looking to solve this.
I have created an Arduino library on Github (https://github.com/gregsrabian/MCP41HVX1) which allows for control of this family of chips. The README.md within the github project documents all of the APIs and also provides the wiring diagram. There are also example sketches included.
I have created an article on Instructables (https://www.instructables.com/id/MCP41HVX1-Digital-Potentiometer-for-Arduino/) that provides a step by step on how to control this family of chips. There is also an explanation on how to solder the TSSOP chip.

One thing I discovered, after coming back to the internet multiple times for clues, is that that SHDN pin on the MCP41HVX1 has to be tied HIGH.
If not, you can try incrementing, decrementing, or writing values to your heart's content and the thing is not going to budge.
I tied SHDN to the VL level via a 10k resistor and I can write and increment without problems.
I think it should have been flagged in the datasheet though, in the Pinout Description table.

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


text:
What is an ICSP pin?
What is an ICSP pin? I have read that it is an AVR and a tiny programming header for the Arduino, but what is an AVR and what does an ICSP pin do?

When would you use the ISPC Header?

@DavidAbela ISP or ICSP (same meaning) is used mainly when developing complex applications onto the ATMega328 (where the Arduino IDE doesn't suffice: https://www.instructables.com/id/Using-an-In-System-Programmer). Since most users aren't creating complex projects, very few users need it.

ICSP stands for In Circuit Serial Programming, which represents one of the several methods available for programming Arduino boards.  Ordinarily, an Arduino bootloader program is used to program an Arduino board, but if the bootloader is missing or damaged, ICSP can be used instead.  ICSP can be used to restore a missing or damaged bootloader.
A typical Arduino ICSP header has six pins, arranged 2x3.  The article Connecting the Programmer:
In-Circuit Serial Programming (ICSP) at Sparkfun describes some of the functions of ICSP pins, which include MISO, MOSI, SCK, V+, Ground, and Reset.
Each ICSP pin usually is cross-connected to another Arduino pin with the same name or function.  For example, MISO on an Uno or Nano's ICSP header is connected to MISO / digital pin 12; MOSI on the ISCP header is connected to MOSI / digital pin 11; and so forth.  Note, MISO, MOSI, and SCK pins taken together make up most of an SPI interface.
Several Arduinos, including the Uno, have two ICSP headers.  One of them is for use with the ATmega328 (or similar), and the other for use with the ATmega16U2 (or similar) chip that implements USB. When present, this  allows reprogramming the USB chip.

AVR refers to the instruction set architecture used in a family of Atmel microcontrollers.  Several Arduinos  – Mega, Uno, Nano, Micro – use AVR chips.  Others, like the Zero and Due, instead use ATSAM3 chips, with an ARM instruction set architecture.


text:
Two Arduinos get out of sync after a few seconds
I built a small PCB that has some LEDs (bare NeoPixel 5050) and an IR receiver on it. The microcontroller is an ATtiny85, and the PCB is powered by a LiPoly battery (3.7V). The circuit normally stays in ULP sleep mode until a pin change interrupt wakes the circuit. The pin change interrupt is tied to the IR receiver so when the receiver gets a signal from a remote (38kHz modulated IR burst) a lighting sequence is triggered. I have multiple of these PCBs running the exact same code (shown below). When the PCBs receive an IR signal they all start at the same time, but then after a few seconds they start to drift apart. The lighting needs to be synchronized. What is the reason for this drift and how can I eliminate it? Is it due to different battery voltages? That would be the only physical difference between any two PCBs. Thanks for your help.
#define IR_PIN      4
#define LIGHT_PIN   0
#define DELAY_TIME  200

#include <Adafruit_NeoPixel.h>
#define NUM_PIXELS  2
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_PIXELS, LIGHT_PIN, NEO_GRB + NEO_KHZ800);

#include "avr/interrupt.h"
#include "avr/sleep.h"

void setup() {
  pinMode(IR_PIN, INPUT);
  strip.begin();
  pixelsOff();
}

void loop() {
  sleep();

  for (int i = 0; i < 5; i++) {
    pixelsOnRed();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
    pixelsOnGreen();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
  }

  for (int i = 0; i < 5; i++) {
    pixelsOnBlue();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
    pixelsOnRed();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
  }

  for (int i = 0; i < 5; i++) {
    pixelsOnGreen();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
    pixelsOnRed();
    delay(DELAY_TIME);
    pixelsOff();
    delay(DELAY_TIME);
  }
}

void pixelsOff() {
  strip.setPixelColor(0, 0, 0, 0);
  strip.setPixelColor(1, 0, 0, 0);
  strip.show();
}

void pixelsOnRed() {
  strip.setPixelColor(0, 255, 0, 0);
  strip.setPixelColor(1, 255, 0, 0);
  strip.show();
}

void pixelsOnGreen() {
  strip.setPixelColor(0, 0, 255, 0);
  strip.setPixelColor(1, 0, 255, 0);
  strip.show();
}

void pixelsOnBlue() {
  strip.setPixelColor(0, 0, 0, 255);
  strip.setPixelColor(1, 0, 0, 255);
  strip.show();
}

ISR(PCINT0_vect)
{
    //This is not needed for the current sketch
}

void sleep() {
    GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
    PCMSK |= _BV(PCINT4);                   // Use PB3 as interrupt pin
    ADCSRA &= ~_BV(ADEN);                   // ADC off
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

    sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
    sei();                                  // Enable interrupts
    sleep_cpu();                            // sleep

    cli();                                  // Disable interrupts
    PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
    sleep_disable();                        // Clear SE bit
    ADCSRA |= _BV(ADEN);                    // ADC on

    sei();                                  // Enable interrupts
}

What is your clock source?

@Majenko internal 8MHz oscillator

That's about the worse clock source you can get.

@EdgarBonet in your opinion is it bad enough to produce the drift I experienced?

It is very likely.

What is the reason for this drift and how can I eliminate it?

two solutions:
1) try using crystal oscillators;
2) try driving on arduino with the other arduino's clock output.

Assuming internal RC oscillator:
In the datasheet:

By default, the Internal RC Oscillator provides an approximate 8.0 MHz clock. Though voltage and temperature
  dependent, this clock can be very accurately calibrated by the user. See “Calibrated Internal RC Oscillator Accuracy”
  on page 164 and “Internal Oscillator Speed” on page 192 for more details. The device is shipped with the
  CKDIV8 Fuse programmed. See “System Clock Prescaler” on page 31 for more details

And page 192 shows a graph of frequency vs voltage.
On 164 it says:

It is possible to manually calibrate the internal oscillator to be more accurate than default factory calibration. Please
  note that the oscillator frequency depends on temperature and voltage. Voltage and temperature characteristics
  can be found in Figure 22-40 on page 193 and Figure 22-41 on page 193.

So yes, conclusive evidence there that the voltage will affect the frequency.

Pretty sure the Arduino uses a 16mhz crystal rather than the internal oscillator.  http://dailylearningnotes.blogspot.com/2010/03/arduino-components-crystal-oscillator.html

@bigjosh "The" Arduino....? READ THE QUESTION: "I built a small PCB that has some LEDs (bare NeoPixel 5050) and an IR receiver on it. The microcontroller is an ATtiny85"... That's not an Uno (ONE of the MANY forms of Arduino)

Thanks, this is insightful. I didn't know that voltage and temperature could affect the oscillator. The only concern I have is that both batteries were charged up to their full 4.2v before use and both PCBs are right next to each other. Maybe small differences in both can produce cascading drift like I saw. I'll take a look at the calibration

@Majenko So true! Comment respectfully withdrawn! :)

It may be possible to characterize the drift between the two and compensate. To a 1st aprox, you might just be able to let them both run for a while, then measure the speed difference and then slow down the faster one to cancel out the difference. To a 2nd aprox, you could characterize the voltage  dependency on each adn then measure and compensate in real-time. But agree with others- easiest probably to use XTAL or a way of syncing (wire, IR LED, etc).

Other answers have noted that the internal RC oscillator's frequency is voltage and temperature dependent.  If you have good control over voltage and temperature, consider manually or automatically calibrating the clocks of your several ATtiny85's.
Absent that control, consider adding crystals or ceramic resonators to your circuits, or set up a synchronization protocol using IR.  For example, if your IR transmitter is programmable, have it send a synchronization character as often as necessary to adequately synchronize the lights.  If your IR transmitter is not programmable, add an IR LED and driver to one or more of your ATtiny85's, and send synchronization characters at regular intervals.


text:
HC-05 emit data without pairing
Is it possible to emit data from an arduino connected to a hc-05 Bluetooth module without pairing it to another device?
i.e. imagine that I want to send a Bluetooth signal as if it was a information spot. Then whoever who gets the signal can read it.

No. The HC-05 has to be paired. It runs on Bluetooth 2.x which requires pairing.  What you want is BLE (or Bluetooth 4.x) which has various "beacon" facilities.


text:
String to persistent memory (EEPROM?)
I am creating a server node that I want to be able to save the wifi SSID and the password into persistent memory so that when it starts ups it can connect to the network. I have looked for several hours and found just a few bits of information. One bit I found here http://playground.arduino.cc/Code/EEPROMWriteAnything
#include <EEPROM.h>
#include <Arduino.h>  // for type definitions

template <class T> int EEPROM_writeAnything(int ee, const T& value) {
    const byte* p = (const byte*)(const void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          EEPROM.write(ee++, *p++);
    return i;
}

template <class T> int EEPROM_readAnything(int ee, T& value) {
    byte* p = (byte*)(void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          *p++ = EEPROM.read(ee++);
    return i;
}

This code will not store String values to the EEPROM. So as I thought I would ask for advice from the Stack Exchange geniuses.
Thanks!

I dont think Arduino.h has a string typedef. perhaps you can use a character array instead.

String is a type that exists in C++, so it doesn't need to exist in Arduino.h. Arduino uses C++, not C.

EEPROM library has two functions put and get , which can help you store character array of any size, not exceeding the size of internal EEPROM size of Arduino. Please see the examples provided in the link above.
Here is a sample code to get you going.
int address = 10;
char arrayToStore[20];                    // Must be greater than the length of string.
String testString = "hello there";

testString.toCharArray(arrayToStore, testString.length()+1);  // Convert string to array.

EEPROM.put(address, arrayToStore);                 // To store data
EEPROM.get(address, arrayToStore);                 // To read data

So this kept bugging me, if I want to get a value from the address how come I have to put a value that I want to store there as well?  What if I want to just read the values there?

I didn't get you, buddy. This is just an example sketch to show you how to store and read data in EEPROM locations. You have to make your own sketch for your requirement based upon this.

This is how I store my configuration data: I have a function to store the configuration, which will execute only occasionally whenever there is a config change. This mode is controlled by a jumper connection on my PCB. When the program restarts in regular execution mode, it just keeps reading the config data. The behavior is controlled by a check flag in  the startup code.


text:
Serial Communication between ESP8266 and Arduino Uno
I want to send data from arduino to ESP8266. I have done all the RX and TX connections.
The problem is that data is not sent every second, it stops after a single byte. When I remove the arduino cable then data is read.
My Arduino Code :
void setup() {
    Serial.begin(9600);
}

void loop() {

    Serial.write("50");
    delay(1000);
}

My ESP8266 Code :
void setup() {

Serial.begin(9600);

  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

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

    delay(500);
  }
  Serial.println("Connected !");

}

void loop() {

 Serial.print(Serial.readString());

}

Since you are  Arduino Uno, it has only one Serial. This Serial can be used to transmit data in USART mode to another Serial Device as well as see any Debug data in the Serial terminal.
However, both the functionality can not be used simultaneously. The Tx Rx pair of Arduino can be connected to one pair of other device i.e. either to the computer via the cable or to the Tx Rx of ESP8266.
But if you really need to plug in the Uno to the computer and send data to ESP8266 simultaneously, then you have to use SoftwareSerial library to convert any digital pin to Tx Rx pin, and connect them to ESP8266 for transmitting data.

As explained by goddland_16. Using Software Serial library will solve the issue. Code is given below. By Initializing other digital pin as communication pin, Interupption between Tx and Rx and to ESP8266 is seperated.
Arduino UNO / Nano Code :
/*
 * bismillah hir rahman nir raheem
 * UNO/Nano = Pin 7 & Pin 8
 * Note: Uno and ESP8266 cross connection
 */

#include <SoftwareSerial.h>

SoftwareSerial ArduinoUno(7,8);
String f;

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

void loop() {
    float i = (random(100) + 1);
    float j = (random(100) + 1);

    f = String('H') + String(i) + String('T') + String(j);
    ArduinoUno.println(f);
    delay(2000);
}

ESP8266 Code :
/*
 * bismillah hir rahman nir raheem
 * ESP8266 = Pin D7 & Pin D8
 * Note: Uno and ESP8266 cross connection
 */

#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>

SoftwareSerial NodeMCU(D7,D8);

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

    pinMode(D7,INPUT);
    pinMode(D8,OUTPUT);
}

void loop() {
    String content = "";
    char character;

    while (NodeMCU.available()) {
       character = NodeMCU.read();
       content.concat(character);
    }

    if (content != "") {
        Serial.println(content);
    }

    Serial.println("Temperature");
    Serial.println(content.substring(1, 6));
    Serial.println("Humidity");
    Serial.println(content.substring(7, 12));
    delay(2000);
}

Hi and welcome to the Arduino Stack Exchange. Please improve your answer by explaining to everyone what your code does and how it fixes the problem.


text:
error: expected unqualified-id before '.' token
I am working on a library to display custom text on a TFT screen and I came up with this error while making an example:
EsploraHelloWorld:31: error: expected unqualified-id before '.' token
   TFTCharPlus.drawChar(chars[5, 0], chars[5, 1], chars[5, 2], chars[5, 3], chars[5, 3], 120, 0, 255, 255, 255, 4, EsploraTFT);
               ^

Heres my code:
#include <Esplora.h>
#include <SPI.h>
#include <TFT.h>
#include <TFTCharPlus.h>

// A table for all of the characters
const char chars[6][5] = {
  {0xf8, 0x20, 0xf8, 0x1f, 0x15},
  {0xf8, 0x08, 0x08, 0x1f, 0x01},
  {0x70, 0x88, 0x70, 0x00, 0x00},
  {0xc0, 0x20, 0xc6, 0x29, 0xc6},
  {0xf0, 0x40, 0x80, 0x5f, 0x01},
  {0xf0, 0x90, 0x60, 0x00, 0x3d}
};

TFTCharPlus TFTCharPlus();

void setup() {
  // initialize the screen
  EsploraTFT.begin();

  // make the background black
  EsploraTFT.background(0,0,0);

  // print the characters
  TFTCharPlus.drawChar(chars[0, 0], chars[0, 1], chars[0, 2], chars[0, 3], chars[0, 3], 0, 0, 255, 255, 255, 4, EsploraTFT);
  TFTCharPlus.drawChar(chars[1, 0], chars[1, 1], chars[1, 2], chars[1, 3], chars[1, 3], 24, 0, 255, 255, 255, 4, EsploraTFT);
  TFTCharPlus.drawChar(chars[2, 0], chars[2, 1], chars[2, 2], chars[2, 3], chars[2, 3], 48, 0, 255, 255, 255, 4, EsploraTFT);
  TFTCharPlus.drawChar(chars[3, 0], chars[3, 1], chars[3, 2], chars[3, 3], chars[3, 3], 72, 0, 255, 255, 255, 4, EsploraTFT);
  TFTCharPlus.drawChar(chars[4, 0], chars[4, 1], chars[4, 2], chars[4, 3], chars[4, 3], 96, 0, 255, 255, 255, 4, EsploraTFT);
  TFTCharPlus.drawChar(chars[5, 0], chars[5, 1], chars[5, 2], chars[5, 3], chars[5, 3], 120, 0, 255, 255, 255, 4, EsploraTFT);
}

void loop() {
  // not necessary
}

And for reference, here is the drawChar() function:
void TFTCharPlus::drawChar(byte data1, byte data2, byte data3, byte data4, byte data5, uint8_t xpos, uint8_t ypos, uint8_t colR, uint8_t colG, uint8_t colB, uint8_t size, TFT tft) {
  tft.stroke(colR, colG, colB);
  tft.fill(colR, colG, colB);
  byte data[5] = {data1, data2, data3, data4, data5};
  for (uint8_t x = 0; x < 5; x++) {
    for (uint8_t y = 0; y < 8; y++) {
      if (bitRead(data[x], 7 - y)) {
        tft.rect(x*size+xpos, y*size+ypos, size, size);
      }
    }
  }
}

How can I fix the error?
BTW: The error is not in the library, everything is done correctly
EDIT: I realized that the error occurs on all six drawChar() lines, and After fixing a small error, I also got this:
request for member 'drawChar' in 'TFTCharPlus', which is of non-class type 'TFTCharPlus()'

what does line 30 and 31 say?

What I presume TFTCharPlus is a class, and class can not call the function. You have to define an object of the class and that will call the function.

It appears that you are calling the "description" of the library method (function).  What is necessary is to use the "description" to create a "working copy" of the library method.  Then call the "working copy".
In the above statement, the "description" is the Class, "to create" means to instantiate and "working copy" is referred to as the Object.
In the Arduino Serial Port Example, you will find the following line:
SoftwareSerial mySerial(10, 11); // RX, TX

Here, the Class "SoftwareSerial" is used to instantiate the Object "mySerial".  Later in the code calls are made to the "write" method with in that object:
mySerial.write(Serial.read());

In this line:
TFTCharPlus TFTCharPlus();

you've given your TFT object the same name as its class, making that name ambiguous. If you change the name of the object to, e.g.:
TFTCharPlus TFTobject();

as well as changing all of your references to it (TFTobject.drawChar(...)), it should fix the issue.


text:
Power a Raspberry Pi 3 from an Arduino Uno
I would like to power my Raspberry Pi 3B using an Arduino Uno.
I have been able to do this by connecting the 5v on the Arduino to the 5 V on the Pi and connecting the GND to GND, and the Pi turns on. But I get a constant under voltage sign.
How can I get the Arduino to output the right amount of power (5 V and 2.5 A)?

Neither Arduino nor RPi can produce electricity, so "powering one using the other" isn't representative of what's happening. You're powering both using whatever power supply you have, and the evidence is that it's not enough.

You can't.
The on-board regulator of the Uno, the NCP1117, is only able to supply up to 1A before starting to dropout voltage (hence your undervoltage warning).
Even worse, because the NCP1117 lacks a proper heatsink, it will probably start dropping out voltage before reaching 1A, due to its internal thermal shutdown protection.

If you are using PC USB, your total current cap is <500mA. Arduino + Pi + accesories is exceed this cap.
Use an adapter for Arduino. Ardiuno will suck up some current and rest can flow to Pi or whatever else is there.
Arduino has a linear voltage regulator. Try not to use >5v adapters. Voltage regulator will generate more heat as more current pass.

Could you give me an example of the type of adaptor needed?

This 5V adapter would be good. Connect the output to both 5V pins in parallel.  https://www.mpja.com/5-Volt-DC-Plug-Power-Supply-4A-Regulated/productinfo/18520+PS/

If you reverse which board gets the power adapter you should be able successfully power them both from a single 5V 2.5A power supply.
Connect the power adapter to the Raspberry Pi3 and power the Arduino from the Pi's 5V pin.  The Uno should only draw about 200mA @ 5V from the Pi (depending on everything else you have connected).


text:
Trying to communicate with an ESP8266
G'day guys, I'm trying to get an ESP8266 to work with an Arduino Uno.Here is the wiring.
When I go to the serial monitor (115200 baud) and type: AT, there is not response from the ESP8266.Is there something that I am missing?I also have a servo motor connected, it works fine.

include "Arduino.h"
include "ESP8266.h"
include "dweet.h"
include "Servo.h"

define ESP8266_PIN_RX 10
define ESP8266_PIN_TX 11
define SERVO9G_PIN_SIG 2

const int servo9gRestPosition   = 20;
const int servo9gTargetPosition = 150;
const char *SSID     = "Wireless Network";
const char *PASSWORD = "wireless_password";

ESP8266 wifi(ESP8266_PIN_RX,ESP8266_PIN_TX);
Servo servo9g;

const int timeout = 10000;
char menuOption = 0;
long time0;

void setup()
{
   Serial.begin(9600);
   while (!Serial); //await connection.
   Serial.println("start");

   wifi.init(SSID, PASSWORD);
   servo9g.attach(SERVO9G_PIN_SIG);
   servo9g.write(servo9gRestPosition);
   delay(100);
   servo9g.detach();

}

void loop()
{
   servo9g.attach(SERVO9G_PIN_SIG);
   servo9g.write(servo9gTargetPosition);
   delay(500);
   servo9g.write(servo9gRestPosition);
   delay(500);
   servo9g.detach();
}

I'm using the ESP8266 Library.When trying to connect it just says Initializing device...

Arduino Uno is 5V; ESP8266 is 3.3V. I have tried that combination without level shifters and it doesn't seems to work. Currently I'm using nodeMCU with a Pro Mini, both 3.3V, communicating over I2C. You have two problems here: 1) Communication between Arduino and ESP8266; 2) Communication between ESP8266 and WiFi. Now, nodeMCU is a much capable board than Arduino if you don't need so many I/O pins. Better you discard the Arduino and keep the ESP8266.

"115200baud" and Serial.begin(9600);. Something doesn't match. Also powering a motor from an Arduino is never a good idea.

G'day mate, I have managed to flash the firmware with what I hope is the latest, I did the AT command and it said Ok, however when I did the command that allows you to see wireless networks, it says error. Also how do you reckon I hook the motor up? I read that the motor is 5v so i would have thought that it would be ok?

@user1234433222 thats another question

Unless you have some project constraints which make it mandatory to use naked ESP8266, why not use a NodeMCU to communicate with the Arduino in a master/slave relation over I2C?

#include <Wire.h>
#define I2CAddressESPWifi 8

in setup()
Wire.begin(D1,D2); // SCL D1 SDA D2

then call from anywhere inside your loop() call this function
char readSlave(int x) { // send current time
  String xY = String(x);
  char c;
  int charArrayLength = xY.length()+1;
  char bufferChar[charArrayLength];
  Wire.beginTransmission(8);
  xY.toCharArray(bufferChar, charArrayLength);
  Wire.write(bufferChar);
  Wire.endTransmission();
  delay(10);
  Serial.print("wire sent: [");
  Serial.print(x);
  delay(50);//Wait for Slave to calculate response.
  int counter = 0;
  char buffMe[32];
  int bytesIn = Wire.requestFrom(8,32);
  while (Wire.available()) {
    delay(2);
    buffMe[counter] = Wire.read();
    /*
    c = Wire.read();
    Serial.print(c);
    */
    counter++;
  }
  delay(10);
  Wire.endTransmission();
  delay(500);
  Serial.print("] bytesIn: [");
  Serial.print(bytesIn);
  Serial.print("] buffMe: [");
  Serial.print(buffMe);
  Serial.print("]");
  return buffMe;
}

and your arduino will be waiting (setup)
Serial.begin(9600);
// slave listens for call from master NodeMCU
Wire.begin(I2CAddressESPWifi);  // predefined as `8` or whatever address you choose
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);

and at the end of your code
void receiveEvent(int howMany) {
  if (howMany) {
    Serial.print("bytes[");
    Serial.print(howMany);
    Serial.print("] Received[");
    char charIn[howMany];
    int counter = 0;
    while (Wire.available()) {
      char c = Wire.read();
      charIn[counter] = c;
      //Serial.print(c);
      counter++;
    }
    delay(10);
    //do something with command from master
  }
}
void requestEvent() {
  char bufferChar[20] = "slave answer string";  // automatically null terminated extra character at end
  Serial.println(bufferChar);
  Wire.write(bufferChar);
}

thank you, I will purchase one and see how I go :)


text:
Repeatedly checking multiple "if" statements
This code is part of a long code for a robot that is both obstacle-avoiding and remote control. I am trying to get the code to check both "if" statements when the code number FF807F is received from an IR remote. When the code number is received
the program checks both "if" statements and carries out the one that is true. I want the program, once it has finished carrying out the true "if statement, to check both "if" statements again.
void loop () {
if (My_Decoder.value==0xFF807F){
 if (cm<6)
 {
  motor_stop();
  digitalWrite(backlights, HIGH);
  delay(2000);
  motor_backward();
  digitalWrite(backlights, HIGH);
  Serial.println("backward");
  delay(2000);
  motor_stop();
  digitalWrite(backlights, HIGH);
  delay(900);
  motor_right();
  digitalWrite(backlights, LOW);
  Serial.println("right");
  delay(1000);
}
if (cm>6)
 {
  motor_forward();
  digitalWrite(backlights, LOW);
  Serial.println("forward");
}
}
}

What changes My_Decoder.value? If cm is exactly 6  you want to do nothing, is that right?

I am going to assume you don't want to include cm == 6 which is why you have both cases. I would consider using a while loop instead of a singular 'if' statement in order to continuously check if those buttons are being pressed or not (while (cm<6){do this stuff}). Otherwise, it will check once and never check again.
Instead it will jump down to the next 'if' statement, it will fail and then jump to the top of the loop where it will check for the code 0xFF807F. Let me know how it goes!

Your are missing the case when "cm == 6".
You don't need to do two "if"; one "if-else" is enough because is either one or the other.
You don't have/need to check twice; "cm" doesn't change inside the "if". But i you want, use functions:
void loop () {
  if (My_Decoder.value == 0xFF807F) {
    doSomething();
    doSomething();
  }
}

void doSomething() {
  if (cm < 6) {
    motor_stop();
    digitalWrite(backlights, HIGH);
    // ...
    delay(1000);
  } else {
    motor_forward();
    digitalWrite(backlights, LOW);
    Serial.println("forward");
  }
}

The above code is working, however I want it to repeat the "void doSomething();" function until another button is pressed. When I press the remote button it will only carry out the function once.

if (My_Decoder.value == 0xFF807F) {
if (cm<6)

Are you wanting both "ifs" to occur? Maybe a bitwise operator like logical AND (&)?

& only makes sense if the bits are related to each other--a logical && would be used here; value == 0xFF807F && cm < 6.

This looks like a good use for a State Machine.
It would look something like this:
typedef enum State
{
  STATE_IDLE,
  STATE_THIS,
  STATE_THAT,
  STATE_OTHER
} State;

State state;

const int IR_BUTTON_1    = 0xFF807F;
const int IR_BUTTON_2    = 0x112233;
const int IR_BUTTON_3    = 0X445566;
const int IR_BUTTON_STOP = 0x778899;

void setup()
{
  Serial.begin(115200);
  Serial.println(F("setup()"));
  state = STATE_IDLE;
}

void loop()
{
  Serial.println(F("loop()"));

  switch(my_decoder.value)
  {
    case IR_BUTTON_1:
      state = STATE_THIS;
      Serial.println(F("Entered STATE_THIS"));
      break;
    case IR_BUTTON_2:
      state = STATE_THAT;
      Serial.println(F("Entered STATE_THAT"));
      break;
    case IR_BUTTON_3:
      state = STATE_OTHER;
      Serial.println(F("Entered STATE_OTHER"));
      break;
    case IR_BUTTON_STOP:
      state = STATE_IDLE;
      Serial.println(F("Entered STATE_IDLE"));
      break;
  }

  switch(state)
  {
    case STATE_THIS:
      DoThis();
      break;
    case STATE_THAT:
      DoThat();
      break;
    case STATE_OTHER:
      DoOther();
      break;
  }
}

void DoThis()
{
  Serial.println(F("DoThis()"));
}

void DoThat()
{
  Serial.println(F("DoThat()"));
}

void DoOther()
{
  Serial.println(F("DoOther()"));
}

This locks the state machine into an active state as per the OP's comment:

I want it to repeat the "void doSomething();" function until another button is pressed.

However, as Dave Newton pointed out in the comments, locking a machine into a particular active state can be dangerous, so I've edited the code to add a STOP button to transition back to the IDLE state. But this still relies on the operator pressing the STOP button to return to idle; there is no automatic return to idle which could be a hazard depending on the application.

Hm, maybe. I think if this was going to be a "non-degenerate" state machine, though, you'd have a "received input" state that then looped over the cm value until whatever its "done" condition is, then go back into a "waiting" or "processing" state, depending on what the OP's actual use-case is. As described here this is just breaking up a value check and a method call. The methods, all for it. The handling of states--dangerous, because no example of exiting a state is provided :)


text:
Arduino code to control 4 led's from 4 buttons
This is my very first arduino sketch and it's causing me a bit of a headache.
Sounds so simple really all I want the sketch to do is digitalread from one of 4 digital input pins and then digitalwrite to one of 4 output pins in essence.
So that when button 1 is pressed LED 1 lights up, button 2 pressed led 2 lights up and so on.
I've added a serial write so I could check that the buttons are actually working when pressed.
The code I've written:
const int buttonPin1 = 7;     // number of pushbutton 1 pin
int buttonState1 = LOW;       // set the default variable value for pushbutton1 status
const int ledPin1 =  6;       // number of the LED 1 pin
const int buttonPin2 = 8;     // number of pushbutton 2 pin
int buttonState2 = LOW;       // set the default variable value for pushbutton2 status
const int ledPin2 =  9;       // number of the LED 2 pin
const int buttonPin3 = 4;     // number of pushbutton 3 pin
int buttonState3 = LOW;       // set the default variable value for pushbutton3 status
const int ledPin3 =  5;       // number of the LED 3 pin
const int buttonPin4 = 2;     // number of pushbutton 4 pin
int buttonState4 = LOW;       // set the default variable value for pushbutton4 status
const int ledPin4 =  3;       // number of the LED 4 pin
void setup() {                  // Set Pins to Outputs Or Inputs
  pinMode(buttonPin1, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin1, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin2, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin2, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin3, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin3, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin4, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin4, OUTPUT);     // initialize the LED pins as an outputs:
  Serial.begin(9600);           // initialize serial communication at 9600 baud
}
void loop() {
buttonState1 = digitalRead(buttonPin1);  // read current states of the pushbutton value:
  buttonState2 = digitalRead(buttonPin2);  // read current states of the pushbutton value:
  buttonState3 = digitalRead(buttonPin3);  // read current states of the pushbutton value:
  buttonState4 = digitalRead(buttonPin4);  // read current states of the pushbutton value:
// check if the pushbutton is pressed buttonState# == HIGH/LOW
  // if pressed change buttonState == HIGH to turn on ledPin#
  // else if buttonState == LOW then digitalWrite(ledPin#, LOW) Keeps Led off.
if (buttonState1 == HIGH) {    //check buttonState
digitalWrite(ledPin1, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin1, LOW);   // turn LED off:
}
Serial.println(buttonState1); //Print buttonState to serial
if (buttonState2 == HIGH) {   //check buttonState
digitalWrite(ledPin2, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin2, LOW);   // turn LED off:
delay(10);
}
Serial.println(buttonState2); //Print buttonState to serial
if (buttonState3 == HIGH) {   //check buttonState
digitalWrite(ledPin3, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin3, LOW);   // turn LED off:
delay(10);
Serial.println(buttonState3); //Print buttonState to serial
}
if (buttonState4 == HIGH) {   //check buttonState
digitalWrite(ledPin4, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin4, LOW);   // turn LED off:
delay(10);
Serial.println(buttonState4); //Print buttonState to serial
}

The Leds all have a common GND and the buttons all have a common GND.
Buttons are connected to +5V & Input pin# so one terminal has got two wires,
Led's are connected to digital output pins then resistor and straight to GND.
What happens is that ALL of the LED's come on when any one of the 4 buttons in pressed.
I've attempted to edit some of the code in the example sketches to get this to work.
Can anyone suggest anything that I'm doing wrong?
Or ammend the code sp that I can see where I'm going wrong.

Show us your schematic.

They way you have wired the buttons is probably not right. They also require resistors or else the digital input is open when a button is not pressed. An open input can do anything, it can even go along with a nearby pin.

It is likely you have connected the switches incorrectly.  Normally, people use single poll single throw (SPST) switches connected to 5 volts and the input pin of the Arduino.  This will pull the input pin to 5 volts when the switch is closed.  Then, to pull the input pin to ground when the switch is open, people add a large resistor between ground and the same processor pin.

Almost any large resistor will work here.  Consider using 10K ohms (10,000 ohms) or there abouts.
Of course, if you are using a 3 volt Arduino, do not connect the switch to a 5 volt source.  Instead connect it to a 3 volt source.
Alternatively, a pull up resistor inside the processor, if available, can be activated.  Look at this arduino.cc web page. There this sample code shows how to activate the processor's pull up on pin number 2:
pinMode(2,INPUT_PULLUP);

Because not all processors have a "pull up" feature on all input pins & because the range of internal to the processor pull up resistances can vary (for example 50,000 ohms to 150,000 ohms), it may be more useful and universal to use an external pull up resistor.

That's obviously the problem, the reisitor I'm using on switches isn't big enough. They are wired exactly as above except I'm not using a 10k resistor. It's of a smaller value. without cracking the multimeter out I can't remeber off the to of my head what rating I used. Does the code look alright though? I've broken it down into logical steps and done a flow chart to work out the logic. So was hoping that there was nothing wrong with the code.....

Didn't see any obvious problems with the code.  But you should always start with something simple that works then build from there.  The 10ms delays will not make much difference.  Likely it will take longer to print out the serial data.

Using a smaller resistor should work as well.  But this will uselessly increase the current draw.  It is possible you have used such a small resistor that you have exceeded the current capacity of your power supply or batteries.  In such a case the voltage will drop and cause unexpected results.  In extreme cases you can cause damage.

"Normally, people use single poll single throw (SPST) switches connected to 5 volts and the input pin of the Arduino. "  No, normally th internal pullup resistor is used, and the button only connectst the pin to Gnd.

Get rid of the external resistors, use the internal pullup resistor.
In setup():
pinMode (pinX, INPUT_PULLUP);
Wire the button between input pin pinX and Gnd, then test for a LOW to see if the button is pressed in loop():
if (digitalRead (pinX) == LOW){ // button is pressed
// do something
}
else { // button is not pressed
// do something else
}

I would suggest taking the resistor/s off the switches, so the button connects to digital inputs to the 3v/5v line. Then use 470ohm resistors for the leds(to limit the current) on the digital outputs.


text:
mcufriend 2.4 TFT with ESP8266
I have this TFT:

Now, the problem is, I will not use this as a shield (i.e. I will not just put it on top of an Arduino Uno). I will use it with an ESP8266 (NodeMCU). I want to know how to wire them up together. There is this website (and a few more that say the same way). But the problem is I cannot find SDI/MOSI or SDD/MISO on the TFT above.

I also want to program mcufriend 2.4 TFT with ESP8266 did you try it and did it work? can you give me any information? (Library, connection between mcufriend 2.4 TFT and ESP8266)

interessting, did it work on NodeMCU?

You have an 8-bit parallel interface TFT display. It requires 13 GPIO pins - D0-D7 plus reset, chip select, read, write and register select. You can forego the "read" signal and tie it high to save a pin. You can probably do the same with the reset signal, meaning you need a minimum of 11 pins.
I am not sure the NodeMCU has that many available, does it? (maybe it does, I don't have one to hand right now), so you may want to try getting it going with an SPI or I2C IO expander (though slowly).
And then of course you have to find the right library for the chip on the display (there's a few it could be - I have seen at least 3 different ones on the same, or similar, carrier PCB) that works with the NodeMCU.

SD_DI is the MOSI, and SD_DO is the MISO. According to the datasheet.


text:
AtTiny44 and AtTiny 85 communication
I'm working on a project where I use two microcontrollers: an AtTiny44 (20MHz ext clock) and an AtTiny85 (8MHz internal).
What I'm trying to achieve is an I2C communication between the 85 and the 44, with the 44 acting as master and the 85 as slave, then transmit the data read from both of them to a PC with FDTI cable using softwareSerial.
I started with writing the AtTiny85 code:
   #include <TinyWireS.h>
   #define ADC3 A3

   void setup() {
      TinyWireS.begin(I2C_SLAVE_ADDRESS); // join i2c network
      TinyWireS.onRequest(requestEvent);
      pinMode(4,OUTPUT);
      digitalWrite(4,HIGH);
      pinMode(ADC3,INPUT_PULLUP);
   }

   void loop() {
      // This needs to be here
      TinyWireS_stop_check();
   }

   // Gets called when the ATtiny receives an i2c request
   void requestEvent() {
     int val=analogRead(ADC3);
     byte valLow = val & 0xff;
     byte valHigh = (val >> 8);
     TinyWireS.send(valHigh);
     TinyWireS.send(valLow);
   }

With this I am able to send the data read from an adc (A3 pin) to an Arduino as 2 bytes
The Arduino code:
  #include <Wire.h>

  int check=0;

  void setup() {
     Wire.begin();        // join i2c bus (address optional for master)
     Serial.begin(9600);  // start serial for output
  }

  void loop() {
      Wire.requestFrom(8, 2);    // request 2 bytes from slave device #8

      while (Wire.available()&&check<2) { // slave may send less than
                                          // requested
        int c = Wire.read(); // receive a byte as int
        check++;
        int d = Wire.read();
        check++;
        int number = d | c << 8; //convert two bytes as int
        Serial.println(number);
     }
     check=0;
     delay(500);
   }

Maybe the check variable is useless, but it's not a problem, because I'm getting the right reading on serial monitor.
I then moved to the AtTiny44; I have an onboard thermistor, and I need to print on softwareSerial the value read from this and the value read from the AtTiny85 board.
This is the code, using TinyWireM:
  #include <TinyWireM.h>
  #include <USI_TWI_Master.h>
  #include <SoftwareSerial.h>

  SoftwareSerial mySerial(0, 1); // RX, TX

  int adc = 2;
  int check=0;

  void setup() {
    pinMode(1, OUTPUT);
    pinMode(0, INPUT);
    pinMode(4,INPUT_PULLUP);
    pinMode(6,INPUT_PULLUP);
    pinMode(7, OUTPUT);
    pinMode(adc, INPUT);
    mySerial.begin(9600);
    TinyWireM.begin();        // join i2c bus (address optional for master)
    while (!mySerial) {
      ;
    }
    mySerial.println("Serial comm started");
    digitalWrite(7, HIGH);
    delay(1000);
    digitalWrite(7, LOW);
 }

 void loop() {
   mySerial.println((int)analogRead(adc));
   TinyWireM.requestFrom(8, 2);    // request 2 bytes from slave device #8
   while (TinyWireM.available()&&check<2) { // slave may send less than
                                            // requested
   digitalWrite(7, HIGH);
   int c = TinyWireM.receive(); // receive a byte as character
   check++;
   int d = TinyWireM.receive();
   check++;
   int number = d | c << 8;
   mySerial.println(number);
   }
 check=0;
 delay(500);
 }

The softwareSerial is working good (I get to write the ADC data from the 44) but I can't find where the problem on I2C is (on console monitor mySerial.println(number) sends out 0).
What I excluded so far: connections error, clock skew (the clocks are distant between them), pull-up on I2c bus (they are high in both devices)

Why use I2C? Maybe other protocols could be faster/simpler/less pins for this use?

I don't think there are simpler protocol, or with less pin. I thought of using two softwareSerial but they can't work togheter at the same time

You data rate seems pretty low, and maybe you only need to send in one direction over the link between the two units? If so, maybe just a single signal wire and a ground between them. Sender drives the wire high for 1ms to signal a "0", 2ms to signal a "1". Really simple bit banged serial port.

I need to send data in only one way, yes. I'd like to use I2C, but I'm interested in your workaround. Can you point me to some hints? Also how can I manage the master requesting data to the slave in your solution?

Do you need to have the master request? Why not just have the slave always blindly sending?

It could also blindly send, but how I can manage the timings between the softwareSerial and the bit banged serial?

On the chip connected to the FDTI, make a pin change ISR for the piun that is connected to the data line coming from the remote. Everytime the pin changes low-to-high, save the current time. Everytime it changes high-to-low, look at the diff between current time and saved time. If time is ~1 second then received a 0 bit, if time is ~2 seconds then received a 1 bit. shift them into a holding variable until you have a byte of data. When you get it working, you can make much faster, but with 1 & 2 seconds easy to debug with an LED.

Perhaps the ATtiny85 can't handle the I2C clock rate being generated by the AtTiny44.  Try running them both at the same clock speed.

the 85 as slave

writing a slave, especially an i2c slave, isn't for the faint of heart. typically you use a state machine to help handle that.
one great example is the one presented by nxp in old LPC210x datasheet. AVRs share the same i2c hardware so it is immensely portable to the avr.

I know that, but the funny thing is that is the attiny44 master that is not working!


text:
Making a 7-hour timer-based relay
I want to make a very small 7-hour timer circuit that can turn on a relay after 7 hours. I am trying to make the first prototype with an Arduino Nano but I can't understand how to program it for such purpose. So please help me out.
Once I make a prototype in Arduino then I was thinking to make a small one  using an ATtiny13. Can I use an ATtiny13 for such purpose?

Never seen an Arduino core for the tiny13. You may have to program it at the avr-libc level.

You could try a timer with millis. 7 hours is (7L * 60L * 60L * 1000L) milliseconds. The ATtiny13 has an internal oscillator for the CPU clock, the 7 hours will not be accurate. I have ATtiny13 chips and I have seen the Arduino core for it, but I never tried it: https://github.com/MCUdude/MicroCore

I have investigated the MicroCore code and compared it with my project for ATtiny13 (I did not actually compile a similar project). The overhead is not too bad, and it makes fast prototyping possible because it is pretty Arduino compatible. The millis function is very inaccurate though, because that uses the watchdog timer. For normal basic use of the ATtiny13 I would recommend the MicroCore. I think the MicroCore is well made, I like it a lot (@EdgarBonet).

Could you please tell in your question: 1) what event will start the timer? 2) will the tiny13 have something to do during these 7 days other than count time? 3) what accuracy do you need (7 days ± how much)? 4) what clock source do you plan to use on the tiny13?

The question is whether its a one shot triggering ON the relay after 7 hours and thereafter you always leave it ON or its some periodic process where every 7 hours, you want the relay to trigger ON and OFF alternatively. Presuming the latter, this can be done in 2 ways:
1) Configure a hardware timer interrupt to call a small function every second and increment a variable within that function. So after 1 hour your variables value must be 3600, therefore after 7 hours it will be 25,200. Once the variable is equal to 25200, you can ON the relay and reset the variable to 0. Factors such as the number of hardware timers and its resolution differs from one MCU to another.
2) Use a Real Time Clock like the DS1307 for this purpose and save you hardware timers for performing some other time critical operations.
Hope this helps!.

You wrote: “Configure a hardware timer(32 or 16 bit)”: there is no such thing in the ATtiny13.

@EdgarBonet, I am not aware if ATiny13 has any inbuilt hardware timers as I haven't used it. However, until today whichever MCU's I have used had at least one hardware timer. For example, the esp8266ex has one 32 bit hardware timer, similarly the TICC3200 has four 32 bit hardware timers.

Just did a Google search and found a few examples as well where they are flashing an LED using the timer interrupts. And between, just got to know its an 8 bit controller, hence edited my answer.

cant understand how to program it for such purpose so please help me out

it is fairly easy to approach such questions:
1) you can program any?
2) can you program this mcu to blink an led?
3) can you program this mcu to do short time counting?
4) can you program this mcu to do long time counting?
what you help helps you the most depends on your  answers to those questions.


text:
Micro servo is not working with Arduino UNO
I am new to Arduino and trying to do some basic tasks. I want a micro servo to rotate but it's not working, only slightly virbating when I launch a sketch. Below on the photos is how it is all assembled: I have a jumpwires connected to GND, 5V and #8 ports just as in the tutorial. I use micro servo SG-90 and Funduino UNO. Does anybody have any ideas what might the problem be? Here is also the sketch.
#include <Servo.h>

Servo servo;

void setup() {
  // put your setup code here, to run once:
servo.attach(8);
}

void loop() {
   // put your main code here, to run repeatedly:
servo.write(0);
delay(2000);
servo.write(90);
delay(2000);
}

USB power is usually way too weak for driving servos or motors

Hm, I didn't think about it. So, should I use batteries or charger instead?

You should not power a servo from a USB port.
However, your most glaring problem is that you have entirely mis-wired the connections, such that no wire is going to the correct place.
Servo connections are in the order of Ground - Power - Signal, usually with a dark color for ground and a redder one for power.  Connector shells aren't standardized between brands, but within one there may be keying to prevent reverse installation.
It would appear that on your servo, ground is brown, power red, and signal orange.
Pull out all three wires and start over; also you'd do well to use a dark color for the ground, as you appear to have mixed up the power and ground as well as the signal.

Yes, I totally messed up with all the wire connections. Now when all of them are in the right places everything is working excellent! Thank you for the explanation, I'm gonna keep it in mind.


text:
How can I define integer inputs to a function and get array as an output?
I am trying to write a function that takes integer values as an input and gives an array as an output. I have tried the following code but it doesn't show the output result in the serial monitor:
int *phi (int cur,int vol,int t) {
  int z[4];
  z[0]=1;
  z[1]=cur;
  z[2]=vol;
  z[3]=t;
//z=cur+vol+t;
  return z;
}

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

}

void loop() {

int result;
result=phi(1,2,5);
Serial.begin(9600);
Serial.print(result);

}

You cannot return an array. What's your final purpose?

You are asking an XY problem.

I'm voting to close this question as off-topic because it's purely a programming question.

If we narrow the scope too much, we end up with nothing but "Did I burn up my Arduino?" and "My PC won't recognize my Arduino" questions. While this is a programming question, Arduinos are all about learning to build and code embedded systems, which means learning programming. We accept questions about using pullups, FET switches, and the lengths of OneWire busses, which strictly speaking, are electronics questions, not Arduino topics either, but are part and parcel of what we do with Arduinos. I vote to reopen the question and perhaps take our guidelines as guides more than lines.

@EnricBlanco While you can't technically return an array, you can return a pointer to the first element, which is what the function does an often sufficient if you obtain the length by some other means.  However in this case the stack address returned invokes undefined behavior, and the improper assignment of an int * return value to an int variable strongly suggests the code we're looking at isn't even a version actually tried, but a mid-experiment mishmash.

-1 for posting code which does not compile and claiming that you have tried its behavior, which is not possible.  Your improper assignment of an int * to an int will be rejected by any sane compiler.  To receive help you must post the actual code.

Just a reminder for everyone to be humble and civil in the comments here. Name calling is strictly not allowed, especially to those that are trying to help others.

like this: https://www.programiz.com/cpp-programming/passing-arrays-function

Defining the array in phi() returns a pointer to unassigned memory - it is no longer reserved once phi() returns. The next function call or interrupt (which you have no control over) will likely clobber the data.
A better choice would be to define z in the caller (loop() in this case) as an uninitialized array and pass it to phi() to fill and return. This is the more usual case, as it:

avoids using globals,
permits multiple calls to the function without clobbering previously returned data (you would pass different arrays in this case), and
it avoids statically defined arrays that may not be needed after the caller returns, in a memory-starved environment (this may not be applicable if loop() is the caller).

In short, it gives the calling function the greatest flexibility, while committing the least amount of memory.

It appears you have created an array which only has scope with in the method "phi".
In practical terms, the array "z" is a local variable declared inside of the method and, as such, will likely end up in temporary RAM.  When the method has completed, the RAM reserved for that method's local variables is released and is available for other purposes.
To fix this you could make "z" a static or you could give "z" global scope.

There are some other problems you need to sort through.  Like mixing "integers" and "pointers to integers".  But the problem addressed by the above answer is usually the one that causes people the most confusion / problems.