text:
Electret microphone board strange offset using Arduino
I'm experimenting with an electret microphone, specifically this one.  I put it on my scope and I see what I expect - a really small voltage, typically under 20mV, that varies appropriately with sound.
However, when I put it into my Arduino (connecting signal pin to A0, V to 5V, and G to GND) and read it using analogRead on the appropriate pin, I end up getting a strange offset.  The analog read should read 0 more or less constantly, due to the low voltage coming out of the board.  However, I get an offset of around 425 counts on the ADC, implying that the voltage is somewhere around 2.5V.
What's going on?  Why would the arduino be reading a voltage when there isn't any?

When you test it with a scope, what supply voltage are you using?

5V, from the Arduino 5V pin

An electret microphone is like a resistor which changes its value according to the sound.
To use it you must form a voltage divider with it, as if it were half of a potentiometer.
Thus you add a resistor to +5V (which is already on the board).  This means that when it is silent the voltage you get is the ratio of the resistor and the resistance of the microphone.
If the resistance has been chosen correctly then the output you get should be roughly half the supply voltage when silent. Any sound will cause that output to swing around that "zero" point.
It's just like a potentiometer.  When silent the potentiometer is in the central point. When you make noise you're moving the potentiometer in both directions.
To get rough values you should first get the "silent" reading from analogRead. You can then subtract that value from all subsequent readings.
Note that the results will be non-linear. To do it properly you should calculate the resistance of the microphone by using the supply voltage, the "upper" resistor value, and the sampled voltage to calculate the resistance value like you would for any other resistive sensor (such as an LDR or force sensitive resistor).

You're right.  I think something is wrong with my scope, then, because it showed the output centered around 0V.  Looking at it on a multimeter and it's at 2.5V when quiet.

Is your scope set to AC coupling?

It was set to DC coupling, but I think that something is wrong with that particular mode.  There is no difference between AC and DC coupling, leading me to believe that the coupling circuitry is not disengaging, causing my confusion above


text:
8 bit arduinos: What happens to the data in registers during a function call? During an interupt?
If I have one function that uses registers heavily calling another that does the same thing, what happens?  Does the data get destroyed?  What, then, would happen on return to the first function?  Is this different for interrupt handlers?

The compiler is capable of analyzing which registers are used by the function or ISR, so it generates prologue and epilogue code that saves the registers on the stack on entry and restores them on exit.

Is it any different for regular functions?

@MichaelStachowsky: Nope.

source: Stack Exchange

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

sort: votes


text:
Teensy lc linker script question
I am under the impression that the origin of RAM on a Cortex M is 0x20000000.  However, in the linker file for it, the ORIGIN of RAM is set to 0x1FFFF800.  Is that an error, or is there a reason for the discrepancy?

The Cortex M does not "have RAM at 0x2000000". The Cortex M is just a CPU. It is down to the chip manufacturer where they choose to place RAM in the memory map.
In the case of the MKL26Z64VFT4 used on the Teensy LC:

The on-chip SRAM is a single contiguous block split into two ranges: 1/4 is allocated to SRAM_L, and 3/4 is allocated to SRAM_U. Regardless of the block size, the SRAM is implemented such that:

SRAM_L is anchored to 0x1FFF_FFFF and occupies the space before this ending address.
SRAM_U is anchored to 0x2000_0000 and occupies the space after this beginning address.

Valid address ranges for SRAM_L and SRAM_U are then defined as:

SRAM_L = [0x2000_0000–(SRAM_size/4)] to 0x1FFF_FFFF
SRAM_U = 0x2000_0000 to [0x2000_0000+(SRAM_size*(3/4))-1]

Since there is 8kB of SRAM, 2kB is below 0x2000000 and 6kB is above 0x20000000. 2kB is 0x800. 0x2000000 - 0x800 = 0x1FFFF800.

Thanks for that, good to know.  One question, though: why does "the cortex memory map" exist, if the chip manufacturers are free to modify it?

For the M0 there is a "default" memory map, which is only a suggestion. It's up to the manufacturer what they do.

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


text:
Can't find OV2640 module! pid: 254
I'm trying to follow this tutorial.
But I'm stuck in this error:
Can't find OV2640 module! pid: 254

I tried to contact the author of the program, but I have not had an answer yet.
I'm using the ArduCAM Mini module OV2640.
Has anyone ever been in this situation?

Thank you very much for your attention.
But the problem was in the dupont connection wires, as mentioned here!

If you look at line 762 of 'ArduCam_ESP8266_FileCapture.ino' you should see it is looking to read two bytes from the camera to check that the model number is either a '2641' or '2642'.
You are seeing the error because you are not getting those values back.  So between 761 and 762 insert some debug and print what you are getting back:
Serial.print ("vid = ");
Serial.println (vid);
Serial.print ("pid = ");
Serial.println (pid);

I guess you will either get 00 00 or a different valid (maybe) model number.  If you think its a valid model number add another condition to the if statement and see if it works.
Oh and don't forget to post the results, because I'm going to give it a chance too when I get time :)

Does it still happen if you power the cameras off and then on again. I was getting the same thing as there is a bug in one of the examples where the cameras are placed into deep sleep mode so when you reset the microcontroller or whatever you have the cameras can't be found because they are sleeping. I add the line
yourcam.clear_bit(ARDUCHIP_GPIO, GPIO_PWDN_MASK);

to clear this state when intialising.


text:
Can't run two separated DC Motors
I'm trying to build Bluetooth RC car, but I can't run only one DC motor.. only both of them. Everything works fine, the bluetooth, the app but when i try to go forward/backward/left/right nothing happens, only when i run both of them. I'm running the Arduino Nano with usb cable. The bluetooth connection is stable, The DC motors are working. I don't know what I'm doing wrong. Thanks!

const int AIA = 2;
const int AIB = 3;
const int BIA = 4;
const int BIB = 5;
byte vSpeed = 255;
int state;

void setup() {
pinMode(AIA, OUTPUT);
pinMode(AIB, OUTPUT);
pinMode(BIA, OUTPUT);
pinMode(BIB, OUTPUT);

// Initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
}

void loop() {
  //Save income data to variable 'state'
    if(Serial.available() > 0){
      state = Serial.read();
    }

  /***********************Forward****************************/
  //If state is equal with letter 'F', car will go forward!
    if (state == 'F') {
      analogWrite(AIA, vSpeed);
      analogWrite(AIB, 0);
      analogWrite(BIA, 0);
      analogWrite(BIB, 0);
    }
  /**********************Forward Left************************/
  //If state is equal with letter 'G', car will go forward left
    else if (state == 'G') {
      analogWrite(AIA, vSpeed);
      analogWrite(AIB, 0);
      analogWrite(BIA, vSpeed);
      analogWrite(BIB, 0);
    }
  /**********************Forward Right************************/
  //If state is equal with letter 'I', car will go forward right
    else if (state == 'I') {
      analogWrite(AIA, vSpeed);
      analogWrite(AIB, 0);
      analogWrite(BIA, 0);
      analogWrite(BIB, vSpeed);
    }
  /***********************Backward****************************/
  //If state is equal with letter 'B', car will go backward
    else if (state == 'B') {
      analogWrite(AIA, 0);
      analogWrite(AIB, vSpeed);
    }
  /**********************Backward Left************************/
  //If state is equal with letter 'H', car will go backward left
    else if (state == 'H') {
      analogWrite(AIA, 0);
      analogWrite(AIB, vSpeed);
      analogWrite(BIA, vSpeed);
      analogWrite(BIB, 0);
    }
  /**********************Backward Right************************/
  //If state is equal with letter 'J', car will go backward right
    else if (state == 'J') {
      analogWrite(AIA, 0);
      analogWrite(AIB, vSpeed);
      analogWrite(BIA, 0);
      analogWrite(BIB, vSpeed);
    }
  /***************************Left*****************************/
  //If state is equal with letter 'L', wheels will turn left
    else if (state == 'L') {
      analogWrite(BIA, vSpeed);
      analogWrite(BIB, 0);
    }
  /***************************Right*****************************/
  //If state is equal with letter 'R', wheels will turn right
    else if (state == 'R') {
      analogWrite(BIA, 0);
      analogWrite(BIB, vSpeed);
    }
  /************************Stop*****************************/
  //If state is equal with letter 'S', stop the car
    else if (state == 'S'){
      analogWrite(AIA, 0);
      analogWrite(AIB, 0);
      analogWrite(BIA, 0);
      analogWrite(BIB, 0);
    }
}

What is meaning "The DC motors are working." ? Are you able to control one DC motor using your analogWrite() calls ?

Most likely unrelated, but...  You can only use analogWrite (PWM) on pins 3, and 5. Also the backwards section seems to be missing settings for BIA and BIB.

It means that are functional. The thing is i can't run only one of them.. only both of them at the same time.

AIA and AIB ar for forward and backward, BIA and BIB for left and right. that's why it's missing at backward.. i don't need to run the left and right motor

Which cases work?    graphics-wise board looks like some sort of a dual L9110S thing.  Is it like https://www.bananarobotics.com/shop/How-to-use-the-HG7881-(L9110)-Dual-Channel-Motor-Driver-Module  ?   Does the board work as expected if you jumper it up manually?

It's L9110S. And works only forward-left and forward right, backward-left and backward-right.. that's it.. IF i disconect the batteries and plug the board in and i put the bridge on VIN and GND it's working great but it doesn't have power. I need power, that's why i connected the bridge to external batteries and the board to another battery. But now it's doing this..

Oh -- probably the separate grounds are causing weirdness.  Tie them down.

Unrelated, but, are you uploading code over bluetooth?

I upload it via usb.

Connect the Nano ground to the driver board ground.  Since they do not share a common ground, they can have odd behavior as their ground planes float.
You need only connect the grounds, the USB can still provide +5 to the Nano, and the +9 can still provide power to the driver.  The only energy that will flow through the black wire connecting the grounds is the energy that flows between pins 2,3,4,5 and the driver's AIA, AIB, BIA, BIB, for the logic signals, which I'd bet is in the sub-uA range.

If I connect the gnd of the driver to nano, then i have to connect the nano gnd to batteries (i e black wire) right? Then i have nano and driver sharing the same power source. But i want to make the driver run on 9v batteries alone and the nano on another power source. So i can have full power to motors. Is it wrong? How am i supposed to make the circuit to achieve what i said?

One more thing. If i connect the nano with usb power source and the driver to nano (gnd and 5v) everything works fine but the motors aren't receiving enough power. The problem is when I'm separating the power sources and make the motors run on their own power, that's when i get the behavior..

Yep, just the black wire.  See update above.  No need to power the Nano with the +9 if you do not want to.


text:
Does a pulldown resistor use less battery power than a pullup resistor?
I am designing a circuit connected to a simple open-close sensor, like a switch. For ease of construction, the circuit with the sensor switch closes to ground, and uses a 1 MΩ pullup resistor to Vcc to signal HIGH when the switch is open.
I realize that power is flowing the entire time the switch is open, which may (or may not) drain the battery. Would it be more efficient to use a pulldown resistor to ground, and have the switch open to Vcc?
Tangentially, should there be a resistor on the connection to Vcc as well? Either to reduce current (save battery power) or prevent damage to the ATmega328?
Thank you!

The input current does not depend on the pin level. Have a look at this discussion from avrfreaks. The input impedance of a digital pin is extremely high. The leakage current of the Atmega328P (here as example chip) is mentioned to be 1uA for both pin states. So this current is both unavoidable and neglectable from a normal view.
But the input impedance of a digital input pin is not only dependent on this leakage current. There is also a capacitance, which will lower the impedance for higher frequencies. So, if you drive the input with higher frequencies, the input will draw more current. But you only have a switch connected to it, which is very very low frequency.
So it doesn't matter, if you pullup or pulldown. The main current consumption will result from the moments, where the switch is activated, since then a current flows through the pullup/pulldown resistor to ground.

Tangentially, should there be a resistor on the connection to Vcc as well?

No need for a resistor there. The input impedance of the pin is already high enough and you don't want to create a voltage divider with your pulldown resistor (which would change the voltage levels at the pin).

A pullup or pulldown resistor causes a current flow additionally to the neglectable current into a input pin. and the voltage level matters, of course.

The additional current only flows, if the switch is activated, so with a pullup resistor, when the switch connects the pin to ground. Otherwise you have the pullup resistance plus the input impedance in series, which is also very neglectable. Normally the pullup resistor for a switch is big enough, so that the current is also neglectable.

If the sensor does provide two defined voltage levels, you do not need a pullup or pulldown resistor, but if it's only a switch: either (closed) connected to Vcc or GND, or (open) not connected, you need a pullup or pulldown resistor to get a defined voltage level in case there's "nothing else" (except the wire to the switch catching noise out of the air) connected to the digital input pin.
When the switch is open, the pullup/pulldown resistor is connected to the input pin and nothing but that neglectable leakage current is flowing.
When that switch is closed, some current will flow through that resistor, according to Ohm's law. You have to optimize between that current and the risk of catching some noise signal. Typically, µControllers like the Arduino atmel atmega328p have builtin pullup resistors of ~30k..50k, which should be fine for standard situations.
If you fear the battery drain, you can experiment with bigger resistors, but first make sure to build a scenario where the usual situation is "switch open". e.g. A fridge's door switch should be NC, but pressed while the door is closed.  :)

I realize that power is flowing the entire time the switch is open, which may (or may not) drain the battery.

No, it doesn't. You get a small spike as the switch is opened or closed, as the gate capacitance is charged or discharged, but other than that there is negligible current draw by a pin, which remains static regardless of the direction of the biasing resistor.

Tangentially, should there be a resistor on the connection to Vcc as well? Either to reduce current (save battery power) or prevent damage to the ATmega328?

Absolutely not.  The current draw of the MCU is not static. That means that the current through such a resistor would not be static, and so the voltage dropped across that resistor would fluctuate too - meaning if the current draw rises above a certain point the chip will be starved of power and will "brown out".
You only need a resistor to limit current when you have a device that cannot control the current by itself, such as an LED or other "non-linear" device.

Thank you. Does this mean that the Pushbutton tutorial on the official Arduino site is wrong in having a resistor between Vcc and the input pin?

@dotancohen No, because that is a pullup resistor. You are on about a resistor between the power supply and the VCC pin (I assume), which is completely different to what that tutorial has.

Ah, I see where the confusion is. When I said "on the connection to Vcc" I was referring to the connection between the input pin and Vcc. I was not referring to the power to the ATmega 328. How should I reword that so that it is clear? Thank you very much for your help, both in teaching the proper wiring and in helping improve my question phrasing.

I am not really sure what you are asking in that question now. If you have a pullup resistor then you have a pullup resistor. If you have a pulldown resistor then you have a pulldown resistor. What actually are you asking about when you ask about a resistor to vcc? That is a pullup resistor. If you have one then you have one. What are you asking "As well?"...?

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


text:
ESP 8266 reverse digitalWrite behaviour on which pins?
I am using a device with an ESP 8266 microcontroller. I have discovered that setting LED_BUILTIN to HIGH turns the built-in LED off and  setting LED_BUILTIN to LOW turns the built-in LED on. This seems to be because the microcontroller can sink more current than it can source.
Before I start using this microcontroller, I would like to know which other pins have this reverse behaviour. I've looked up datasheets for the ESP 8266 but I don't see how to discern this information. I would simply write a sketch to test, but I'm not sure what I might damage, and I'm not sure how to determine when an output pin is in the high-impedance state anyway.
On the ESP 8266, how to know which pins are HIGH -> 0v and which pins are HIGH -> 5v? Are the HIGH -> 0v pins necessarily LOW -> 5v? Where is this documented?

the pin is not reversed. the attached circuit with the LED reverses the signal.

@Juraj: Thank you. The pin is not reversed, but the behaviour (on this board and others) is. Are you saying that the issue is board-specific, so won't be relevant to all ESP 8266 boards? This is the board that I'm using.

it is a Wemos D1 R1

the behaviour is not reversed ... a HIGH does not necessarily mean LED on ... a HIGH only means high output

Yes, or at lease a clone of one. I see mention on forums of people having this issue with other ESP 8266 boards as well.

@jsotola: So if the output is HIGH, that would make the LED turn off only if the LED were pulled down to 0v on the same side as the pin, and connected to 5v on the other side (i.e. the pin is on the LED cathode). Is that how this board is wired? Where is that documented?

'people' have issues with everything

@dotancohen, the schematic diagram is the documentation

@dotancohen, it is unclear what this means LED were pulled down to 0v on the same side as the pin .... how do you turn on a LED? ... one side is connected to HIGH and the other side is connected to ______

@dotancohen, you are overthinking this ... an LED lights up if there is a voltage difference across the LED, and that is all (assuming correct orientation) ... the LED will not light if both leads are grounded, or if both leads are conected to 5 V, or if both leads are connected to a 1000 V

@jsotola Where is that schematic diagram? I found the WeMos D1 page on the Raspberry pie wiki but the diagram is impossible to read. The Official WeMos site doesn't seem to have such a diagram, mentioning only the D1 Mini.

I see on the D1 Mini schematic that the LED is in fact connected with the cathode to the ESP 8266, but without the pulldown resistor that I suspected.

The esp8266 must have a pull-up on io 2 for boot configuration. The Wemos D1 boards put the LED in series with the pull-up resistor on io 2. This creates the 'reversed' LED behavior.

The large D1s are retired and it is hard to find a good and readable schematics. The cut out is from D1 mini schematics.

I see now, thank you! I take it that this is common, but not necessary, on ESP 8266 boards.

I've found the explanation of the boot configuration and it is lucky that I did, as it is non-trivial and very important. Thank you Juraj!

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


text:
Which Datasheet applies to the ATmega328p?
While researching minimum-voltage requirements of Uno, I came across what appear to be two datasheets for the ATmega328P:
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf
Specifically, the power requirements (and processor speed for each power level) differ. How could I know which datasheet applies to the chip I'm using? I'm actually using an Arduino clone:

It seems the first document is only for the 328P, and the other supports more (including the 328P). I would expect the information regarding the 328P is consequent in both versions (or should be).

@MichelKeijzers: As can be seen in the photo, I am using a 328P. One of the datasheets states that the microcontroller can run at 1.8v @ 4 MHz, the other states a 2.7v minimum.

I checked the revision history and the first talks about adding automotive, but sorry, I can't explain the differences. Hopefully adds a correct answer. Upvoted since I'm curious too now.

You have ATmega328P-AU. Classic Uno with DIP socket has ATmega328P-PU. Arduino Uno SMD has Atmega328P-MU.
The automotive versions ATmega328P-15AZ and ATmega328P-15MZ have separate datasheet starting in Revision History with

Creation of the automotive version starting from industrial version
  based on the ATmega48P/88P/168P/328P datasheet 8025F-AVR-08/08.
  Temperature and voltage ranges reflecting automotive requirements.

Just to be sure: -AU does not stand for automotive? What does it stand for?

the first letter is package form. -P is "Plastic Dual Inline Package", -M is "Micro Lead Frame Package", -A is " Plastic Quad Flat Package". I only read the datasheet

Thank you. I've gone through the second datasheet again and still cannot find that information, even when searching for the phrases you mention.

@dotancohen, page 635

I see, thank you. I had no idea how to read that, I was expecting the information in another format.

I think there is an error concerning the information about supply voltages. At least it's not consistent: microchip has separate websites for ATmega328 and ATmega328p. On the site for the ATmega328p it says: "The device operates between 1.8-5.5 volts". But the datasheet they link on the exact same site says:
    "Operating voltage: 2.7V to 5.5V for ATmega328p".
This is not just confusing, but contradictory and so I think the only one who can say for sure is the manufacturer.
Actually, the specified supply voltages are determined by the manufacturer by testing at various levels, but the device might operate even below or above this range (of course, a developer has to comply with the specs). The 2.7V rating could be an old spec and in the meantime they might have found out that the device indeed runs fine even at 1.8V. Maybe, they have just missed to apply this change everywhere this rating is mentioned, but that's just a guess.


text:
Interfacing with TC5564APL-15 paralell static ram
I've found a Z80 processor and a TC5564APL-15 8K static ram chips, and I want to test the RAM chip, because it's really old and I'm not sure that it's not damaged. I do not have any experience with Z80's and RAM chip's, I'm not even sure that I didn't damage it while desoldering. I found THIS forum link, where a guy wanted to use a different RAM chip, but the code looked OK and I've took it. I did some modifications:

I only own one 74HC595, so I used that, I've connected the remaining address lines to 5V via 200Ohm resistors
I did not use any capacitors.
I've changed some connections.

Here's the modified code:
https://pastebin.com/9nfTQY8X
(Sorry for PB)
So it SHOULD print "0 0 0 8 / 0 0 0 8" to the serial, but it prints "0 0 0 8 / 8 8 8 8". The reason is unknown. Every other number works, I only found that specific bit not working correctly.
I'm not sure. Can my RAM chip be broken, or the circuit causes the problems?

Add a capacitor (0.1 uF at least) to the RAM chip.

The "modified code" on PasteBin has been deleted so there is definitely no way to answer this question as it stands.


text:
Connecting Arduino to a cheap Graphics Card for VGA Output
I understand that the Arduino is generally not fast or powerful enough to generate a suitable VGA/HDMI signal with higher resolution.
However, I've noticed that there are inexpensive PC graphics cards available that can easily maintain a stable screen on a monitor.

Back in the DOS era, it was relatively straightforward to write a short program that could output text to CGA/EGA/VGA cards using BIOS calls and a few assembly instructions. The BIOS itself surely was not overly complex or large.

So my idea is to take an Arduino, use shift registers like the 74HC595 to create a sufficiently long bus, and connect it to a cheap, obsolete GPU (e.g., an NVIDIA card from a discarded PC) along with a regular monitor. I would then write Arduino code to emulate a BIOS call, such as 10h, which would shift out the "bus status" to the 74HC595s, send the signal to the GPU, and continue this process until the characters are transferred to the GPU.
The GPU can easily generate VGA/HDMI signals and work with any modern monitor. It also has enough memory to support screen resolutions like 80x25, 80x50, or even 132x60 for text-based displays. In fact, it might even be possible to run at full graphical resolutions such as 640x480 or even 2560x1440, with the Arduino slowly sending graphic primitives to display.
While the GPU's performance would be severely degraded, it would still be a better alternative than throwing it away.

My question is whether it is possible or even feasible to connect a GPU to such a slow source. If it is, I would like to know if there are any readily available and understandable documentation or even someone who has already attempted this approach.
(Or should I post it somwere else? Where?)

There were gameduinos, vgaduinos and similar but i don't think it was that popular. Currently I don't even have a monitor with VGA. Rapsberry pi with hdmi is much better. But surely you can try some old bus, but they might need all the voltages you'll never see anymore (-5, -12)

I think you will have a very hard time implementing a functional PCI(e) bus electrically and timing-wise on an Arduino.

This is the kind of project where things are going to be hard to do and the result hardly worth the effort.  But even if you completely fail you'll learn a ton in the process.  So I say go for it if you have the time.

@StarCat I had seen some projects, where processors like 6502 were driven by external clock so slow, that arduino was able emulate RAM/ROM for them. (Basically the CPU was stopped until new data was generated). So I was hoping, that some Grasphic Cards could also run in such slow/static mode. But I could not found the lower limits (how slow it can run) - all I found was upper limits, how fast it can run.

You might have more luck with interfacing an old ISA VGA card to an Arduino/AVR, but I would not use the x86 emulation as described in this project and just program the VGA registers directly.

Wow, thank you, I was looking for something like that, but had no success. (And yes, my idea was to set it directly from my code, if possible)

This doesn't answer your question about the cheap graphics card, but see https://forum.arduino.cc/t/toorums-quest-ii-atmega328p-based-retro-video-game-with-256-color-graphics/192920 for where Petri Häkkinen did an arcade-style game with an Atmega328 and the AD725 chip for generating the VGA signal.


text:
expected initializer before void arduino
When I try to compile the following code in Arduino ,I get the error "expected initializer before 'void'".How can I get the code to work?
  void setup() {
  Serial.begin(9600);
}

float area = 0.0f,pre_area = 0.0f,tarea = 0.0f,rarea = 0.0f;
int x = 0,pre_x = 0,t = 0,pre_t = 0;

long unsigned int t

void loop()
{
  x = analogRead(A0);
  t = millis();
  float diff_t = (float)(t - pre_t)/1000.0f;
  area = (0.5 * (pre_x + x) * diff_t) + pre_area;

  Serial.print(area);
  analogWrite(DAC0, area);
  pre_x = x;
  pre_area = area;
  pre_time = t;
}

Now that the question is answered please flag it as answered

You add the semicolon that is missing at the end of long unsigned int t

Amongst other things. ;)

Why have you written t = 0 here and declared it again below??
int x = 0,pre_x = 0,t = 0,pre_t = 0;

Semi Colon Missing
long unsigned int t;

Where have you declared pre_time??
  pre_time = t;

long unsigned int t

No semicolon.

Plus, make up your mind what type "t" is:
int x = 0,pre_x = 0,t = 0,pre_t = 0;
long unsigned int t;

Is it int or long unsigned int?

How can I get the code to work?

Avoid C++ syntax errors.


text:
How to store incoming serial string in arduino?
In my recent project, I am working with serial data. Till now, I'm able to receive data and display on LCD. Now, suddenly I can't get any serial data. Nothing display on LCD.
My incoming string is:
{"Action":"ONE","TPS":"0.40","MAP":"0.95","LOAD":"14"}

And my code is below:
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String response = "";
bool begin = false;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop()
{

  while(Serial.available() || !begin)
  {
    char in = Serial.read();

    if (in == '{')
    {
      begin = true;
    }

    if(begin)
    {
      response += (in);
    }

    if(in == '}')
    {
        break;
    }
    delay(1);
  }

  lcd.setCursor(0, 0);
  lcd.print(response);
}

:)   Does your LCD work? Can you print a literal value to it?  I suspect the problem is that rather than you have forgot to set begin to false before the break statement.

@CodeGorilla Yes, my LCD working fine. And already tried put that things mean set to begin to false. But, not working.

Something changed from the time the LCD worked until when it didn't - what changed? Did you reload the code? Same code/ different code? Change any wiring, even accidentally? Short circuit something? Go back and figure out what might have changed and try to undo the change. Unless it was accidental damage, you should be able to get working again.

@JRobert Nothing changed. I tried out my previous old code. Check out everything like wiring, short circuit etc. But, nothing happened.

@LookAlterno No...

Actually I can see what I think may be an issue with your code.
 while(Serial.available() || !begin)

This isn't right.  If there is no data available in the serial buffer but the first { hasn't been seen then go and read the non-existent data anyway?
Rather than try and explain what I mean in multiple comments I have put it all together and this is what I think your loop should be this:
/// This is un-compiled code, so you might have to fix some little issues.
/// bool begin = false;         // True when the initial { has been seen

void loop()
{
  while (finished == false)
  {
    if (Serial.available())
    {
      const char in = Serial.read();
      if (in == '{')
      {
        response = "";  // Blank the string
        begin = true;
      }
      if (begin)
      {
        response += (in); // Only write if within the {}
      }
      if (in == '}')
      {
        begin = false;   // Prevent any chars between } and { leaking through.
        lcd.setCursor(0, 0);
        lcd.print(response);
      }
    }
    delay(1);
  }

  delay(500); // Not sure what will happen if you send multiple {} to the LCD too fast.
}

I tried out your code and it's working fine. And now my code is working fine. Why ? I answer it.

I just switch from Arduino UNO to Arduino MEGA. And everything works fine. I know this is not a proper answer but I want to know why this happens. I don't understand why this happens? Can anyone explain me?


text:
How to start particular event for particular time using millis()?
In my recent project, I want to run particular event for the particular time. For example, If I want to Turn ON my LED for 20 Second. And rest time LED must be off. I know using delay() it is possible but If we used delay() function then that time we can't do anything. So, I tried out millis() for that. I tried the basic code for this.
The code is below:
const int ledPin =  LED_BUILTIN;

int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 5000;

void setup()
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval)
  {
    previousMillis = currentMillis;

    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    digitalWrite(ledPin, ledState);
  }
}

But the output of this is like LED ON for 5 Second and then LED OFF for 5 Second. And this thing happens continuously.But I don't want this. I just want to turn ON LED for 5 Second when I want and then LED off forever. And I tried out many logics for that somehow can't able to get this thing. Someone suggest me some idea about this.

Use an extra boolean variable. Some use the previousMillis and make it zero to tell that the delay is not active, but please don't do that. Let previousMillis be the value of millis and use an extra boolean variable.
To start the millis delay, three things are needed: enable the delay, set previousMillis, and turn the led on.
To stop the millis delay, two things are needed: disable the delay, turn the led off. There is no need to do something with the previousMillis since the millis delay will be disabled.
const int ledPin =  LED_BUILTIN;

unsigned long previousMillis;
const unsigned long interval = 5000UL;
boolean enableDelay = false;

void setup()
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  unsigned long currentMillis = millis();

  // Trigger the delay, I use analogRead.
  if (analogRead(A0) > 500)
  {
    enableDelay = true;
    previousMillis = currentMillis;
    digitalWrite(ledpin, HIGH);
  }

  // Checking the millis delay should be done in the loop.
  // This code is not inside the code to start the delay, but
  // at the same level as other code in the loop.
  if (enableDelay)
  {
    if (currentMillis - previousMillis >= interval)
    {
      enableDelay = false;
      digitalWrite(ledPin, LOW);
    }
  }
}

There are libraries that can do this. The above code is the basic way to make a millis delay. I have changed the variable "interval" to a unsigned long, because the other two (currentMillis and previousMillis) are also unsigned long. That makes it more straightforward. The currentMillis and previousMillis must be unsigned long, but it is okay if "interval" is a long.
This way of a millis delay can be used with a finite state machine. If your sketch has many states, and one of those states is to keep a fan or a motor on for some time, then you can use it. The variable "enableDelay" is probably not needed in a finite state machine, because the "state" variable tells if that specific state (with the millis delay) is active.

Thank you so much... It is working fine...It is used in many application of mine...


text:
Non-blocking analogRead
In my recent project, I'm working with the motor. I have to drive the motor for the specific time like for 2 minutes, 3 minutes, 4 minutes and 5 minutes. I already created functions for that. And motor drive based on readings taken from the sensor.
My code is below:
#define PIN_OUTPUT 6

const int kPinIN1 = 4;
const int kPinIN2 = 5;

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

  pinMode(kPinIN1, OUTPUT);
  pinMode(kPinIN2, OUTPUT);
}

void loop()
{
  Serial.println(analogRead(A0));

  if(analogRead(A0) > 100 && analogRead(A0) < 200)
  {
    motorDriveFor2Min();
  }
  else if(analogRead(A0) > 200 && analogRead(A0) < 300)
  {
    motorDriveFor3Min();
  }
  else if(analogRead(A0) > 300 && analogRead(A0) < 400)
  {
    motorDriveFor4Min();
  }
  else if(analogRead(A0) > 400 && analogRead(A0) < 500)
  {
    motorDriveFor5Min();
  }
}

void motorDriveFor2Min()
{
  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(64000);
}

void motorDriveFor3Min()
{
  motorDriveFor2Min();

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(32000);
}

void motorDriveFor4Min()
{
  motorDriveFor3Min();

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(46000);
}

void motorDriveFor5Min()
{
  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(120000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, HIGH);
  digitalWrite(kPinIN2, LOW);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(7000);

  digitalWrite(kPinIN1, LOW);
  digitalWrite(kPinIN2, HIGH);

  analogWrite(PIN_OUTPUT, 255);

  verboseDelay(120000);
}

void verboseDelay(unsigned long ms)
{
  unsigned long now = millis();
  unsigned long start = now;

  do
  {
    now = millis();
  }
  while (now - start < ms);
}

Here, I have four functions named motorDriveFor2Min(), motorDriveFor3Min(), motorDriveFor4Min() and motorDriveFor5Min() for my specific time means for 2 minutes, 3 minutes, 4 minutes and 5 minutes respectively.
So, suppose If I want to drive motor for 4 min then I have to call function motorDriveFor4Min() and for that, I have to set my reading between 300 & 400. But I can't able to do that because when my reading reaches at 100 then it starts executing another function means motorDriveFor2Min() and then continuously run that functionality. During that time I try to change the reading but nothing happens. After restating Arduino it run according to the reading.
So, I thought maybe delay() function block everything. So I replace inbuilt delay function with custom delay function. But that can't solve my problem. Then I google it out and I found out that analogRead may cause this problem. Any suggestion for this.

That is clearly a design fault. What does your analog reading represent? Are there discrete values for stopping the motor? Like <100 and >500? You could simply keep running until the reading reaches those.

In essence, all your program does is run the motor all the time. Because as soon as it has run to motor for X minutes, it immediately goes through your code again, and run for Y minutes. I think you benefit from adding a button. So that only when you press the button, the motor will run for X minutes, where X is dependent on the position of your potentiometer.

If you want to determine the length of time to drive the motor before the motor starts (as it sounds like you want to) what you probably need is a "go" button.  If you can alter your goal and instead keep reading the analog to make an ongoing decision if you want to keep driving it, that would probably be wiser - the time taken to do even a blocking analog read is short in motor terms.  Keep in mind that your system should have a non-software "emergency stop" and that you really shouldn't be using an Arduino to control anything where mis-operation would be hazardous.

In effect, right now, you have the reset button or power switch functioning as a "go" button that causes it to evaluate the (hopefully desired) analog input value you have set.

Also you should call analog read only once for your printout and decision tree and save the result in a variable.  Otherwise every check may see a different value and you could fall through satisfying none.  And change some of your comparisons to include the equals case, so that the boundary numbers like 200, 300 etc don't fall through satisfying nothing.

your code repeats unnecessarily .... you only need one motorDriveForXMin() function .... just pass the delay in an argument value ..... motorDriveForXMin(4)  ..... multiply the argument by the delay value of 1 minute inside the function ..... also your code does not check for values of 200, 300 and 400

@mystery I Here analogRead is sensor reading. Depend upon sensor reading motor run for specific time. Suppose if reading is about between 100 & 200 then a motor run for 2 minutes.

@Gerben yeah, I just added button. So that first I set my analogRead value then press button for start execution.

@ChrisStratton Yeah one button is needed for that. without that, I can't able to fulfill my purpose.

@jsotola No it's not unnecessarily. Every function's functionality is different from each other.

It's not analogRead. It's not (just) delay. It's the whole method of your program.
The way it's written you can do nothing else while driving a motor for X minutes.
You need to rethink your whole program so that it's not "run for X minutes" each time, but instead "Run the motor until the time is up" and constantly re-evaluate what the time should be.
That means:

No "run for X" functions.
No delay() functions (of any form - yours is as bad as the normal one).
A state machine to determine what should be happening when.
Constantly referencing both millis() and analogRead() to determine what state the state machine should be in or progress to and when.

Actually, that's not quite the problem.  They want to do nothing but drive the motor for several minutes.  The problem is that while they are adjusting the pot (or before they get a chance to) it takes off on an undesired reading.   It's possible the task could be re-organized to drive the motor for some period of time, and then read the analog input to decide if driving should continue - and that might be smarter, but it's not the goal that was stated.

@ChrisStratton For something like this there are many many ways of achieving the same thing. None are wrong. Either way, the underlying methodology of their existing program prevents any proper control and they need to re-think how to better do what they want.

@Majenko Thank you for clearing my misunderstanding about the delay() and analogRead(). I just find out a better way for my logic.


text:
How to set PID parameter Kp, Ki and Kd?
Right now, I'm working with Peltier module using PID algorithm. I search out on the Internet about this and so I found that there are three parameters Kp, Ki and Kd. And everyone uses the different value for that. So, they actually calibrate that value but I don't understand how?
I just use default value like Kp = 2, Ki = 5 and Kd = 1.
And here I take Input as Temperature. My normal temperature is around 25. And now I set my setpoint 20. So, according to the PID algorithm temperature must be reduced to around 20. But still, no change in temperature and my PWM is still 0.
Below is my code:
#include <PID_v1.h>
#include "Adafruit_MAX31855.h"

int thermoDO = 3;
int thermoCS = 4;
int thermoCLK = 5;
Adafruit_MAX31855 thermocouple(thermoCLK, thermoCS, thermoDO);

#define PIN_OUTPUT 6

//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Specify the links and initial tuning parameters
double Kp = 2, Ki = 5, Kd = 1;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

int IN1 = 8;
int IN2 = 9;

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

  //initialize the variables we're linked to
  Input = thermocouple.readCelsius();
  Setpoint = 20;

  //turn the PID on
  myPID.SetMode(AUTOMATIC);

  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
}

void loop()
{
  Input = thermocouple.readCelsius();
  myPID.Compute();
  analogWrite(PIN_OUTPUT, Output);

  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);

  Serial.print("Setpoint: ");
  Serial.print(Setpoint);
  Serial.print("\t");
  Serial.print("Input: ");
  Serial.print(Input);
  Serial.print("\t");
  Serial.print("Output: ");
  Serial.print(Output);
  Serial.print("\t");
  Serial.print("Kp: ");
  Serial.print(myPID.GetKp());
  Serial.print("\t");
  Serial.print("Ki: ");
  Serial.print(myPID.GetKi());
  Serial.print("\t");
  Serial.print("Kd: ");
  Serial.print(myPID.GetKd());
  Serial.print("\n");
}

And my output is like:
Setpoint: 20.00 Input: 24.50    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.50    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.50    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.50    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.50    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.50    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.50    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 24.75    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.00    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.50    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00
Setpoint: 20.00 Input: 25.25    Output: 0.00    Kp: 2.00    Ki: 5.00    Kd: 1.00

Now here I use MAX31855 module for measuring the temperature which takes as Input here.
MAX31855 Module:

I think that may be my Kp, Ki and Kd are not perfect for my system. So, maybe this cause problem means not the proper value of Kp, Ki, and Kd. Can anyone give some suggestion how to set this value of Kp, Ki, and Kd? Or there is something else which caused the problem for that. Suggest me.
And here I'm using DC motor driver(20A) for driving the Peltier Module.

Sorry Hasan, I cannot find your other post where I added a comment, which was about this problem but with more noisy measures. Did you cancel it?

@frarugi87 Yes, I deleted that post because I thought that post was not cleared as I want. But now my problem is solved. And thank you for your answer.

Well, it was a different question than this, so I think you should've posted an answer on that topic. How did you solve the problem you had? Was it due to noisy measurements? Or wrong setup?

@frarugi87 Ok, If you think so then I will definitely post it. Actually, both questions' motto is same. And as you see that noisy measurement is only due to some loose connections. After I tried out again and I got the proper fine result.

No, I think that reposting the previous question is useless; in any case so it was just a loose connection?

@frarugi87 May be possible. But it happened only one time. So, after that no issues. I can't say exact reason why that noisy reading I got that time !!!

PID algorithms basically change the output to approach the setpoint. Now in your case you have a setpoint of 20 and an input of 24.5. Thus the algorithm thinks it needs to turn the output off so it can "cool down". This would work for a heater.
However since your output is a cooler you need to specify "REVERSE" rather than "DIRECT". This tells the PID module that the output needs to be higher if the input is higher than the setpoint.


text:
Two sensors on one input
I got this question from my teacher the other day and I can't figure it out:

If you have two sensors from two different outputs but want them to go into one input, what do you need, and how can you read the input?

In short, the project includes an Arduino Uno with two ultrasonic sensors.

Well, i guess one correct answer would be "Multiplex",  you'll have to switch the outputs inside the loop(). One output have to be HIGH during the other one is LOW, so you always get the input from one sensor only. Ofc you'll have to check which sensor is active to get the correct sensors signal. Another way would be using analog input and different resistors for each sensor. So you get different voltage signals from the sensor.

I think those unit pull low to send a signal. So you could use just two diodes. Though I'm unsure where the out signal is going, as most ultrasonic units have only one SIG pin to use as both input and output.

If you multiplex then you need another pin to control which multiplexer input is going to be selected. Please state which sensor you are planning to use. Without knowing any more the "two diodes" answer seems to be the most likely.

There are two basic solutions to your problem, an active one and a passive one, and which is best (or will even work) depends on the rest of your setup.
The active solution requires a device called a multiplexer.  This is basically a switch and it selects one of its inputs to route through to its output, so it can be used to connect your input pin to the output of one of the sensors.  It requires an extra IO pin, though, so is pretty pointless as you could just use that IO pin as an input from the second sensor.  It does mean, though, that both sensors can be active at once and you just select one to read the output from.
The passive solution is called open drain or open collector (if you are using TTL not CMOS terminology).  This means you convert each of the outputs of the sensors into a switch using a transistor (NPN BJT or N-Channel MOSFET) to connect your input pin to ground.  When then transistors are off the input pin is pulled up through a pullup resistor (could be internal or external to the IO pin).  When one sensor's output activates it turns on the transistor which then pulls the input pin low.  This means that you can only have one sensor active at a time, so they have to be triggered by separate output pins.

Open Drain is how things like I2C support multiple devices on the same bus without any voltage conflicts.

Isn't it right that the Multiplexer is not needed as you can switch the outputs by yourself in code?

@nouseforname As long as you have separate outputs to control the sensors then the second (passive) option is for you. That is why that's the option that I put most detail into.  A multiplexer may be needed if the signal is analog though (analog mux) since the OD won't work for that.

understood, i am also new to this and just learned i can do the "multiplexing" in code...thats why i asked. Your solution seems to be  the very perfect one for this case here

Is it a diode in a parallel with the MOSFET?

That is called the body diode and is integral to all MOSFETs.

As I know the MOSFET, then input (1) is gate, output (2) is source and ground (3) is drain?

No, 2 is drain, 3 is source.  The source always connects to the most common point (ground in this case) since it's the voltage difference between the source and the gate that controls the MOSFET - in this case that's the voltage difference between the gate and ground.

I think the last one is the right one though I can't figure out how to implement it in my figure

The outputs of your two ultrasonics go to the INx pins on the schematic.  The OUT of the schematic goes to the IN on your drawing.  The Vdd is the +5V pin of the Arduino and the ground symbols go to the GND pin of the Arduino.

Let us continue this discussion in chat.

Assuming IN1 goes HIGH, there will be a low impedance path between OUT and ground. Won't this cause excessive current to flow out of the OUT pin? Or is there a resistance to the right hand side of the OUT that isn't shown? And if there is, what would happen if the user erroneously set the pin to be OUTPUT (either through real error or because the previously loaded sketch had it set up this way and he's only just plugged it in to write the real sketch, if you know what I mean.)

If you have two sensors from two different outputs but want them to go
  into one input, what do you need, and how can you read the input?

If you want your teacher lose his mind answer his question with this:
What I need? :)

A wire

The solution is to use one trig for both ultrasonic sensor and two echos.
or one echo and two triggers.
ultrasonic sensor sends the pulse > pulse back > now echo pin is connected to second sensors trig > the Second Ultrasonic sensor sends the pulse then starts listening. When the second ultrasonic echo back, it sends to other Arduino pin, reverse it if you want it on one input pin :)
#define trigPin 6
#define echoPin 4
#define echoPin2 7

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
   pinMode(echoPin2, INPUT);
}

void loop() {
  long duration, distance, distance2;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(20);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  duration = duration + pulseIn(echoPin2, HIGH);
  distance2 = (duration/2) / 29.1;
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println("cm");
       Serial.print(distance2);
    Serial.println(" cm");
        Serial.println("HHH");
  }
  delay(500);
}

that's it.

I ran into the same question, except I wanted to put 8 of the HC-SR04 sensors on pro-mini.
I used an I2C pin expander for the triggers, and an octal OR/NOR chip to multiplex the return.
Library, examples and pictures
https://github.com/arielnh56/SonarI2C
http://redhunter.com/blog/2016/04/28/sonari2c-multiple-hc-sr04-sensors-on-arduino-i2c/

The OP does not specify whether the focus is on hardware or software.
So I will presume that what the professor might looking for is a solution using minimal circuitry; as close to the diagram as possible.  Thus, the solution would be implemented in software.
Given all that, I'd propose that the trigger signal be sent out on sensor 1, and the reflection measured at the receiving pin.
It is time-gated (the time for the sensor to react to an object at maximum range).  If detected, then set a variable saving the distance measured on sensor 1.
Then the same could be sent from the second sensor's trigger pin.  And if there is a reflection within the time-gate then that can be recorded in another variable.
It would require creating two instances of the ultrasonic sensor, and they would just happen to share the same receive pulse pin.

This solution only actually uses one pin, but only works with simple things like push buttons (which are either open, or closed).
Connect a (different) resistor in series (end-to-end) with each switch. Connect the loose end of each resistor together to +5V. Connect the loose end of those two switches together, then via another resistor to ground. Where the two switches meet, connect them to an analog pin on your Arduino.
For example, you might use a 20k resistor with button A, and a 10k resistor with button B, and a 10k resistor connected to ground. They should be pretty close to the same value, and at least 1k each.
Use the ReadAnalogVoltage sketch to measure the voltage with different combinations of button presses (no button pressed, A, B, A+B), then, in your final sketch, you can compare the value read with the values in this table - pick the closest one, because actual readings may vary slightly. For the resistors above, you should get about: (no button = 0v; A=1.7v, B=2.5v, both 3v). Sort these numerically (which in this case they already are), and work out the values exactly between each pair (up to 0.85 is closest to 0=> no button; else up to 2.1=> button A; else up to 2.75 is closest to B; otherwise, both are pressed.
The circuit described looks like this:

The wire leading off to the right goes to the analog pin on the Arduino. Switch A is on the left.
The results can be used either in a table, with a loop, or in an if/else if statement (I used this technique on a 12-key keypad, so the list was a lot longer).
Read up about voltage dividers https://learn.sparkfun.com/tutorials/voltage-dividers and, for both buttons being pressed at the same time, resistors in parallel https://learn.sparkfun.com/tutorials/series-and-parallel-circuits

A SPDT switch would fit nicely in your diagram where the question mark is.

Try the above logic use a 555 timer with  C1: 10uF, R2: 300k and R1: 30k for 1.1 sec switching time,now for approx every one second data from USS1 goes to SIN(Arduino IN) when the timer OUT is high and  similarly when timer OUT is LOW signal from USS2 goes to SIN(Arduino),,,
But you will not be able to know from which sensor is the output coming.
If you would like to know from which sensor the output is coming you can just add one INVERTER to one of the branch so so both the sensors will give different states i.e one will return HIGH and other will return LOW
hope this helps
Edited:Please note 555 timer design part is not complete ,,i am just giving an idea :)

The question is two Ultrasonic data get input on one.  Its simple.  You just need two IDs.  Creat a IDs of each sensors.  You can use I2C bus too.  You need to hub who keep the two input in raw.  And than digitally write with address and than do codding for read the data.  Howz my idea guys?

Welcome to Arduino Stack Exchange.  Please take the Tour at https://arduino.com/Tour to get the most out of this site.  FYI - Normal ultrasonic detectors do not work on I2C - they wrok by pulsing a signal pin then monitoring an output pin.  The library measures the time and infers the distance.


text:
Problem assign float to an embed class within the Linked-list libary
I have successfully implemented some code which uses a linked-list.  Everything is working, except assigning a value to a float within the embeded class.  When I run the code below, I get the expected behavior, a flashing LED for 10 secs then LED turns continuously ON, and I also get the debug messages I expect.  However, when I comment the marked line to assign a value to the float, it still compiles, but the LED does not flash as expected and I get complete rubbish from debug.  I am using codebender on Chrome, and I have tried Firefox (both given same results).
Main Sketch https://codebender.cc/sketch:175995
Example of library working https://codebender.cc/sketch:176008
Can anyone help?
typedef void(*GF)(void);

#include "LinkedList.h"

class CsC {
    public:
        float PerS;
        GF FunctionToCall;
};

LinkedList<CsC*> TaskList = LinkedList<CsC*>();

void LEDON()
{
    digitalWrite(13,HIGH);
}
void after(float interval, String intervalDescription, GF func);

void after(float interval, String intervalDescription, GF func)
{
    float multi = 1;
    if(intervalDescription == "mins") multi *= 60;
    float delayMS = multi * interval;
    CsC *c;
    //Error if either of these lines uncommented
    //c->PerS=10000;
    //c->PerS=delayMS;
    c->FunctionToCall=func;
    TaskList.add(c);
    Serial.print(".");
}

void setup()
{
    Serial.begin(9600);
    pinMode(13, OUTPUT);
    Serial.println("Start write task list");

    after(35,"secs",LEDON);

    Serial.println("Done");
    Serial.println("Start prog");
}
void loop()
{
    Serial.print("List=");
    Serial.print(TaskList.size());
    while(TaskList.size()>0){
        CsC *c=TaskList.shift();
        long timeout=millis()+10000;
        //long timeout=millis()+((long)(c->PerS*1000.0));
        while(millis()<timeout){
            //To indicate it is running, and to save time, I have used a delay here
            digitalWrite(13,HIGH);
            delay(250);
            digitalWrite(13,LOW);
            delay(250);
        }
        c->FunctionToCall();
    }
    Serial.print(".");
    Serial.println("complete");
    while(1){}
}

Have you considered allocating memory for c?

I thought in c++ i did not have to allocate memory.  If I did allocate memory beforehand, how would I do it?

With the new operator. And you deallocate it with the delete operator.

My mistake, I will try tonight

One possible error is a memory leak as you did not allocate the memory to the class
Try
CsC *c=new CsC();


text:
Underwater positioning system (swimming pool)
I'm making a few experiments with a quite simple rover car I made using Arduino UNO and a few spare parts. Just for the heck of it I made it waterproof and now I want to toss it in my pool to make some underwater exploration. Maybe I'll fit some scrubers under it to make it easer to clean the floor.
My problem is: my rover navigates on its own, avoiding walls and objects using an ultrasonic sensor. But underwater the speed of sound goes up, and different qualities of water make it even harder for this system to work. Sometimes the pool is full of particles, and the scruber will probably worse the water quality around the robot.
My question is: what kind of system is better to navigate underwater, simply avoiding walls? The current behavor (on dry ground) is to turn to the right and go on when it finds a wall, I would like to keep this behavior, but underwater. As it's a simple toy, I'm hardly willing to spend a hundred bucks on a fancy laser proximity sensor, neither I need to map the entire pool with a single pulse, it should be a simple wall avoiding system.
Thank you!

bumberswitches (i.e. limit switch with long stiff wire attached).

Infrasound could work. Same as ultrasound but low frequency audio instead.

Infrasound works well on large distances. I doubt it's of any use inside a regular pool.

Try it out with the ultrasonic system.  Other than the speed issue (which will result in things appearing closer than they are) the ultrasonic system should work fine in the water, even with floating particles.

@IgorStoppa You don't have an Olympic size pool in your garden?!

@Majenko: I suppose with Olympic you refer to the real thing, as in "swimming place near Mount Olympus", colloquially known as Aegean Sea. Because that's what would probably make the use of infrasounds possible. No, I don't have that in my garden.

@IgorStoppa Imagine the pool parties you could have...

@IgorStoppa Also, just because infrasound has a large range doesn't mean it's useless for shorter range. It doesn't travel any faster than ultrasound, it can just travel much much further. It still echoes off close things. The only thing you have to watch is that your sound production period is shorter than the period of your shortest desired echo, and with infrasound that is limited by the wavelength of you want to produce at least one full cycle of the audio signal. So you choose your frequency to suit. You may well end up with a frequency that isn't strictly infrasound, but sure isn't ....

... ultrasound. Low audible frequencies, for instance . The theory of operation is just the same

Have a look at this, form the Robotics site, perhaps: http://robotics.stackexchange.com/questions/7564/how-to-localise-a-underwater-robot

How about a tilt switch?  The bottom corners of a pool should allow the car to ride up the wall a little, when it tilts past 5 or 10 degrees, turn it left.....


text:
Arduino, lcd 16x2 and UTP cable shows gibberish text?
I'm using an arduino uno, and an 16x2 LCD that is connected to the arduino uno with a 1m long UTP cable to transmit data and as well power the LCD screen.
I used to test my code and my wiring with short wires and everything worked perfectly, as soon as I used the UTP cable to move my lcd a bit away from the arduino, the same code and wiring doesn't work, all i see is gibberish text (nonsense characters on the screen).
I have other components in the circuit, but I have disabled them all and checked again (quadruplechecked) everything, including the LCD alone, but the problem remians. I also gave the lcd a whole separate powering line, as I thought it could have run low in energy bcs of other components using the same 5v line.
Anyone has any idea of what could the problem be? Has anyone tried connecting components with UTP cables? Should I maybe use STP instead?
Thanks!

What is the protocol you are using? Which wires are you using for what function?

possible duplicate of 2,5m cable too long for LCD connected to Arduino UNO?

Please try using a multimeter and check the voltage in the + and - wires. Also try wrapping the wires in tinfoil, it should reduce the interference.

Until we know what protocol you are using (I2C? SPI Shift registers? UART?) and which pins you are using on the UTP cable (not all pins are equal - it's the way the wire is made) we can't make any serious recommendations.  There are specific things you can do in specific circumstances (decrease pullup resistance for I2C, use the pairs of the UTP properly as pairs with signal/ground, or even generate an LVDS for maximum performance).  All depend though on what you are doing and using now.

This might be of some help assuming that we are talking about I2C wiring; http://electronics.stackexchange.com/questions/106265/maximum-i2c-bus-length

Do you have access to a scope of some sort? It would also help us help you if you could add a link to the display you're using (or at least name it specifically).

Is the cable shielded?
Have to performed continuity test on all leads of the cable to ensure there no break internally that could be causing an issue, or a short?
What is the impedance of your total length of cable?
These sorts of checks will help you further narrow down the issue. If you are certain your wiring is correct, then the most probable issue is either a hardware failure (continuity test)
a hardware limitation (Too much resistance for accurate data travel)
Improper Hardware, unshielded wires can be subject to crosstalk, or signal corruption/distortion due to external signals interfering.


text:
Execute Code sent over Serial
I was wondering if its possible to send code to the Arduino, and then have it execute this code.
What I'm trying to do is use an Arduino Mega with a bunch of stuff connected to it send code to an Uno with a TFT LCD display to do whatever the Mega tells it to do with the Adafruit GFX Library.  I want to add things to this 'system' gradually so I want the whole program hosted on the Arduino Mega, and a minimal amount of code on the Uno.
Sorry I'm really new at this so if its not possible at all let me know!
Thanks in advance,
-Will

Just send the GFX commands (and arguments) as text using serial, and have the UNO parse this text and call the appropriate GFX function. But why would you need two micro controllers? Can't you have the Mega do the TFT stuff too?

Sending code over serial is what the bootloader does. However this is a once-off for a given moment. It doesn't interactively execute code. You could send commands over serial to a device with a LCD display on it (eg. display "Hello, world").

No, it's not possible as you describe it.
The Arduino's main chip, the ATMega328p, is what is known as Harvard Architecture.  This means that the Flash memory and RAM both occupy completely separate memory address spaces.  The CPU in the chip is only able to fetch its instructions from the memory space the Flash is connected to (the Instruction Bus) and not the memory space the RAM is connected to (the Data Bus).  This means it can only run instructions that are in Flash and not RAM.
It is possible to re-program the flash on the fly - after all, that's what the bootloader does, and while the actual act of reprogramming flash is fairly trivial, generating the instructions in the right way is far from trivial.
There are other options though.

Use an interpreted language.  I believe there are versions of BASIC available for the Arduino that would allow you to upload a program through the serial port and execute it.
Define a protocol (or use an existing protocol) to send pre-defined control commands to the Uno.  Firmata might be of use here.

Thanks for your help, that helps out a lot!  Theres not to many functions in the Adafruit GFX library, so I could probably create a protocol to do all of what I'm looking for... Don't know why I didn't think of that.
Thanks so much for your help!
-Will


text:
How can I configure Arduino after programming it (for post upload wifi configuration)?
I would like to make a device that can take a photo, and send it to a website over wifi. I'm using an Arduino Uno, a ArduCam OV2640 module, and ESP8266 Serial WIFI module. Eventually I'd like to take it off the board as a stand alone project for permanent use.
The wifi works fine, but requires a serial communication to configure. I would like to make it so that I can plug the device into a computer (via something like micro usb), change the WIFI settings, and save those settings for future reboots.
If there anyway I can do this with an Arduino interface? If not, what could I use instead?

There are firmware versions for the ESP8266 that will try to connect to wifi. And if it can't it will create an access point for any wifi device to connect to. After that you can load a webpage on the ESP that enables you to change the WiFi settings. (I think something like this  one)

I like Gerben's suggestion about putting the ESP8266 into Wireless Access Point mode and then providing access to your configuration settings via a web interface.  I've been dealing with the same question myself and this might be a workable solution.  The only downside is the amount of code required to get an ESP8266 to function as a WAP, provide a web-based UI, switch between configuration and running mode, etc.
Another idea that isn't as elegant, but would require a lot less code: Just store your configuration on an SD card, and add an SD card to your project using a separate board or shield.  You could edit the configuration by plugging it into a PC and editing the configuration file, then plug the card into your project which would read its configuration from the SD Card.

I had no idea that I could use the ESP8266 as an access point. I'll give that a try, but the backup idea works quite well for this project, thanks.


text:
Power saving configuration of unconnected pins
By default, all Arduino (ATmega328P) pins are configured for input without the internal pull-up enabled. This default seems to come from the AVR microcontroller itself.
When it comes to saving power - is this an optimal configuration for unused (and thus unconnected) pins?
Section 14.2.6 Unconnected Pins of the ATmega328P datasheet (page 88) recommends to configure pull-ups in order to save power:

If some pins are unused, it is recommended to ensure that these pins have a defined level. Even though most of
the digital inputs are disabled in the deep sleep modes as described above, floating inputs should be avoided to
reduce current consumption in all other modes where the digital inputs are enabled (Reset, Active mode and
Idle mode).

The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. In this case,
the pull-up will be disabled during reset. If low power consumption during reset is important, it is recommended
to use an external pull-up or pull-down.

So I'm tempted to call something like
for (uint8_t i = first_unused_pin; i < 20; ++i)
    pinMode(i, INPUT_PULLUP);

during setup.
Although, I don't understand where an increased power-consumption would come from when the INPUT pin is unconnected and no pull-up is active. I mean, since the pull-up is connected to VCC, there definitely is some current flowing, whereas without the pull-up I don't see where current would flow, since the pin is unconnected ...
However, Nick Gammon reports in his extensive article on power saving techniques (Section Configuring pins as inputs/outputs, Sketch D) an increased power consumption when 6 unused pins are configured as inputs with internal pull-ups attached:

All pins as inputs, and LOW (in other words, internal pull-ups disabled): 0.35 µA (same as before).
All pins as inputs, and HIGH (in other words, internal pull-ups enabled): 1.25 µA.

So the datasheet's statements seem to conflict with these results.
Is this an error in the datasheet are am I missing something?

Re “since the pull-up is connected to VCC, there definitely is some current flowing”: some current flowing where? For current to be able to flow, there must a complete path from Vcc to GND. The pull-up connects the pin to Vcc, what does connect it to GND?

@EdgarBonet leakage current that is. See also page 323 of the data sheet where max ' Input Leakage Current I/O Pin' is specified as 1 µA.

FWIW, "Input leakage current". https://electronics.stackexchange.com/a/325619/165322

Similar question on electronics SE: How should unused I/O pins be configured on ATMega328P for lowest power consumption?

Current is consumed when an input pin switches from HIGH to LOW or from LOW to HIGH. An unconnected "floating" input pin can change randomly depending on the local environment (EMI, noise, etc). That is unpredictable. The "it will consume more" is erroneous - it should be "it could consume more". The could is important, as I mentioned, it is unpredictable. By pulling up or down it is no longer unpredictable, as you have a defined steady state, and the input pin will not switch randomly.
Yes, you will get some leakage current through the pullup and the low-side MOSFET, but it is a defined predictable amount which you can incorporate into your design. If you want to reduce it then use larger external pullups (or pulldowns) to reduce the leakage current (note: using too large will start to encroach on the "floating" teritory again).
But when you're dealing with such small currents you're usually below the self-discharge equivalent current of your battery anyway, so saving a few nA isn't going to actually make the slightest bit of difference.

ok, yes, these are small amounts - re: '[..] so saving a few nA isn't going to actually make the slightest bit of difference'. Perhaps I'm missing something here, but isn't such leakage additive? I mean the self-discharge of a battery I have in any case - and on top of that I have to account for any additional leakage current, right? Also, what would be the worst-case that could happen when no pull-up is configured/attached to an unconnected input pin in terms of power usage (or something else)?

@maxschlepzig It's not quite as simple as that, since self discharge isn't a current per se, it's an effect of the chemistry of the battery. For example an NiMH can lose 30% of its charge in a month (NiMH is one of the worst for self discharge). But of course what current you draw is drawn from what is left in the battery, which is constantly depleting, and the less you draw the longer it will last, but when you've got (as in the NiMH example) about 3 months of potential runtime anyway trying to save enough power to last 6 months just isn't going to happen.

You could try feeding a high frequency (few MHz) signal into all the unconnected pins when set as INPUT and measure the sleep current to see how (if) it increases.

That's a great idea Majenko!

Although, I don't understand where an increased power-consumption would come from when the INPUT pin is unconnected and no pull-up is active.

This part of your question already has 2 answers, so I'll just answer the "power saving part".
The data sheet says "If some pins are unused, it is recommended to ensure that these pins have a defined level.". Configuring them with pinMode() to OUTPUT, then driving them LOW using digitalWrite() is perfectly acceptable, and MAY offer the greatest power saving / noise immunity of all.
If you look at "14.3 Alternate Port Functions" on page 89, you get a glimpse of the internal digital logic circuitry. When set to OUTPUT, the internal circuits provides a low impedance path to ground to sink current. What ever part of the internal circuitry that was "oscillating due to a floating input pin", causing the extra power consumption, is now connected to ground, or it's input is ignored, or how ever Microchip did it.
When you follow the I/O pin on Figure 14-2, it shows the INPUT_PULLUP circuitry at the top of the diagram, followed by the tri-state control lower down, then the SLEEP circuitry comprised of an analogue switch OR transmission gate if you prefer, inverter gate and N channel FET. When the Arduino is in some sleep modes, it "disconnects" the pin with the analog switch, and also grounds the Schmitt trigger input at the same time. What would be cool is if you could write "Arduino code" in the IDE to toggle this ON/OFF programmatically.

From the data sheet:

14.2.5 Digital Input Enable and Sleep Modes
As shown in Figure 14-2, the digital input signal can be clamped to ground at the input of the Schmitt Trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller in Power-down mode, Power-save mode, and Standby mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to VCC/2.

The bottom line is, you don't want unused pins set as INPUT (Tri-state (Hi-Z) mode). See "Table 14-1. Port Pin Configurations".

My earlier testing would seem to confirm that setting the pins to OUTPUT and LOW probably has the lowest power consumption. In my tests setting them to INPUT also had low consumption, but that would probably vary depending on what is going on around the pins.

Ok - one issue with that approach (setting an unconnected pin to OUTPUT+low) is perhaps the behavior during reset, i.e. where the pin is set to INPUT for a short time. So, connecting external pull-ups to unused pins (and keeping them as INPUT) would help with that. However, I guess if you don't reset much, the savings (of OUTPUT+low vs. INPUT+pull-up) offset the potential 'waste' during reset by a large margin. I don't know, connecting all unused pins to external pull-ups feels a bit excessive.

@maxschlepzig - I don't recommend connecting the unused pins to anything. Are you commenting on something I've written in my answer, or on the comment above yours made by Nick Gammon?

@maxschlepzig - Page 619 of the data sheet may shed some light on how much current is used during the re-set process. See: 35.12 Current Consumption in Reset and Reset Pulsewidth

@VE7JRO I didn't say that you did. In my comment I just wanted to discuss the trade-offs of the method described in your answer (i.e. OUTPUT+low). So reset-behavior is - arguably - its only drawback, AFAICS - so, I just mentioned INPUT+external pull-up since it's the only alternative that yields a defined level also during reset. What I mean with reset behavior is this: during reset an unconnected pin (previously set to OUTPUT+low) is reset to INPUT until setup() runs. During that time-window of 1 s or so the level isn't defined, yet. 35.12 doesn't deal with that scenario, right?

@maxschlepzig - Have you tested to see if those inputs are floating for one second? If they are, then I would say the answer to your question, is in your question - "If low power consumption during reset is important, it is recommended to use an external pull-up or pull-down.". The data sheet also says not to tie the pins directly to power or ground because of damage "IF" you happen to set the pins to input/output with "code" by mistake. If there is no possible way for you code to set the un-used inputs to VCC or GND, then connect them directly to ground.

@VE7JRO no, I haven't tried to measure those inputs, yet. See also Majenko's answer and comments on how measuring the consequences of an unconnected INPUT (without pull-up) isn't exactly trivial.

@maxschlepzig - In that case, just do what the data sheet recommends.

The theory here is that an pin without a pull-up will probably float somewhere around the switching voltage. A bit of noise from the surroundings or whatever might push the pin up or down slightly, which will cause the internal circuitry to "flip" from high to low (or vice versa). All that flipping consumes quite a lot of power. The little tiny trickle from a pull-up resistor is so much smaller than the "flip cost" that it's worth using them.
I should also mention that it's very hard to test for a floating pin's consumption of power. Whenever you test it, you'll find it behaving very nicely, but as soon as you put it into a proper application it'll go crazy and won't work anywhere near your expectation. Putting in pull ups avoids this uncertainty, and lets you work with whatever the power consumption is when they're present.
I don't have the results any longer, but a while back I tried measuring the power consumption of the Arduino in various "idle" modes. The theory and practice did't match up terribly well.
It's possibly worth doing some tests, but IIRC, the lowest power setup was to set all pins as inputs and pull them low. In practice that's a lot of work to arrange, so setting them as inputs and using the internal pull-ups works nearly as well.
What you'll also find is that almost anything else will save far more power than the little trickle in the internal pull-ups. Here are some guides which might help:

https://learn.sparkfun.com/tutorials/reducing-arduino-power-consumption/all
https://www.makeuseof.com/tag/arduino-power-saving-tips/
https://docs.arduino.cc/learn/electronics/low-power
https://arduino.stackexchange.com/a/50734/26212


text:
What is the best board for setting up an SSH protocol to an Arduino?
I currently have a project using an Arduino R3, set up across the room from my computer. This has become quite annoying, as every time I want to push something to the Arduino I have to get up and move either the computer or the Arduino to another location, plug it in, and hope my code works the first time, lest I have to repeat the test over and over again. I am trying to set up an SSH server between my Raspberry Pi 2 and computer so I can just push new sketches over SSH, however, I use my Pi 2 for other projects occasionally and want to purchase a second board specifically for this purpose. Is there a good, cheap, board with wifi built in (besides the Pi 3) that I could use for this? Any suggestions?

How is SSH helping achieve your goals?

https://hackaday.io/project/9931-wireless-arduino-uploading-using-esp8266

@Gerben I don't see any reference to SSH on that page.

@NickGammon simply that I could create sketches on my computer and upload them with an ssh connection to whatever board is hooked up to the arduino, rather than unplugging either device and walking across the room every time I want to upload

SSH is a secure (encrypted) shell. Why do you need to encrypt an upload from one part of your room to the other?

@NickGammon I don't, it just seemed like the easiest way to link the two terminals, and I have a friend who did it and said it works fine for him.

Sounds like you want an Arduino Yun instead of an Uno.  Or a Dragino Yun Shield that turns your Uno into a Yun.

Yeah I confirm. I did some work recently and the Arduino Yùn Shield could do the job. You can push sketches via Wifi and run ssh commands. I add performance problem, but otherwise it works like a charm.
https://www.arduino.cc/en/Guide/ArduinoYunShield

If you get it working on the Pi2, could you just drop in a Pi Zero ($5) and a cheap USB network adapter ($2)?
Note that your question title asks for "best", but you don't define your criteria.  Reading between the lines I suspect "cheapest and adequate" is what you mean.

You could swap out the Arduino for a ESP012, not sure it meets your I/O needs. The new ESPs support over wifi firmware uploads.


text:
error: too few arguments to function 'char* itoa(int, char*, int)' byte blockcontent= itoa(order); ^ In file include
I have this statement in my Arduino code :
 byte blockcontent [16] = itoa(order);

and it gives me an error saying:
"Too few arguments to function 'charitoa(int,char,int)'. Even though I've looked for the documentation of itoa function and I found that it accepts one input argument.
Can anyone help me fix this error?

Where did you find this documentation, out of interest? The very first hit I get with Google shows 3 arguments: char *  itoa ( int value, char * str, int base );

@NickGammon https://stackoverflow.com/a/5590395/539490

That "reference" is just a question on Stack Overflow. Underneath that question is the comment: How does option 1 even work for you at all? It's my understanding that itoa() takes three parameters - Questions are often asked because people are unsure about what they are doing.

itoa requires a minimum of 2 arguments.
Reference: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaa571de9e773dde59b0550a5ca4bd2f00

Thank you, but is it possible to set an array pointer instead of character pointer?

You can probably set a char pointer inside an array of char pointer yes if that is what you mean.