text:
What is the best arduino board for a robotic arm?
In my university we need to buy arduino boards and kits to build a moving robotic arm, that moves up and down and clockwise in a specific degree (almost like humans's).
So, what's the most suitable arduino board to build this arm?
I suggested to use the basic UNO board, but we may need to use relays (for example) if the power source is 12volts. So there is should be a better one.
My regards.

There is no Arduino that runs on 12v. To power higher voltage motors you'll have to learn about transistors. The question of which Arduino to use depends on how many input/output pins you need and the form factor. If you need lots of pins then go with the Mega or Due. If you don't need a lot of pins and size doesn't matter then go with the Uno. If you want a small size go with the Nano or Mini (these are harder to prototype with).

Thank you. I thought that mega can run on 12V. It's their (the university staff) to make or find the transistors.
We will see if UNO is suitable.
Thanks again.

@Jerry The UNO does run on 12V. It dissipates lots of power but it does run on 12V.

I'm sorry. I misunderstood the question. Doesn't it technically accept 12v power, but "runs" at 5v?

@Jerry yes, that's correct. However here I think the question is mixing power supply for the controller and power supply for the actuation. See my answer below.

This attitude that part of the problem is the staff's job, and that you will somehow select the controller in intentional ignorance of that, is going to cause untold headaches, delay, and team conflict in your project - if it doesn't ultimately cause you to abandon the effort unfinished.  You all need to sit down together, define the problem, and figure out the constrains which that imposes on each system, and the inter-relation between the decisions made for each component.

If you buy something like an Uno or a toy robot arm now, accept that you are doing it to learn about the issues (which can indeed be a good idea when you have no perspective) but be realistic that it is not necessarily going to be part of the final implementation, and be prepared to change based on what you learn.

I am voting to close this because a question like "what is the best Arduino?" is likely to have a lot of different answers, mainly opinions rather than facts. In addition, there is no real criteria for making a decision, such as size, cost, complexity of the program, and so on.

If you are hoping to drive the arm straight from the Arduino, that's not going to work.
What you should do is:

Define the maximum weight and size of the load your arm will carry.
Define expected precision and speed of the movements.
Count the Degrees of Freedom (DoF) your arm will need (1 DoF = 1 simple joint)
Figure out size and materials of each part of the arm
Calculate the torque required at each joint (yes, you need some basic physics calculation)
Identify the motors you want to drive (DC are inexpensive but not very well suited for this, without lots of additional control logic & HW - stepper motors are better, but they still do require some additional effort - servos are the easier way but they are a bit more expensive)
Define the requirements for both the micro controller and the power supply, based on the previous choice.

If you can refine your question, based on the few points I sketched, you will get ahead much faster and with less risk later on to have to backtrack and re-design something.
You might have already answered some of those steps, then I suggest you list here your choices.
Similarly, if you are referring to some link you found (instructables, etc.) please post it.
As reference, hobbyking has an extensive catalog of motors and power supplies. You can find the same items also on ebay, but hobbyking can be used at least as reference for various specs (power, torque, weight, etc.).

Thank you for the answer.
Can we use something like 'arduino motor shield'?
these physics calculations is the staff job, they asked me the board and kits that can do this work.
They want something like this Robotic arm on amazon
I did not find any instructions that suitable for this project.

@HorizonDragon If the "staff" haven't specified the kind of information Igor has mentioned then you cannot do the job properly. Go back to them and ask them for more detail so you can know what kind of power is being expected.

@HorizonDragon that link you posted would be even scarier for me :-) because it relies on levers to perform combined movements, instead of having a motor at each joint. It's an approach pulled out by kits that want to stay on the cheap side and has the advantage of being lightweight. The drawback is that even if you have apparently several dofs, in practice they have mechanical constraints on which movements they can perform and are not so easy to control.

@HorizonDragon something like this [1] might be easier to deal with, albeit more expensive.  [1] http://www.ebay.com/itm/1-Set-6DOF-Aluminium-Mechanical-Robotic-Arm-Clamp-Claw-Mount-Robot-Kit-/271968122257?hash=item3f52903591:g:tCQAAOSwosFUVJ-~

Best answer is Arduino Uno because it is enough for your application.
But all Arduino are works on 5 volt or 3.3 volt.
For operating 12 volt devices use transistors or MOSFETs.

If you're going to use transistors/mosfet I would say arduino Nano plugged into a breadboard is easier to use. Or use an Arduino Uno with a motor driver board. (But I think it's better not to since they are limited in the amount of motors they can drive, and you'll be very likely driving servo's, not DC/Steppers).


text:
How to simulate delay() to debounce mechanical button using millis()?
Im trying to use the millis() function as a replacement for the delay() function in order to debounce a mechanical button. This is for an electric drum kit I am building. Im using a teensy Arduino to send MIDI signals from the drum pads to an external music program. The mechanical button needs to be responsible for cycling through five different states which change the MIDI signal sent from each pad, thus changing the sound, as well as lighting up one of five LEDs on my drum pad so I know which state i'm in.  However I cant use delay() to debounce the button because that effects the efficiency of the drum pads, with some hits not being registered, latency etc.
Im trying to debug the code by just getting the LEDs to light up correctly when I press the button. This was the original code I wrote with the delay() function. This worked perfectly to debounce the button, but messed with my drum pads:
int but = 12;
int led0 = 7;
int led1 = 8;
int led2 = 9;
int led3 = 10;
int led4 = 11;

int ledCase = 0;
int butState = 0;
int oldButState = 0;

void setup()   {
pinMode(led0, OUTPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(but, INPUT_PULLUP);
}

void loop()    {

   oldButState = digitalRead(but);
   delay(10);
   butState = digitalRead(but);

   if (butState != oldButState && butState == LOW) {
     ledCase += 1;
     oldButState = butState;
   }

   if (ledCase > 4) {
    ledCase = 0;
   }

   Serial.println(ledCase);

switch (ledCase) {
case 0:
digitalWrite(led0, HIGH);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 1:
digitalWrite(led0, LOW);
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 2:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 3:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, HIGH);
digitalWrite(led4, LOW);
break;
case 4:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, HIGH);
break;
}
}

This is what I tried to use to replace the delay() function, but that hasn't worked. Note I added these lines in and removed the delay section:
unsigned long onTime;
unsigned long delayTime;

void setup() {
delayTime = millis() + 10;
}

void loop()    {
oldButState = digitalRead(but);
onTime = millis();
if (onTime >= delayTime) {
butState = digitalRead(but);
delayTime = millis() + 10;
}
}

Any pointers as to how I can make the millis() function work to debounce this would be would be very much appreciated, thank you :)

To better understand how you can do this it is good to understand first just what goes on when a button bounces.
It is, literally, bouncing - just like a ball when you drop it.  Due to the fact that it's either connected to ground or pulled up to +5V by the pullup resistor it's either going to be LOW or HIGH with very little time between when it's not in either state, so we can pretty much ignore the rise and fall times of the signal.  It's either connected to ground, or it's not connected to ground.  And we're only really interested in when it's connected to ground.
More importantly we're interested in how long it's been connected to ground for.
By remembering the time it transitioned from HIGH to LOW and then comparing that time to the current time you can know how long it has been connected to ground.  By noticing when it's no longer connected to ground and "forgetting" the time you remembered you can start counting afresh with the next transition from HIGH to LOW.
Take the following diagram for instance:

The blue line is the state of the button.  As you can see it starts HIGH, then it gets pressed to be LOW and bounces between HIGH and LOW a number of times before it settles on being LOW.
The red line is the difference between a timestamp that is set to be equal to millis() at the moment the button transitions from HIGH to LOW and the current millis() value, and is ignored when the button is HIGH.  As you can see the difference between that timestamp and the current millis() value steadily increases. Whenever the button bounces to the HIGH state it resets that difference, and it starts again with the next LOW transition.
When the button has finished bouncing there is nothing to change the state of the timestamp, so the difference keeps increasing.  Eventually that difference will pass a trigger point (the yellow line in this diagram) and at that point you can be fairly sure that the button has finished bouncing and you should react to it.
To translate that into some code, you may end up with something like this (untested):
// Two variables to store remembered state information - the time
// of the last HIGH-LOW transition and the previous state of the
//  button.
static uint32_t debounceTime = 0;
static uint8_t buttonState = HIGH;

// Check to see if the button has changed state
if (digitalRead(buttonPin) != buttonState) {
    // Remember the new state
    buttonState = digitalRead(buttonPin);
    // If the new state is LOW ...
    if (buttonState == LOW) {
        // ... then record the time stamp
        debounceTime = millis();
    } else {
        // ... otherwise set the time stamp to 0 for "don't care".
        debounceTime = 0;
    }
}

// If the time stamp is more than 0 and the difference between now and
// then is greater than 10ms ...
if (debounceTime > 0 && (millis() - debounceTime > 10)) {
    // ... set the time stamp to 0 to say we have finished debouncing
    debounceTime = 0;
    // and do whatever it is you need to do.
    digitalWrite(ledPin, HIGH);
}

There are various tweaks and additions that could be made to that method, but that gives you the basic idea of how you split the debouncing away from the reacting, and it's the results of the debouncing that you react to, not the button state itself.

Hey sorry I never got back to this, your advice really helped! I got it working in the end.

Actually, Majenko's diagram assumes the interplay of the pullup resistor forces the line back to a HIGH position (as quickly as the internal transistors can overpower the drop from the switch).  If the switch itself is mechanical with a pullup resistor (external or internal), then the only thing "bouncing" is the switch.  If you use a digital switch, the rise is much sharper without significant bounce.
A cheap and effective debouncing tactic is to add a capacitor in parallel with the switch.  The cap will drop to GND quickly as the switch drains the charge stored in the cap.  But the cap will take a while to recharge since its only source is through the resistor (during which time the mechanicals settle down).  (This looks much better in a diagram, but I haven't figured out how to draw on here yet.) I wish I could recommend values, but it really depends on the mechanicals of the switch and the certainty of the debounce desired--make everything HUGE and you're guaranteed no bounce, use values in between and you go on probabilities.  I usually start out with 0.1uF and vary it up or down until I get a balance between reliability and speed.
The main advantage is, of course, you use absolutely no computing time to debounce any number of switches.
Potential disadvantages:

Added hardware cost for each switch, making this technique less desirable in production scenarios
0/1 thresholds of input pins will vary across the manufacturing process, so one cap / input pin may have a different debounce time than another on an identical circuit.
Software debouncing schemes can note that the switch is pushed on the first drop to GND, where this hardware-only tactic relies on the last actual contact with GND.  As the switch ages, I've seen this delay exceed 50 mSec.
Since the bounce is mechanical at its core, bounce worsens over the life of the mechanical part (in this case the switch).  Typically, software can be fine-tuned easier than hardware. Often, however, swapping out a cap is easier than reflashing firmware.

source: Stack Exchange

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

sort: votes


text:
Arduino UNO with Sparkfun MP3 Trigger
I have a basic mp3 trigger with arduino uno setup:
Trigger - https://www.sparkfun.com/products/11029
Arduino Uno code:
#include <MP3Trigger.h>

//  Script Function:  RobertSonics mp3trigger (v2) paired with an Arduino UNO
//
//  Jumper Connections:   UNO  ------  mp3trigger (v2)
//             (UNO RX)     0  ------  TX
//             (UNO TX)     1  ------  RX
//             (Ground)   GND  ------  GND
//           (+5 volts)    5v  ------  USBVCC

#include <SoftwareSerial.h>
void setup(){
    Serial.begin(38400);    // Standard for mp3trigger
    Serial.print("t");
    Serial.write(1);
    delay(50000);
}

void loop()
{

}

I can't get it to play any tracks. The response in the Serial monitor just says tt

So, from the beginning:

Have you got data on you SD card and is it is FT16 or FAT32 format?
Is the MP3 status light giving any indication of life?
Does the MP3 card detect when you start it up without the SD card in (One long flash).
Do you have a data file named "001SomethingOrOther.MP3"?
Have you tried the command "v" 0x00?
Have you tried the commands "S0" and "S1"?
Have you looked at the sample data on http://robertsonics.com/mp3-trigger-support/?

Hope that helps, an please post your finding, because mine arrives next week :)

Finally I got it working yesterday, and by accident!!!! Sorry it was not sooner, hope you had better luck with it. In any case if anyone wants to know what I did, you can read about it here.
https://forum.sparkfun.com/viewtopic.php?f=14&t=44292

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


text:
Connect Antenna to GPS Module ET314AC
How can I connect antenna to GPS Module ET314AC?(it is not on a breakout board). I have an antenna like this one GPS Active Antenna and Here is the datasheet of ET314ACET314AC Datasheet.I want to connect it manually without any connectors or other things in fact I want to cutoff the connector from antenna.

Just solder the center wire to the ANT pin, and the outer shielding to the GND pin.

What about power supply? How can I connect battery to that antenna as it is an active antenna?

Have you actually read the datasheet? It's plainly there in black and white.

Read the datasheet!

V_ANT_IN
This pin is reserved an external DC power supply for active antenna.
  If using 2.85V active antenna, pin 19 has to be connected to pin 20.
  If the bias voltage of active isn’t 2.85V,you can input bias voltage of you need to this pin.

So just wire the antenna to the RF_IN pin and GND, and connect pin 19 to +3.3V (since your antenna is 3.3V not 2.85V).

i got the point :)


text:
Using GPS Module ET314AC With arduino Mega
Can I use GPS Module ET314AC with Arduino Mega? Here is the datasheet of ET314AC            ET314AC Datasheet

yes you can, the datasheet is saying that you can read from a serial port which is what you want to do.
Connecting the serial port to TX and RX pins of the Arduino, ground and power, you should be able to talk to the module.
I cant find a breakboard for this module so I suppose you are going to solder it or you can give us the link where you bought it.
I suggest you to try with TinyGPS library to decode the data, after you are sure that the module is talking to the Arduino correctly.

Yes I'm going to solder it manually as I got it from a local store for $4. I also got an active antenna (this one : http://www.aliexpress.com/item/1575-42MHZ-Magnetic-base-GPS-active-Antenna-with-SMA-Plug-connector-for-GPS-receivers-and-Mobile/1531700595.html ) and I'll really appreciate your help if you can tell me how to connect this antenna with above mentioned gps module again I do not have any breakout module and I have to done it manually.

that is an active antenna so it means you need to connect more than one pin to the gps module. At page 11 you can see the small schematic to connect the antenna


text:
How can you determine the duration of a timer interrupt?
So I understand that when setting a timer interrupt you don't use nanoseconds or milliseconds, but the actual number of clock cycles. However, I don't understand how you would be able to setup a specific time this way. If I wanted my interrupt to go off every 20 milliseconds would I have to divide that by the duration of each clock cycle?

The timer takes its time from the system clock. That may be, typically, 16MHz. We call this F_clk_io for the Frequency of the IO CLocK.
Every time that clock ticks the timer counts. Or, depending on settings, every time that clock ticks the prescaler counts, and eventually the output of the prescaler ticks and then the timer counts.
So first you need to divide the F_clk_io by the prescaler. That may be 1:1, 1:2, 1:4, 1:8, etc, depending on settings. No prescaler is the same as a prescaler of 1:1.
So say you have selected a 1:4 prescaler.  The timer's frequency is then F_clk_io / 4, or if it's 16MHz you're running at, then the timer's frequency is 16/4 = 4MHz.
So at 4MHz each tick lasts for 1/4000000 = 250ns.
If you want 20ms you need to know how many ticks that would be.
20ms in nanoseconds would be 20000000. 20000000 / 250 = 80000 ticks.
Now, there's a problem there. 80000 won't fit into the 16-bit registers of a 16-bit timer. The maximum you can have is 65535. So we're going to need to slow things down a bit.
Set the prescaler to 1:8 and see what happens...
16/8 = 2MHz. 1/2000000 = 500ns. 20000000 / 500 = 40000 ticks.
That fits.  See how doubling the prescaler has simply halved the number of ticks you get in the same time?
So setting it to a prescaler of 1:8 and letting it tick 40000 times should give you 20ms.
Except it doesn't.
It gives you 20.0005ms.
Why? Because the interrupt triggers and the counter resets when it reaches the target count, not when it passes the target count.  And since it starts counting at 0, there's actually 40001 ticks there. So you have to subtract 1 from the number of ticks.
So the finished formula is:
ticks = ((F_clk_io ÷ Prescale) × time) - 1

Things get more tricky when you are working with a smaller chip though and only have an 8-bit timer to use. With that the maximum ticks you can have is a mere 255. So you will have to use a much bigger prescale to get it to fit in. If that's even possible.  If it's not, then there are other tricks you can use.  My favourite is a manual pre-scale:

Run the timer at a multiple of your target frequency (10x is easy)
Count the number of times the interrupt triggers
When the interrupt has triggered 10 times (if using a 10x faster timer) then reset the count to 0 and trigger your real ISR code.

10x is simple to program and visualize, but it's not very programatically efficient. Better is to use a "power of two" multiple since you can examine a single bit in your counter to see if it's reached the target count.  Only minimal differences though, and not really worth worrying about unless you are having a very fast timer interrupt.

My goal is to set a 33 second delay on the ATtiny85 which is supposed to have 8 bit register. Will it even be possible for me to get that kind of a delay?

@FortunaIwasaki: If you clock your ATtiny at 8 kHz, yes.

Or if you use the method I mentioned - have a shorter delay and count those to know when 33 seconds have elapsed.


text:
How can I test if pixels are being sent to my arduino?
If I'm using digitalWrite(); to send a clock impulse to a camera and then get analog signal back, how can I check to see if these pixels are in fact returning? Since there is no console how can I see if any values are actually being returned?
I'm using an Arduino Mega with the TSL1401 Linear Array Scanner.

There is a console - it's called Serial.

Send clocks, read the ADC in between, print out the results.  Change the light pattern on the sensor.  Consider the phase relationship between the clock and the ADC conversion time.  Consider using an oscilloscope, or even find a sketch that makes the Arduino into a crude scope with data plotted using processing or something like that on the PC end, and modify that to add clocks to the sensor in between the readings.

@Majenko Where is it in the IDE? Isn't Serial a pin on the Arduino?

@FortunaIwasaki It's the little icon in the top right of a magnifying glass with dots behind it. "Serial Monitor" or something it's called. Any Serial.println() etc you execute will come out there.


text:
How to interpret analog values sent to Arduino from line scanner?
So I have a line scan camera attached to my Arduino Mega and I'm trying to send it a digital clock impulse and get an analog output back. The line scan camera is supposed to return 128 pixels.
So far I've been able to send the impulses and get analog values back which I am printing out. However, the values are different every time, which doesn't make sense because the camera didn't move so I assume that it should give back similar numbers.
Also, is there a way to determine what these numbers mean? Is there some way of turning analog signals into color pixels? My ultimate goals is to be able to determine if something has moved through the vision of the line scanner
Here is the datasheet for the line scanner: http://www.farnell.com/datasheets/315815.pdf
Here is my code:
void loop() {

  int delayTime = 20;
  digitalWrite(syncPin, HIGH);
  delayMicroseconds(delayTime);
  digitalWrite(clockPin, HIGH);
  delayMicroseconds(delayTime);
  digitalWrite(syncPin, LOW);
  delayMicroseconds(delayTime);
  digitalWrite(clockPin, LOW);
  delayMicroseconds(delayTime);

  for (int i = 0; i < 128; i++)
  {
    digitalWrite(clockPin, HIGH);
    pixelValue[i] = analogRead(dataPin);
    delayMicroseconds(delayTime);
    digitalWrite(clockPin, LOW);
    delayMicroseconds(delayTime);
  }

  digitalWrite(clockPin, HIGH);
  delayMicroseconds(delayTime);
  digitalWrite(clockPin, LOW);
  delayMicroseconds(delayTime);

  for (int j = 0; j < 128; j++)
  {
    Serial.print("I received: ");
    Serial.println(pixelValue[j]);
  }

}

It should be noted that analogRead() causes a delay of at least 104 µs, so the delayMicroseconds() right after it is probably not needed.

First, a preliminary note: according to the datasheet, the only time you
need a delay in your program is after reading the whole array and before
sending the next sync pulse. All the other timing requirements are
shorter than a single CPU cycle of your Mega, so no need to add extra
delays.

the camera didn't move so I assume that it should give back similar
  numbers.

Similar: yes. Identical: no. You expect noise to make every reading
slightly different, and you also will have variations due to uneven
timing of your program (e.g. the timer interrupt kicking in from time to
time).

is there a way to determine what these numbers mean?

They are proportional to the amount of light collected by each pixel.
That's about all you know about their meaning.

Is there some way of turning analog signals into color pixels?

No. This is a B&W camera.

That helps a lot, thank you. But even though this is a B&W camera can I still turn the numbers to actual values?

@FortunaIwasaki: What do you mean by “actual values”?

Sorry I mean B&W pixels, also can you let me know where in the datasheet you only need the delay after reading the whole array?

@FortunaIwasaki: You want to turn the numbers into pixels? That doesn't make sense. You want to turn them into pixel values? They are already pixel values. The timings are on page 4, “Timing Requirements”: tql(min) = 20 µs, the other min values are at most 50 ns.


text:
counting ADC samples ( using a light sensor)
i am new to micro controller programming and in need of help. i have managed to interface a light sensor to a micro controller (atmega 32a) and can read the value i.e. (1023) as per the set prescale. however i intended to achieve a single decimal value as the result. in this case (1) every time the sensor is exposed to light and successively perform an incremented tally as lights go on and off around the sensor ( i am using a LDR for this). i am currently having problem getting my micro controller to do this. i have searched all over the internet but no seems to assist me on this... please any insight on how to achieve this will be much appreciated. i know its a simple thing,HELP :(
basically just a means of making my micro controller count the number of times light falls on the LDR

What reading do you have when the sensor is lit? And when it's not? 1023 sounds like you wired the LDR wrong. Forgot a pulldown maybe?

Can you show what code you have so far? This isn't really a code-writing site.

There are 2 common light sensor types.  The photo diode and the photo resistor.  The first produces small amounts of current and operates fast.  The second changes resistance and operates (very) slowly.
There is a good stack exchange response here for how to use a photo diode.  Often the photo diode output is small and additional hardware is used to amplify the signal.  As discussed in this stack exchange response.
The photo resistor or cadmium sulphide cell or Light Dependent Resistor is much easier to interface with an Arduino.  However, the response time is very slow.  On the order of hundreds of milliseconds to seconds.  This is acceptable when controlling street lights.  But is not acceptable in applications requiring fast light detectors such as those used for communication.
Before going on, verify which device you are using in your design.
Generally, Arduinos contain a 10 bit ADC.  This results in values from 0 to 210−1 or 0 to 1023.  Should you consistently get a reading at or near the limits of the ADC check your hardware.  Do this by measuring the voltage at the input of the ADC pin used.  Do this under varying conditions to verify the hardware is operating as expected.
A good software design uses hysteresis to convert an analog value to a logical 1 or 0.  Here is a stack exchange response about using hysteresis with Arduinos.

i have perfect wiring of the LDR and yes i used a pull up resistor. the results range from 0-1023. this occurs when i vary the variable resistor. to add i am not using a arduino. i am using a programmer to push a C++ code into my micro controller then fabricate it on a pcb. what i need is how to manipulate the returned ADC value read from the pins, from a 10 bit value to just a single decimal 1 (at code level ) . i require the micro controller to return the value 1 on exposure, store the value when not exposed and increment the value on every subsequent exposures.

in other words ..is it possible to dictate the value returned. . i intend to use the sensor at its maximum reading. (will use a trimer instead of a pontentiometer for final fabrication ) . all i want to achieve is a tally of number of max exposure times

No, the ADC hardware inside the processor returns a value proportional to the voltage seen at it's input.  The Arduino ADC library configures the ADC hardware and returns this value to your sketch.   It is up to your sketch to interpret this value.  If all you want to do is interpret the ADC value as a 1 or 0 ...  I suggest you use the knowledge in the last paragraph of the answer.

There are hardware hysteresis solutions to this problem.  But they tend to operate at a fixed point and, normally, people tend to address this problem in software.  If you use a compatible hardware solution you should be able to use a GPIO pin and simply test if it is connected to a high or low voltage source.

thank you sir, @st2000 .let me try approach it your way.. much appreciated.. some guys though..smh


text:
Communication between two arduinos over wifi esp8266
I have two arduinos one is Arduino Mega while other is Arduino UNO and I want to send data from UNO to Mega and vice versa over wifi using two ESP8266 wifi modules without use of any router in between, so what is the simplest procedure I can use to do this? Moreover how can I do this with a router in between?

The simplest solution is to turn on Access Point Mode on one of Wifi modules. and the other one has to be set to Station Mode in order to connect to the first one.
In case you want to add a router, just set both ESP8266 modules to Station Mode and connect them to the router.
Also, I would recommend replacing the Original Firware (AT firmware) of ESP8266 with NodeMCU Firmware. It uses lua language to write programs directly to ESP8266 which means that you can even make 2 ESP8266 modules talk with each other without even using Arduino.

can i use Arduino to Flash NodeMCU to ESP8266 or I have to buy usb to ttl adapter like thing?

No you don't need a USB to TTL. Use your arduino, just connect RX pins together and TX pins together (RX<------>RX and TX<------->TX).

You first need to upload a blink sketch to ensure that Serial interface isn't used by Arduino. then you can flash NodeMCU.


text:
LCD Pin Numbering vs I2C Controller Pin Numbering vs Sketch
I've been playing with an Arduino Uno, trying to get a 16x2 LCD screen to work with an I2C controller. I've got this LCD screen and this controller. And I've been trying to get the sketch below to work.
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7,3,POSITIVE);//, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
void setup()
{
    lcd.begin(16,2);
    lcd.backlight();
    lcd.setCursor(0, 0);
    lcd.print("Hello world!");
    lcd.setCursor(0, 1);
    lcd.print("Row number: ");
    lcd.setCursor(12, 1);
    lcd.print("2");
}
void loop()
{

}

I've used an address scanner to verify that the address is correct (39 [0x27]), but it still won't display anything. It lights up, and I've tried adjusting the contrast, but it just won't display any characters.
I'm wondering if the definition of which pins are which is correct, but I can't seem to find anything detailing how the numbers used in the sketch correlate to the pins on the controller, which then correlate to the pins on the LCD screen. If any body can give me some insight I'd appreciate it.

In case it helps, the pins on the LCD screen are labeled as follows:
1  VSS VDD V0 RS RW E D0 D1 D2 D3 D4 D5 D6 D7 A K 16

So far I've tried a couple different things: I added a quick loop to blink the backlight, which does work with the constructor as shown; I added pull-up resistors to the data and clock pins, which didn't seem to affect anything; I tried switching the data and clock connections just in case, which then made the backlight not blink. I'll also add that I AM using the newer LiquidCrystal library from fmalpartida from here. Nothing has worked. Anybody have any more suggestions, please?

Yes, the pins can be different depending on the LCD and the controller. My favorite solution to this is to run a simple "i2c guesser" sketch that can be downloaded from the following forum thread (download link is at the bottom of the first post):
http://forum.arduino.cc/index.php?topic=260510.0
With that sketch it usually only takes me a couple minutes to find the correct pin numbers.

The handful of combinations that sketch tried did not seem to work. Thanks for the info though.


text:
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
So I try to compile and upload a simple code such as the Basic Blink.
I have not connected it to pin 0 or pin 1.
There is an LED with the "L" label on the card that works. So I guess not the chip is damaged?
I have selected the correct model which is Arduino Uno / Genuino. I've checked the drivers several times now, even reinstalled Arduino Software twice and tried on 2 different computers.
5V works with ground, I can get the LED to light up. But I cannot compile / upload code.
Error MSG: avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
(this message repeats 10 times with attempts)

I read something about bootloader, but I have no idea how to do this / what it is. I do not have the right components for bootloading I guess.
Also the COM is correct. I've tried using all the listed COMs without any result. Is this a hardware issue? Is my chip grilled or something?

That might be a bootloader issue, it is not hard to solve but you will need another arduino as programmer to reprogram the bootloader.

But the L led is working? If that one works, shouldn't the chip be working? By the way, how do I remove the chip?

Ah sorry, if the LED marked L ( usually known as pin 13 ) is on, then it might be another problem, since the booloader is still there. did you unplug any circuit attached to Arduino on upload time?

How to remove the chip? watch this video: https://www.youtube.com/watch?v=Hi5CsIsq28M

https://youtu.be/P6IKJehtB_c . Bad quality, but this is how it looks.

According to the video, your bootloader is still there and the reset works just fine, so the microcontroller is working. I see your TX LED constantly on ?!

TX led is flashing rapidly fast. Looks like it is sending all the time, is this normal?

No, there is something wrong, plug in your Arduino and try to uninstall its COM port from Device Manager, then unplug it, wait a few seconds and replug it again.

I uninstalled the COM port, waited a few seconds as you said and replugged it. Then I went over to the Arduino IDE and uploaded the blink again. Then the TX is high while it says "Uploading" and I still get the not in sync errors. Image: http://i.imgur.com/Kc4HltE.jpg

Overriding Baud Rate          : 115200 What does this mean?

I look into the Serial monitor, and it prints numbers like: 1187.50 etc

Yes, your arduino is constantly sending values to your computer. try to upload a sketch to your arduino and when you see uploading to I/O board try to press the reset button.

btw, make sure that you use AVRISP mkll as programmer.

I am using AVRISP mkll and tried reseting once I upload. No difference. Image: http://i.imgur.com/MOpwPSe.png

Try to connect RX and TX pins of your Arduino with a wire and then plug it to your computer, then open Serial Monitor and send some string and see if you get it back?

Should I add pinMode 0 and 1 as outputs in setup? I connected a wire from RX (0) to TX (1)

No don't use any sketch, just open the Serial Monitor and see what happens?

It prints numbers on the same line. I connected a wire from 0 to 1, right?

The TX light is flashing. RX light doesn't respond.

Do you have another arduino or another chip?

No, this is the only one. I uploaded an empty sketch and now the TX is lighting constantly.

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00 avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00 avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00 ...

Are there other solutions? I think the chip needs to be reprogrammed..

I feel the same, you either need another arduino to use it as ISP programmer or an AVR programmer.

I read somewhere else that one got it to work by changing the baud rate. Where do I change the baud rate? Did he just send a command in the serial monitor? avrdude.exe -v -P COM3 -c arduino -p atmega328p -b57600 ...

Before dealing with avrdude, did you try to change the usb cable? use a short one.

Also, try Tools->Programmer->AVR ISP. then upload blink sketch.

The solution that involved dealing with avrdude is for arduino clone boards based on CH340 chip. You arduino is obviously a genuine one.

Yes, mine is 100% genuine. I'll try the AVR ISP. And yes, I've tried 2 cables but none of them worked. They are long though.

Unfortunately it didn't work by changing to AVR ISP.

If you can get an AVR programmer that would solve your problem, it will use SPI interface to program the chip rather than the UART (Serial interface)

I tried another Arduino today and that one worked. So I guess the other Arduino board's chip has to be reprogrammed. Thanks for trying to help me.

Yes I think so, you may use that Arduino to reprogram yours.

You probably could try use Old bootloader option in the arduino IDE upload configuration

You should re-burn the bootloader. If you have another uno, you can burn bootloader here

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


text:
Segmentation fault and huge SRAM need for Serial.println
I have written my own 'assert' since I want to use it for both Windows and Arduino. The class is called from many files (about 10).
AssertUtils.h:
#pragma once

#define assert(expr) AssertUtils::Assert2((expr), (__func__), (__FILE__), (__LINE__));

class AssertUtils
{
public:
    static void Assert2(bool expression, const char* funcName, const char* fileName, int line);
};

AssertUtils.cpp:
#include "AssertUtils.h"
#include "Arduino.h"

/* static */ void AssertUtils::Assert2(bool expression, const char* funcName, const char* fileName, int line)
{
    if (!expression)
    {
        Serial.println(funcName);
        Serial.println(fileName);
        Serial.println(line, DEC);
        Serial.flush();

        // Abort program execution.
        abort();
    }
}

When I compile this, the SRAM usage is 1469 bytes (together with the rest of my sketch and classes).
When I comment the line below, I get a segmentation fault in a random assert call (when I comment out that call, I get it in the next, etc.).
    //Serial.println(funcName);

When I also comment out the second print statement, the compiler reports only 1137 bytes SRAM usage (which I expect since this was about equal until before I added the Assert class).
    //Serial.println(funcName);
    //Serial.println(fileName);

Questions:

How can I get rid of the segmentation fault?
How can it be that about 332 bytes are used for one two additional print statements? (maybe related to the const char* buffering (?)

the  segmentation fault is a bug in compiler in 1.6.22 and 1.6.23. more here https://forum.arduino.cc/index.php?topic=619213.msg4195749#msg4195749

try F(__FILE__) and F(__func__). (change the parameter type to __FlashStringHelper)

@Juraj Somehow it only works for __FILE__ but not for __func__. Anyway using F( __FILE__) was about -90B difference (It's probably full path and it was only used in one file).

so the compiler optimizes the parameters away if hey are not used

Why are you wasting a class on this? Just use the prints directly in the macro.

@juraj Thanks (see answer, but feel free to add your own if you want an upvote from me)

@KIIV Thanks (see answer, but feel free to add your own if you want an upvote from me)

@Majenko Thanks (see answer, but feel free to add your own if you want an upvote from me)

Note, this answer is not MY answer, but approximately the combination of the first 5 comments from my original question.
What I did was:

(Juraj) Changed the compiler version to 6.21
(juraj) Added an F in F(__FILE__)
(KIIV) Removed func; this did not work with the F flash helper, but I can find back the code anyway unambiguously because of the file name + line number.
(Majenko) I removed the class and use a macro. This costs some more Flash memory (depending on the number of asserts I use, but I'm still around 40% (was 35%).

The SRAM usage is now 1125 bytes, even less than where I'm started with.
The resulting code is below:
#define assert(expression) \
  if (!(expression)) \
  { \
    Serial.println(F(__FILE__)); \
    Serial.println(__LINE__, DEC); \
    Serial.flush(); \
    abort(); \
  }

About class - in this case it was used as old form of namespaces (as namespaces weren't present in c++ until 1990). However struct was used more likely as it doesn't need public: specifier.

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


text:
How to use PROGMEM in a .h/.cpp file instead of a .ino file?
I want to use a lot of .h/.cpp files to be used by my ino sketch.
In one of these .cpp files (and later more) I want to use constant arrays (like lookup tables). To save SRAM I want to use PROGMEM.
What worked before in the Ino sketch is:
const uint8_t _red[]   PROGMEM = { 0, 9, 10, 220, 230, 240, 255 };

But when I put the line above in a .h or .cpp file I get the error:
Par.h:13:25: error: expected initializer before 'PROGMEM'

Should I include something or can't I use PROGMEM in a .h/.cpp file?

I already found the answer.
Include:
#include <avr/pgmspace.h>

Update
See also remark of AnT, which is a more generic (and in most cases better solution):
#include "Arduino.h"

(just to help others with the same problem).

... that is If you have a reason not to include <Arduino.h>. But if you do include <Arduino.h>, then <avr/pgmspace.h> is included with it anyway.

@AnT Thanks for that remark; I added it to the solution (I really thought I tried it before and didn't work, but it does).


text:
SPIMemory does not write always correctly
I'm using a WinBond 25Q128FVIQ (Flash 128 mbit, 3.3V) in combination with the Marzogh SpiMemory library on my Arduino Nano (also 3.3V).
After using the default example, I found out what was read, did not always fully match what I wrote. So I created a slightly alternative example writing 16 bytes:
#include<SPIMemory.h>

uint32_t address;

#define BAUD_RATE 115200
#define RANDPIN A0

//SPIFlash flash(SS1, &SPI1);       //Use this constructor if using an SPI bus other than the default SPI. Only works with chips with more than one hardware SPI bus
SPIFlash flash;

bool readSerialStr(String &inputStr);

void setup() {
  Serial.begin(BAUD_RATE);
#if defined (ARDUINO_SAMD_ZERO) || (__AVR_ATmega32U4__)
  while (!Serial) ; // Wait for Serial monitor to open
#endif

  flash.begin();
  Serial.println(F("Flash Test"));
  Serial.print(F("Capacity: "));
  Serial.println(flash.getCapacity());

  char writeBuffer[16] = "0123456789ABCDEF";
  char readBuffer[17];

  for (int n = 0; n < 5; n++)
  {
    memset(readBuffer, 17, 0);
    randomSeed(analogRead(RANDPIN));
    address = random(0, flash.getCapacity() - 16);
    bool err = flash.writeAnything(address, writeBuffer, true);
    delay(50);
    Serial.print(F("Write: "));
    Serial.println(err);
    for (int m = 0; m < 10; m++)
    {
      if (flash.readAnything(address, readBuffer, true))
      {
        Serial.print(m);
        Serial.print(F(", read: "));
        Serial.print(readBuffer);
        Serial.print(F(", from address: "));
        Serial.println(address);
      }
      delay(50);
    }
  }
}

void loop() {

}

//Reads a string from Serial
bool readSerialStr(String &inputStr) {
  if (!Serial)
    Serial.begin(115200);
  while (Serial.available()) {
    inputStr = Serial.readStringUntil('\n');
    Serial.println(inputStr);
    return true;
  }
  return false;
}

Short explanation: 5 times I write a string (hex numbers), and I read this 5 times. The result is: (one example, differs every time):
 Flash Test
Capacity: 8388608
Write: 1
0, read: 0123456789ABCDEF, from address: 6252204
1, read: 0123456789ABCDEF, from address: 6252204
2, read: 0123456789ABCDEF, from address: 6252204
3, read: 0123456789ABCDEF, from address: 6252204
4, read: 0123456789ABCDEF, from address: 6252204
5, read: 0123456789ABCDEF, from address: 6252204
6, read: 0123456789ABCDEF, from address: 6252204
7, read: 0123456789ABCDEF, from address: 6252204
8, read: 0123456789ABCDEF, from address: 6252204
9, read: 0123456789ABCDEF, from address: 6252204
Write: 1
0, read: 0123456789ABCDEF, from address: 5680766
1, read: 0123456789ABCDEF, from address: 5680766
2, read: 0123456789ABCDEF, from address: 5680766
3, read: 0123456789ABCDEF, from address: 5680766
4, read: 0123456789ABCDEF, from address: 5680766
5, read: 0123456789ABCDEF, from address: 5680766
6, read: 0123456789ABCDEF, from address: 5680766
7, read: 0123456789ABCDEF, from address: 5680766
8, read: 0123456789ABCDEF, from address: 5680766
9, read: 0123456789ABCDEF, from address: 5680766
Write: 0
0, read: , from address: 5277398
1, read: , from address: 5277398
2, read: , from address: 5277398
3, read: , from address: 5277398
4, read: , from address: 5277398
5, read: , from address: 5277398
6, read: , from address: 5277398
7, read: , from address: 5277398
8, read: , from address: 5277398
9, read: , from address: 5277398
Write: 0
0, read: , from address: 4941258
1, read: , from address: 4941258
2, read: , from address: 4941258
3, read: , from address: 4941258
4, read: , from address: 4941258
5, read: , from address: 4941258
6, read: , from address: 4941258
7, read: , from address: 4941258
8, read: , from address: 4941258
9, read: , from address: 4941258
Write: 0
0, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
1, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
2, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
3, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
4, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
5, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
6, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
7, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
8, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
9, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153

Conclusion: The write seems to be the problem as the read consequently returns the same value (either garbage or the correct string).
What do I wrong?
Actually, I even don't want the 50 ms delay (and when I remove it, the result is the same).

I made a stupid mistake; I accidentally removed the next line at the end of the application which takes care of erasing the sector. If this is omitted, then the next time write actions will fail (or fail sometimes):
flash.eraseSector(address);


text:
ESP8266MOD programing using Arduino uno?
I want to make a very simple webserver who sends welcome message to anyone who joins it using WiFi.
I have a ESP8266MOD module, I want to program it using arduino ide and arduino uno board.
How I can use arduino uno to program this WiFi module without using urat USB serial board?
SoftwareSerial.h is not working with esp.write() command, I believe it is because of low power, can anyone suggest me on power supply too?
Thanks in advance,
Mohan

Why use a mini to tell a Ferrari what to do? Program the esp8266 directly and screw the Arduino.

just short the UNO's reset to ground to use it as an "FTDI" to program the ESP from the Arduino IDE

Hi dandavis, can you please show me an example, because how to use UNO as FTDI is not documented well anywhere...

your absolutely right Majenko, but my problem is that I don't have URAT or FTDI, so to connect to IDE I have to use UNO itself as FTDI

rx>tx,tx>Rx,gnd<gnd, on avr: rst to gnd. then you can use at mode et al

Making Rx > Tx and Tx > Rx not sending data, more I got a weird error now, I was able to connect it, and blue light is blinking, I can also found it working in my phone's wifi list. but in IDE when I try to upload the sketch I am getting error: error: Failed to open COM1
error: espcomm_open failed
error: espcomm_open failed,

When you use the Uno for its UART only, i.e. grounding RST pin, its Rx pin 0 becomes Tx, and Tx pin 1 becomes Rx -- because that's what pins on the UART you are connecting to. AppMonk didn't say what specific breakout/ chip mount he's using, there are many, or say how he's managing level-shifting from the Uno to the ESP if needed. The Tx pin on Uno (0, labeled Rx) is putting out 5v and the ESP would prefer 3.3, so level shifting w/ simple voltage divider is recommended. You don't need to level shift the Tx signal from ESP to Arduino's Rx (pin 1).


text:
RasPi GPIO into Arduino Digital Inputs
So I'm making a Robot for my AP Comp Sci Class, and I'm borrowing an Arduino, as well as a Pi from the school. What I plan to do is have my Pi output from the normal GPIO pins and into the Arduino's digital inputs to "Tell" the Arduino what servos to run. The reason I'm doing it this way is so I don't have to screw with interfacing and all that crap. Is it safe for the Arduino? If so, what would I need for resistors and such?

Didn't you already ask this?

I was told to move it here instead of having it on Stackexchange

You will need to expand on "I don't have to screw with interfacing and all that crap", because you are trying to do exactly that.

I think he means communication protocols (which would be the sensible way to do things)...

I think you are talking about writing to a GPIO and that being received by the Arduino if so the Pi is 3.3v and the Arduino is 5V so you will need a "Level Shifter" to boost the voltage to 5V so the Arduino can read the signals.
Other than that there is no problem with doing what you are doing, apart from its a lazy solution and you won't score very highly.  I know you don't want to mess with protocols but if you can use I2C from the Pi then use that to send messages to the Arduino.  Your protocol could be as simple as 1 byte saying which pin you want to light up, you'll get better marks.
Edit
To use I2C is really quite simple because someone has done almost all the work for you in Wire.h, so just include that file and then to send a byteits simply a case of:
Wire.beginTransmission(device_address);
Wire.write(data_byte);
Wire.endTransmission();

Reading data sheets for devices makes it look a lot harder with all the transmission sequence diagrams, but you don't need to worry about that its all done for you.  The hardest bit to remember is the pull up resistors on the data lines.
Have a look at these links for more information:

http://tronixstuff.com/2010/10/20/tutorial-arduino-and-the-i2c-bus/
http://howtomechatronics.com/tutorials/arduino/how-i2c-communication-works-and-how-to-use-it-with-arduino/
https://www.arduino.cc/en/Tutorial/MasterReader

That was exactly what I was talking about,  my one problem is that I have no clue about how to use I2C correctly (i find it Kinda confusing)

There is a little bit more to it than that but not much.


text:
How to connect RFID Module to Arduino UNO
I brought 860mhz-960mhz UHF rfid reader module for chip card skimmer from follow link:
https://www.alibaba.com/product-detail/860mhz-960mhz-UHF-rfid-reader-module_60312310172.html
I want to do communication with arduino uno so is it possible to connect

VCC to VCC
GND to GND
RX to TX
TX to RX
and what is meaning of EN and GPIO if any one know please help me to do serial communication.

Its just a simple RFID module based on UART working on 5V.  EN stands for enable, to enable the chip. It has to be connected to VCC too. Because its active high signal. GPIOs are general purpose io pins. No need of them if you are just reading from RFID.

thank you so much I will try to connect these and let you know


text:
Problem with 2 decimal places/2 significant figures
Lora/GPS Shield + Arduino Uno + PLX-DAQ (latest custom version)
I have a problem on how to generate more than 1/2 decimal output.
Currently, I'm trying to generate GPS Lat and Long(code from TinyGPS++) on PLX-DAQ

Just like in the image. Latitude generated in 1/2 decimal places.
I'm trying to get more than 2 decimal places.
For example : from 3.2 to 3.123953
Coding link:
https://www.dropbox.com/s/rqjpnsc9pg33f9n/Coding.txt?dl=0
Thanks.

You're talking about the output from this line?
Serial.println( (String) "DATA,DATE,TIME," +flat+ "");

drop the use of the String class and make that two separate print statements.  Then you can use the second argument to print to define the precision.
Serial.print("DATA,DATE,TIME,");
Serial.println(flat, 6);

That gets the same end result output going out the serial line, but lets you specify the precision and avoids the nasty String class.

Okay, one problem solved. Now how do I get Longitude output same as latitude?

The same way.  Just print it.  I can't see where in the code you tried to print longitude so I'm not sure what exactly you want to do there.

This one.
Serial.print("DATA,DATE,TIME,"); Serial.println(flat, 6); //latitude Serial.println(flon,6); //longitude
But the output only latitude. It's like longitude output doesn't work.

Is it not there at all?  Or is it going to the next line?  Pay attention to when you use print and when you use println.  You should maybe print something in between like a space or a comma or something just to make sure they're separated so you can read them.

 float flat, flon;   Serial.print("DATA,DATE,TIME,");   Serial.println(flat, 6);   Serial.print(",");    Serial.print(flon, 6);
this is what i did. Sorry, I'm confuse.

Do you know what the difference is between print and println?  Would you care to answer the opening question in my last comment?

Serial.print ("abc");Serial.print("def"); = abcdef
Serial.println("abc"); Serial.println("def"); = abc
def
from what I know.. that's how it prints.
well I did managed to get an output for longitude
btw, thanks for your help.

Not quite.  println doesn't put a space, it puts a newline after whatever it prints.

oh, sorry. That not a space. i put "def" in newline. The format for comment here make it just like space.


text:
How to wake up Arduino Mega when in Power Saving Sleep Mode?
I'm using sleep mode to turn off my device after the routine has finished executing and want to use interrupts to wake it up every 33 milliseconds. Basically, the idea is that if the routine completes in less than 33 milliseconds the processor can shutdown and save power for whatever remaining time, which will hopefully translate to reduced power consumption. I've currenlty managed to turn off my device with the sleepNow() function you see below, but the interrupt I have programmed in doesn't seem to work. The program simply goes to sleep and never wakes up. What am I doing wrong?
#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/sleep.h>

const uint16_t PERIOD = 2150;

void setup()
{
  noInterrupts();
  TCCR1A = 0;            // undo the timer config done...
  TCCR1B = 0;            // ...by the Arduino core library
  TCNT1 = 0;             // reset the timer
  OCR1A = PERIOD - 1;    // set the period
  TIMSK1 = _BV(OCIE1A);  // enable TIMERx_COMPA interrupt
  TCCR1B |= (1 << CS12); // ...and set the prescaler
  interrupts();

  Serial.begin(9600);
}

ISR(TIMER1_COMPA_vect)
{
  Serial.println(millis());
}

void loop()
{
  Serial.println("Program is on");
  Serial.flush();
  sleepNow();
}

void sleepNow()
{

    // Choose our preferred sleep mode:
    set_sleep_mode(SLEEP_MODE_PWR_SAVE);

    // Set sleep enable (SE) bit:
    sleep_enable();

    // Put the device to sleep:
    sleep_mode();

    // Upon waking up, sketch continues from this point.
    sleep_disable();

}

Timer 1 cannot wake you up because... it's sleeping! Only Timer 2 is awake in SLEEP_MODE_PWR_SAVE.

Problem is that when I do that it never leaves the ISR and re-enters the loop. It just infinently prints out the time. It didn't use to do that before when I used IDLE and Timer 1.

What's strange is that when I move the print statement outside of the ISR function the program runs just fine.

Printing from within an ISR should be avoided, as the serial port relies on interrupts to send the data, and they are blocked inside the ISR.

Okay that makes sense, but I just have a quick housekeeping question. When I tried to move the interrupt setup into a separate method and then call it from the setup method the interrupts stop working. Is that because you NEED to setup your interrupt in the setup method?

No, you can setup the interrupts wherever you want. You probably introduced an unrelated bug while doing that.

It is certainly tempting to go into a very deep sleep in order to save
power, but you still need to keep awake whatever peripheral you want to
use as a wakeup source. If you want to use a 16 bit timer, there is no
other choice than SLEEP_MODE_IDLE.
But it may not be that bad. In IDLE mode you can selectively disable the
clock (and hence put to sleep) the peripherals you do not use. Or maybe
put them all to sleep, and then wake up the few ones you do need. This
is achieved with the power_*_disable() and power_*_enable() family
of functions.
In the edited code below: all peripherals but the Timer 1 are disabled
while the CPU sleeps. The USART is enabled only for the time it needs to
send its message:
#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <util/delay.h>

const uint16_t PERIOD = 2150;  // 34.4 ms

void setup()
{
  // Disable all but the needed peripherals.
  power_all_disable();
  power_timer1_enable();

  // This is for debug pulses.
  pinMode(22, OUTPUT);

  // Configure Timer 1 to wake us up every 34.4 ms.
  TCCR1A = 0;            // undo the timer config done...
  TCCR1B = 0;            // ...by the Arduino core library
  TCNT1 = 0;             // reset the timer
  OCR1A = PERIOD - 1;    // set the period
  TIMSK1 = _BV(OCIE1A);  // enable TIMERx_COMPA interrupt
  TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
         | _BV(CS12);    // ...and set the prescaler /256

  Serial.begin(9600);
}

ISR(TIMER1_COMPA_vect)
{
  // Send a debug pulse.
  digitalWrite(22, HIGH);
  _delay_ms(2);
  digitalWrite(22, LOW);
}

void loop()
{
  // Enable the USART only while needed.
  power_usart0_enable();
  Serial.println("Program is on");
  Serial.flush();
  power_usart0_disable();

  // And go to sleep in IDLE mode.
  sleep_mode();
}

Notice also that the ISR does not print to the serial port: it just
sends a debug pulse to watch with the scope. This should be removed from
production code. The delay is achieved with the avr-libc function
_delay_ms() because the standard Arduino delay() would not work: it
relies on Timer 0, which has been disabled.

But wouldn't this affect the functionality of the program since you are disabling the peripherals in the start of the program with power_all_disable(); since I'm not an expert on Arduino couldn't this introduce a whole bunch of new bugs? Lastly, if I am able to use very deep sleep and wake it up with the code I have above what would be the advantage of switching to the less power saving option of IDLE mode?

Also why would using a 16 bit timer force me to use IDLE?

@AngelLockhart: If you want to be on the safe side, you can disable only the peripherals you do not use. The nice thing about the IDLE mode is that you can wake up out of it. ;-) The datasheet has, on section 11.1, a table with the wakeup sources available in each sleep mode. You can see that most peripherals (“Other I/O”), including all the 16-bit timers, are only available in IDLE mode.


text:
Is there a way to set an interrupt to go off after a certain period of time?
I'm trying to save power by putting my device to sleep once it has run through the code once and turn it back on every 33 milliseconds. So basically, if the code finishes executing in 20 milliseconds the device can go to sleep for the remaining 13 milliseconds and it will be turned on by the interupt which is set to go off every 33 milliseocnds.
According to the documentation an interrupt is based on a change to the pin state, but I'm sure there must be a way to base it on time. If there isn't then is there a way to set the total time that a device sleeps? The sleep function seemed to just turn the device off, but can it be given a parameter to just turn off for a certain amount of time?

See for example this answer for an example of setting a timer to periodically wake-up the Arduino Mega.

I saw the sleep function, but where are they setting the actual interrupt?

The line TIMSK1 = _BV(OCIE1A);  // enable TIMER1_COMPA interrupt, as the comment says, enables the interrupt.

Follow up question, is this code Arduino? I see a main method but no setup() or loop().

It's plain avr-libc, but it works under the Arduino environment.

The easiest way to achieve your purpose seems to be to configure a
timer to fire every 33 ms, and use this interrupt to wake up the
MCU. For this, you first have to choose what timer to use. On the Mega, I
would rather use the 16-bit timer, but the ATtiny85 only has 8-bit
timers. Next you have to choose a prescaler value (clock frequency
division) among those available for that timer. The prescaler should be
large enough to avoid overflowing your timer, but smaller prescaler
values give better time resolution.
Then you configure the timer to run in “CTC mode” (clear timer on
compare match). In this mode, it counts from zero to the value that you
programmed in the OCRxA register (where x is the number identifying
the timer), and then goes back to zero. This way you can get an
interrupt every OCRxA + 1 timer cycles.
In the example code below, you have to replace x with the appropriate
timer number, and check the datasheet for the bits to set in the control
registers TCCR*:
#include <avr/interrupt.h>

// Interrupt period, in prescaled clock cycles.
const uint16_t PERIOD = ...;  // or uint8_t for an 8-bit timer.

// The timer interrupt is used ONLY to wake the CPU, so there is no job
// to be done inside the interrupt service routine.
EMPTY_INTERRUPT(TIMERx_COMPA_vect);

void setup()
{
    // Disable Timer 0 interrupts.
    // Warning: this will prevent the Arduino from keeping time.
    TIMSK0 = 0;

    // Configure Timer x.
    TCCRxA = 0;            // undo the timer config done...
    TCCRxB = 0;            // ...by the Arduino core library
    TCNTx = 0;             // reset the timer
    OCRxA = PERIOD - 1;    // set the period
    TIMSKx = _BV(OCIExA);  // enable TIMERx_COMPA interrupt
    TCCRxA = ...;          // set the counting mode to CTC...
    TCCRxB = ...;          // ...and set the prescaler
}

void loop()
{
    // Sleep while waiting for the timer interrupt.
    sleep_mode();

    // Now that we have been waken up...
    do_the_job();
}

Edit: As noticed by Gerben, the Arduino core library configures
Timer 0 to send periodic interrupts (one every 1024 µs), which
are used for timekeeping (millis(), delay() and co.). This
interrupts will wake up the MCU and prevent it from sleeping as long as
you want. The simplest solution, which is implemented in the code above,
is to disable the Timer 0 interrupts. The drawback is that the
Arduino timekeeping functions will not work anymore.
If you need those timekeeping functions, then the proper solution is the
one sketched by Gerben in his comment: set a boolean in the interrupt
that can be checked in the main loop. Here is the naive implementation
of this idea: EMPTY_INTERRUPT(TIMERx_COMPA_vect); is replaced by
volatile bool time_elapsed;

ISR(TIMERx_COMPA_vect)
{
    time_elapsed = true;
}

Then, in the main loop you sleep repeatedly until the ISR sets the flag:
void loop()
{
    // Warning: race condition here!
    while (!time_elapsed)
        sleep_mode();
    time_elapsed = false;

    // Now that we have been waken up...
    do_the_job();
}

As stated in the comment, this naive implementation suffers from what is
known as a race condition. The problem is in the following scenario:

The main loop reads the value of time_elapsed and it turns out to
be false
At this point the interrupt fires and the ISR sets that boolean to
true
Returning from the ISR, the main loop does not test the flag again
(since it just did it) and goes straight to sleep_mode();.

At this point the MCU ends up sleeping although it should be performing
the job which is due now.
This race condition may not a be a big deal to you: The MCU will be
eventually woken up by the Timer 0 interrupt no more than 1024 µs
later. In some cases it is an issue, but fortunately there is a proper
solution. It is described in the page about sleeping of the avr-libc
documentation. It relies on the fact that when interrupts are
disabled, then enabled again with sei(), the machine instruction right
after the sei() is guaranteed to be executed before any interrupt is
serviced. Then the proper way to test the flag and sleep is:
void loop()
{
    while (!time_elapsed) {
        cli();
        if (!time_elapsed) {
            sleep_enable();
            sei();          // interrupts enabled
            sleep_cpu();    // this will be executed before any ISR
            sleep_disable();
        }
        sei();
    }
    time_elapsed = false;

    // Now that we have been waken up...
    do_the_job();
}

With this version, if the interrupt fires right after the test
if (!time_elapsed), it will be serviced after sleep_cpu(), which
will have the effect of waking the MCU right away.

Wow that helps a lot, but why do you subtract 1 from PERIOD? That other example did that too. Also, PERIOD is supposed to be the duration between interrupts, correct? So for my project I'd set it equal to the number of clock cycles that will equal 33 milliseconds. Right?

The counter counts from 0 to OCRxA inclusive, so the period is OCRxA+1. The period is in prescaled clock cycles, see the prescaler setting.

Timer0 (used for millis and delay) will also wake up the device. You probably need to set Boolean inside the interrupt, so the main loop can check if it needs to go back to sleep or not

Thanks @Gerben for noticing. You are absolutely right. I've amended the answer to account for this issue.

Nice solution for the race condition.

There are many many kinds of interrupt. External interrupts (of the kind you use with attachInterrupt()) are but one.
Almost every internal peripheral in the AVR chip can generate an interrupt (or multiple interrupts in some cases). One of the most useful is the timer interrupt which is triggered by one of the timers when its timer has overflowed.
I am not familiar with the AVR's sleep mechanisms, but I would assume a timer interrupt can wake it from sleep - assuming the timer can run while sleeping.
You should check the documentation for the chip on your Arduino rather than relying on the (somewhat scant and basic, and often misleading) documentation on the Arduino website when it comes to doing anything low-level like this.

You are right: the timer interrupt can wake up the MCU, but only if it's sleeping in the so called “IDLE” mode... which is the default sleep mode anyway.

Does the setting of a timer interrupt vary from microcontroller to microcontroller? I'm trying to write this code on the Arduino Mega first and then port it to an ATtiny.

Yes. You should read the documentation for both your target microcontrollers and program accordingly - probably with copious usage of #ifdef ... #endif

@AngelLockhart: It's often not that different. You could probably use the same code for the 16-bit timers of the ATmega2560 and the ATtiny84A. What ATtiny are you targeting? At what clock frequency?

The principle of operation will be almost the same between them. Numbers will change though (calculations for time vs clock frequency), and register names may change (depending on number of timers available, etc). In general, though, there will be a lot of copy-and-paste of logic blocks like these when it comes to designing chips in the same broad family.

@EdgarBonet I'm using the ATtiny85, also can you explain why the number would change? My plan was to calculate the time the program ran with millis() and then subtract that from 33 milliseconds. Will that not work?

Timers operate on clock ticks. You need to calculate how many clock ticks make up the time you need it to run for, and of course that changes depending on the speed the clock is running at.


text:
Arduino Micro tone() PWM Pins
according to the tone() documentation using tone() interferes with PWM output:

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

On my Arduino Micro it seems to interfere with PWM on pin 5. After using tone() the PWM does not seem to work anymore. If I use pin 3,9 instead everything works fine.
So can someone explain why that is happening and if there is a way to circumvent that?

It's called a resource conflict.  The Arduino only has limited resources, and some resources are shared between different tasks. You can use that resource for one task or the other but not both.
In this case the resource is a timer.  You can use that timer to generate PWM or you can use it to drive the tone() system - but not both.
By default the timer is configured for PWM, but once you use tone() it re-assigns the timer to be used to trigger an interrupt at a specific frequency to toggle an IO pin.

ok thanks, but I don't want to use both simultaneously. Can I manually re-assign the timer back to the PWM?

It may be doable, but there isn't (AFAIK) a single function to do it. You will have to undo whatever tone does and re-do whatever PWM does.  Look at the source code to both the tone() command and the analogWrite() command and associated functions to see what they do.

ok I understand. That's not worth the effort for me. I will just avoid pin 5 then.

You could just extend disableTimer, to reset properly timer 3, like it does for timer2. Or force it to use timer 2 (here). Shouldn't be to hard, but might indeed not be worth the effort.

The pin 3 and 11 only refers to boards based on the ATMega328. On these boards timer2 is used by tone, disabling PWM on pins 3 and 11. See Majenko answer about timers.
The Micro (ATMega32u4) tone uses timer 3, which is connected to pin 5 only.
So on the Micro, just don't use pin 5 for PWM when using tone.
Secondly don't trust everything on the arduino.cc website. There quite a bit of misinformation on there.


text:
How do I connect this string of LEDs to my Arduino Uno?
I'm an electronics noob. I have this string of LEDs but don't know how to connect them to my Arduino Uno. As they are wired in parallel, there are two wires / four ends. What do I plug where?

How many LEDs are in the string?  How much current is the string of LEDs supposed to take?  What voltage are they rated at?  What model number, or do you have a spec sheet we can look at?

Connect the negative ( or cathode ) to ground ( 0V )
and the postive ( anode ) to the output pin of the controller.
Firstly connecting that many LEDS directly to a single micro pin is not a good idea. Usually you would need to go through a buffer/driver first which can deliver the correct power to the LEDS.
I'm not that familiar with the UNO but unless that board has a driver circuit on it you might need a few extra components.

What are the specs of the LEDS?

Just to be clear. The resistor isn't necessarily on the anode (+) side of the leds (as shown in the diagram). To easily figure out, which is which, plug one end in the 5v pin and the other in the GND pin. If they don't light up, swap the ends around. The end placed in the 5v is the anode(+).


text:
Using Arduino for simultaneous lighting effects
I am building a computer for my son (me).  I'm trying to spark his interest in computer technology, so my idea is to drive multiple case lighting effects with a microprocessor or controller.  I went with the arduino over the pi because of simplicity of the system.
There are several lighting effects I want to drive, simultaneously, and that's where I'm wondering if the arduino is well suited, because the effects need to make use of delay(), and with it being single threaded I'm struggling to figure out how to make each output operate independently.
To give you an idea of what the microcontroller needs to drive simultaneously:

Flicker pattern using random delay values for outer case lighting
Heartbeat pattern for CPU cooling block
Blacklight / UV LED lighting for coolant lines.
Strobing LEDs aimed at the fans to make them look stationary.

Trying to run all these effects in a linear loop with delay() operators just doesn't seem to be feasible.
Do I need to get an UNO for each effect?  Or is there a way of making these outputs operate independently?

Avoid delay() and use specific times of next actions and compare them to millis().  For a random time, set something like:
now=millis();
...
if(nextFlicker < now) {
   toggleFlicker();
   nextFlicker=now+random(10000);
}
if(nextPulse < now) {
   nextPulse=now+ isPulseOn? 100 : 1000 ;
   togglePulse();
}

...

If you are running more than the 50 day roll-over time of millis(), you may need some care to handle the overflows.  See http://playground.arduino.cc/Code/TimingRollover
For the strobing leds, investigate the timer-controlled outputs outputs.

Base the pattern on time, instead of using delays. E.g. if the current time in seconds if odd, the led should be on. If it's even it should be off. This creates a blinking led effect without using any delay.
Some example code:
long seconds = millis()/1000;
if( (seconds % 2)==0 )// even
  digitalWrite(led, HIGH);
else // odd
  digitalWrite(led, LOW);

E.g. to have it blink faster, change 1000 to a lower value.
E.g. to make the led be on shorter than of change %2 to e.g. %4 (i.e. 1 second on, 3 seconds off)
etc.


text:
Why the global variables info is not shown for Arduino Due in IDE?
If I compile a sketch for the Arduino Mega:
Sketch uses 1804 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 188 bytes (2%) of dynamic memory,
leaving 8004 bytes for local variables. Maximum is 8192 bytes.

If I compile the same sketch for the Arduino Due:
Sketch uses 26304 bytes (5%) of program storage space. Maximum is 524288 bytes.

Why is the global variables part not supported for the Due, it seems to me it's quite important (even more than the sketch size).
Or can I enable this option somehow? (and if yes, how)

There is a difference in how the build system calculates the memory size for AVR and SAM. The platform.txt file contains the rule for calculating the size. There is a difference how this is done for SAM (Arduino Due).
The AVR size rules (https://github.com/arduino/ArduinoCore-avr/blob/master/platform.txt#L79) are:
## Compute size
recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
recipe.size.regex=^(?:\.text|\.data|\.bootloader)\s+([0-9]+).*
recipe.size.regex.data=^(?:\.data|\.bss|\.noinit)\s+([0-9]+).*
recipe.size.regex.eeprom=^(?:\.eeprom)\s+([0-9]+).*

And the rules for SAM (https://github.com/arduino/ArduinoCore-sam/blob/master/platform.txt#L91) are:
recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf"
recipe.size.regex=\.text\s+([0-9]+).*

They may be updated to give more information about the memory size. A good reference on the subject is http://www.support.code-red-tech.com/CodeRedWiki/FlashRamSize which shows that the output from size command for SAM contains much more information.
I assume that from the above information you see how this could be updated.
Cheers!

Thank you very much ... that output looks very much to what I get when I compile software for the STM32. However, I tried to find how to run arm-none-eabi-nm -S --size-sort -s project.axf, but I cannot find the axf file and there is - at least no menu option - to  run arm-none-eabi-nm


text:
Is low memory warning based on a fixed number of on the actual sketch?
I have the following output of my sketch for the Arduino Mega so far:
Sketch uses 25020 bytes (9%) of program storage space. Maximum is 253952 bytes.
Global variables use 6919 bytes (84%) of dynamic memory, leaving 1273 bytes for
local variables. Maximum is 8192 bytes.

Low memory available, stability problems may occur.

I think 1273 bytes is not so less for most sketches, although mine is quite big (several thousand of lines, and I'm about half).
I was wondering if the IDE is so smart to statically analyze my code to see what my dynamic storage is (about 600 bytes) and/or calculates some expected stack size (several hundred bytes at least).
Or is it just a (very) safe fixed or percentage-based value?

1273 = 8192 - 6919. There is no guessing whatsoever on the part of the IDE.

What I mean is, why it gives already a warning when I still have 1273 bytes left? It seems like a 'very safe' value.

I just did some tests and found the answer.
char a[6135];

void setup()
{
  a[0] = 0;
}

void loop()
{
}

This sketch does not give a warning:
Sketch uses 660 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 6144 bytes (75%) of dynamic memory, leaving 2048 bytes for local variables. Maximum is 8192 bytes.

If I increase the array with 1, I get an error:
Sketch uses 660 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 6145 bytes (75%) of dynamic memory, leaving 2047 bytes for local variables. Maximum is 8192 bytes.
Low memory available, stability problems may occur.

Conclusion: below 2 KB (2048 bytes) of free space, the warning is shown.
I did the same test for the Uno, and there the warning is shown when less than 1536 bytes are free.
Both percentages are 75%, so the end conclusion is that the value is based on 75% of memory.


text:
Is the a low memory alternative to SoftwareSerial?
I'm running a program on a ATtiny85 and running into problems because of a lack of available RAM. When I ran avr-nm on my ELF file I found that SoftwareSerial was taking up a lot of RAM even though I'm just using it to set the data transfer rate with mySerial.begin(9600); and nowhere else.
So I'm wondering if there is another way of doing this without using so much memory:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(0,1);

mySerial.begin(9600);

Simplest thing would probably be to edit your copy of SoftwareSerial.h
and replace #define _SS_MAX_RX_BUFF 64 on line
42
by something smaller. If your loop() runs fast enough (no delays, no
blocking code) you could probably get away with buffering only a very
few bytes.
Or you could rewrite the library so that, instead of buffering the
incoming bytes, it handles them to you for processing. See for example
this receive-only UART code based on the USI
port for an illustration of the
approach.

Where would I go to edit my SoftwareSerial.h? Also my program is working with a camera and I am using delays to send a clock impulse does that mean that lowering the buffer rate would not work for me?

@AngelLockhart: It's probably somewhere like $ARDUINO_HOME/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h, where $ARDUINO_HOME is you Arduino installation directory. You can use the search facilities of your OS. If your clock pulses are very short (a few microseconds or so), the delays may be OK. Otherwise you should learn to control timings without delay().

My ESP8266 was randomly crashing any time I used SoftwareSerial from framework-arduinoespressif8266 or https://github.com/plerup/espsoftwareserial, due to too low memory.
https://github.com/CrazyRobMiles/Esp8266EdgeSoftwareSerial fixed this problem. I still receive data from the sensor via SoftwareSerial, and there is 4000 bytes more RAM compared to the alternative implementations.

how should it help with the problem in the question?

@Juraj Well, the arduino SoftwareSerial.h somehow requires more 4000 bytes of RAM to transfer a buffer of 64 bytes (why???).  The linked library can be used as a direct replacement for SoftwareSerial, and has a much smaller footprint.
I now realize the code is called Esp8266EdgeSoftwareSerial, and might not run on other architectures. Is that your implied question?

I doubt that the standard SoftwareSerial has a 4000 byte RAM overhead, this must be something else. Anyway, the OP uses an ATtiny85, so answers for Esp8266 don't help.

@thebusybee: Okay, I'll delete my answer. SoftwareSerial.h seems to have a huge overhead for the projects I work on. If I include it and use it, without changing any other parameter, ESP.getMaxFreeBlockSize() and ESP.getFreeHeap() both take a huge hit. I'll keep on investigating, and file a bug report (I'm not the only one complaining about memory use). For what it's worth, OP's question still need a proper answer : the accepted one leads to 404 and tells OP to rewrite the lib. :-/


text:
Triggering capacitive touch on a touch device
As you can see in the video, it is possible to trigger a touch with arduino. I have tried a couple of methods but with no success.

I have a wire soldered on to a coin which is being used to trigger
the touch.
I tried to directly connect pin 2 from arduino to the    coin (no
touch applies)
I tried to connect a relay and transistor,    seems    necessary for
this project but I didnt get it to work either.

I will say I have very little knowledge of relay/transistor and the wiring part of it, so Im guessing thats where the problem is.
My parts:
Transistor P2N2222A:
http://www.onsemi.com/pub_link/Collateral/P2N2222A-D.PDF
Relay:
JZC-11F
Sketch used:
  void setup() {
  digitalWrite(2,LOW);
}

void loop() {

  pinMode(2, INPUT);
  delay(500);

  pinMode(2, OUTPUT);
  delay(500);

}

If possible please provide a frizting schematic showing how to connect.

http://electronics.stackexchange.com/questions/63950/arduino-trigger-an-iphones-touch-screen-with-no-human-interaction

Capacitive touch screens are design (both the hardware and software) to work with human fingers and human like movements.  It could be that you are not only working against the physical aspects of influencing capacitance at the screen location you are interested in controlling, but also the software which is trying to reject noise and "unwanted touches".
That said, this stack exchange question / answer addresses some of your questions and even proposes an (untested) circuit to try.  I would suggest to skip the "accepted" answer and read the answer with the highest score.
Based on the above response, I would suggest changing your strategy.  I might try connecting the Arduino directly to the metal probe.  Then changing the software to alternate between putting a negative then positive voltage potential on the metal probe.  Avoiding using the Atmel's input or high impedance configuration.  I might also try a smaller metal probe that covers a smaller area of the target device.  Perhaps something that is conductive and easily reforms to a flat screen as if it were a finger tip.  Something like a small ball of aluminum foil. Also, make sure that there is nothing else touching the screen like tape or a stray wire.  Such objects may cause the target's software to consider all touch events as noise or as "unwanted touches".


text:
Flexiforce to Uno to Keyboard. Working but not as inteded
I have a Flexiforce 25 pound pressure sensors connected to my Arduino Uno which connects to my laptop. My requirement is to be able to play video games using taps on pressure sensors. I am successfully sending signals to my Laptop and I am using Java on my Mac to send keystrokes (Key Down and Key Up) signals to move in the game. However I am facing issues with long key down and key up. How do I detect that and make sure that my program runs smooth?
Uno code:
void setup() {}

void loop() {
int sensorValue = analogRead(A0);
int sensorValue2 = analogRead(A1);
int sensorValue3 = analogRead(A2);
int sensorValue4 = analogRead(A3);
int sensorValue5 = analogRead(A4);
int sensorValue6 = digitalRead(2);

// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
float voltage2 = sensorValue2 * (5.0 / 1023.0);
float voltage3 = sensorValue3 * (5.0 / 1023.0);
float voltage4 = sensorValue4 * (5.0 / 1023.0);
float voltage5 = sensorValue5 * (5.0 / 1023.0);
float voltage6 = sensorValue6 * (5.0 / 1023.0);

if(voltage > 1){
   Serial.begin(9600); Serial.println("A0"); Serial.end();
}
if(voltage2 > 1){
   Serial.begin(9600); Serial.println("A1"); Serial.end();
}
if(voltage3 > 1){
   Serial.begin(9600); Serial.println("A2"); Serial.end();
}
if(voltage4 > 1){
   Serial.begin(9600); Serial.println("A3"); Serial.end();
}
if(voltage5 > 1){
   Serial.begin(9600); Serial.println("A4"); Serial.end();
}
if(voltage6 > 0){
   Serial.begin(9600); Serial.println("D2"); Serial.end();
}
// Wait 100 milliseconds
delay(100);
}

In java I'm using java.wt.Robot and gnu.io.SerialPort to press key and read from serial port. On a serialEvent I will override the listener function to perform my operation which is press Keys on my machine.
Java Code:
public void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            String inputLine = null;
            if (input.ready()) {
                inputLine = input.readLine();
                if (inputLine.contains("A0")) {

                    long start = System.currentTimeMillis();
                    while (System.currentTimeMillis() - start < duration) {
                        robot.keyPress(KeyEvent.VK_UP);
                    }
                    robot.keyRelease(KeyEvent.VK_UP);
                    System.out.println("UP");

                } else if (inputLine.contains("A1")) {

                    long start = System.currentTimeMillis();
                    while (System.currentTimeMillis() - start < duration) {
                        robot.keyPress(KeyEvent.VK_DOWN);
                    }
                    robot.keyRelease(KeyEvent.VK_DOWN);
                    System.out.println("DOWN");

                } else if (inputLine.contains("A2")) {

                    long start = System.currentTimeMillis();
                    while (System.currentTimeMillis() - start < duration) {
                        robot.keyPress(KeyEvent.VK_LEFT);
                    }
                    robot.keyRelease(KeyEvent.VK_LEFT);
                    System.out.println("LEFT");

                } else if (inputLine.contains("A3")) {

                    long start = System.currentTimeMillis();
                    while (System.currentTimeMillis() - start < duration) {
                        robot.keyPress(KeyEvent.VK_RIGHT);
                    }
                    robot.keyRelease(KeyEvent.VK_RIGHT);
                    System.out.println("RIGHT");

                } else if (inputLine.contains("A4")) {

                    long start = System.currentTimeMillis();
                    while (System.currentTimeMillis() - start < duration) {
                        robot.keyPress(KeyEvent.VK_S);
                    }
                    robot.keyRelease(KeyEvent.VK_S);
                    System.out.println("S");

                } else if (inputLine.contains("D2")) {
                    robot.keyPress(KeyEvent.VK_D);
                    robot.keyRelease(KeyEvent.VK_D);
                    System.out.println("D");

                }
            }

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
}

This performs Up, Down, Left, Right, "S" and "D" operation for SuperMario 3 GBA game. This works but not as smooth as intended. Is there anything that I can use to directly bind to my keyboard to get a smoother key operations.


text:
HDMI EDID emulator
I am working on a project where i emulate the EDID of a screen to force a source into sending data on a certain resolution.
I read the original EDID code of a screen and change the timings into the resolution I want to force the source in, i send this changed EDID code to the source with an Arduino uno when the source gives a read on address 0x50 (where the EDID located, see handshake). We have an HDMI in/out with the data lines connected thru and the DDC lines (source) connected to the Arduino that we can send the changed EDID to the source (i²c protocol).
I can change the resolution successfully on some sources, and on some it doesn’t change. The attached screen doesn’t find a source. I use the same code for both scenarios.
#include <DTWI.h>
#include <Wire.h>         //BUFFER_LENGTH = 256

uint8_t edid[256] = {
 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x4C, 0x2D, 0xF4, 0x0C, 0x45, 0x52, 0x46, 0x31, 0x15, 0x19, 0x01, 0x03, 0x80, 0x3C, 0x22, 0x78, 0x2A, 0x52, 0x95, 0xA5, 0x56, 0x54, 0x9D, 0x25, 0x0E, 0x50, 0x54, 0xBF, 0xEF, 0x80, 0x71, 0x4F, 0x81, 0xC0, 0x81, 0x00, 0x81, 0x80, 0x95, 0x00, 0xA9, 0xC0, 0xB3, 0x00, 0x01, 0x01, 0x02, 0x3A, 0x80, 0x18, 0x71, 0x38, 0x2D, 0x40, 0x58, 0x2C, 0x45, 0x00, 0x56, 0x50, 0x21, 0x00, 0x00, 0x1E, 0x01, 0x1D, 0x00, 0x72, 0x51, 0xD0, 0x1E, 0x20, 0x6E, 0x28, 0x55, 0x00, 0x56, 0x50, 0x21, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x32, 0x4B, 0x1E, 0x51, 0x11, 0x00, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xFC, 0x00, 0x53, 0x32, 0x37, 0x45, 0x33, 0x37, 0x30, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x01, 0x62, 0x02, 0x03, 0x1B, 0xF1, 0x46, 0x90, 0x04, 0x1F, 0x13, 0x03, 0x12, 0x67, 0x03, 0x0C, 0x00, 0x10, 0x00, 0x80, 0x22, 0x23, 0x09, 0x07, 0x07, 0x83, 0x01, 0x00, 0x00, 0x01, 0x1D, 0x00, 0xBC, 0x52, 0xD0, 0x1E, 0x20, 0xB8, 0x28, 0x55, 0x40, 0x56, 0x50, 0x21, 0x00, 0x00, 0x1E, 0x8C, 0x0A, 0xD0, 0x90, 0x20, 0x40, 0x31, 0x20, 0x0C, 0x40, 0x55, 0x00, 0x56, 0x50, 0x21, 0x00, 0x00, 0x18, 0x8C, 0x0A, 0xD0, 0x8A, 0x20, 0xE0, 0x2D, 0x10, 0x10, 0x3E, 0x96, 0x00, 0x56, 0x50, 0x21, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3D
};

void receiveEvent(int receivedByte)
{
    if (receivedByte == 1)          //If there is 1 byte received
    {
      int receivedValue = Wire.read() << 1;
      receivedValue |= Wire.read();
      Serial.print("Read byte: ");
      Serial.print(receivedValue);
      Serial.println();
    }
    else
    {
        Serial.println("Not the amount of bytes that was expected: ");
        Serial.print(receivedByte);
    }

    while(Wire.available())
    {
        Wire.read();
    }
    return;
}

void requestEvent()
{
      Serial.println();

     for (int i = 0; i < 256; i++){
            Wire.write(edid[i]);               //Write EDID
            Serial.print(edid[i], HEX);      //Print EDID
            Serial.print(",");
     }

    Serial.println();
    Serial.println("Finished");      //Write is complete

}

void setup()
{
  Serial.begin(9600);
  Serial.println("**** HDMI ****");
  pinMode(2, OUTPUT);          //Hot plug detection
  Wire.begin(0x50);
  digitalWrite(2, LOW);
  delay(20);
  digitalWrite(2, HIGH);         //Source knows that a screen is attached and want to read the edid of the screen

  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
}

void loop()
{

}

The following attached pictures are the EDID handshakes without the Arduino involved.
Handshake 1: This is an HDMI 1.4 device
Handshake 2: This is another HDMI 1.4 device
You can see that the handshakes are the same.
My code only works on handshake 1.
Does anyone have an idea why it doesn't work on the other devices ?
Does it has to do with the Start/Restart ?
Regards !

I'm not an expert in HDMI/DDC, but I have some theories to remove potential problems:

"Wire.onRequest/Wire.onReceive" could be before "digitalWrite(2, HIGH)", to really represent "OK, you can send me data now" (Arduino isn't the fastest HW, and Arduino libs add extra overhead - lots of condition races can occur);
You could use "Write.write(did, 256)", instead of writing one byte to I2C then another via serial (again, racing conditions, specially since serial writing is slow);
If I'm not misunderstanding, the byte received from HDMI means the byte you should start transmitting EDID (ex: for "0", do a "Wire.write(edid, 128)", for "0x80", do a "Wire.write(edid + 0x80)"). This is a common approach for reading from PROM chips. HDMI have a 5V pin to allow PROM reading from turned-off devices, and byte 127 from EDID means "I may have more 128 bytes for you".
Are you doing simple tests, with unmodified data? Ex: read EDID from device X, test that same EDID, then test with modified data?


text:
Configuring IO18, IO19 for I2C connectivity on Intel Edison Kit for Arduino
Intel Edison Kit for Arduino Hardware Guide instructs:
echo 28 > /sys/class/gpio/export
echo 27 > /sys/class/gpio/export
echo 204 > /sys/class/gpio/export
echo 205 > /sys/class/gpio/export
echo 236 > /sys/class/gpio/export
echo 237 > /sys/class/gpio/export
echo 14 > /sys/class/gpio/export
echo 165 > /sys/class/gpio/export
echo 212 > /sys/class/gpio/export
echo 213 > /sys/class/gpio/export
echo 214 > /sys/class/gpio/export
echo low > /sys/class/gpio/gpio214/direction
echo high > /sys/class/gpio/gpio204/direction
echo high > /sys/class/gpio/gpio205/direction
echo in > /sys/class/gpio/gpio14/direction
echo in > /sys/class/gpio/gpio165/direction
echo low > /sys/class/gpio/gpio236/direction
echo low > /sys/class/gpio/gpio237/direction
echo in > /sys/class/gpio/gpio212/direction
echo in > /sys/class/gpio/gpio213/direction
echo mode1 > /sys/kernel/debug/gpio_debug/gpio28/current_pinmux
echo mode1 > /sys/kernel/debug/gpio_debug/gpio27/current_pinmux
echo high > /sys/class/gpio/gpio214/direction

However line 3 already gives an error:
echo: write error: No such device

Any suggestions on how to enable I2C?

It was a strange problem which we were not able to resolve in an acceptable manner after all.
The problem disappeared after we re-flashed the device.


text:
Serial Print, String And Variable On Same Line
How can I print to the serial monitor a string or just single character followed by a variable like "L 55"

Read the Arduino docs for Serial.print.

int Var = 55;
//Do it in 2 lines e.g.
Serial.print("L ");     // String
Serial.println(Var);    // Print Variable on same line then send a line feed

Thanks a lot for your answers. I made this ...
#define DEBUG  //If you comment this line, the functions below are defined as blank lines.
#ifdef DEBUG    //Macros
  #define Say(var)    Serial.print(#var"\t")   //debug print, do not need to put text in between of double quotes
  #define SayLn(var)  Serial.println(#var)  //debug print with new line
  #define VSay(var)    Serial.print(#var " =\t"); Serial.print(var);Serial.print("\t")     //variable debug print
  #define VSayLn(var)  Serial.print(#var " =\t"); Serial.println(var)  //variable debug print with new line
#else
  #define Say(...)     //now defines a blank line
  #define SayLn(...)   //now defines a blank line
  #define VSay(...)     //now defines a blank line
  #define VSayLn(...)   //now defines a blank line
#endif

if (some_condition) VSayLn(some_var); won't work as intended. The standard fix is to #define VSayLn(var) do { Serial.print(#var " =\t"); Serial.println(var); } while (0). C.f. Why use apparently meaningless do-while and if-else statements in macros?

For debug printing, you can define a macro to print both the name and value of a variable like this:
#define PRINTLN(var) Serial.print(#var ": "); Serial.println(var)

which you then use like this:
int x = 5;
PRINTLN(x);

// Prints 'x: 5'

Also this is nice:
#define PRINT(var) Serial.print(#var ":\t"); Serial.print(var); Serial.print('\t')
#define PRINTLN(var) Serial.print(#var ":\t"); Serial.println(var)

when used in a loop like so
PRINT(x);
PRINT(y);
PRINTLN(z);

prints an output like this:
x:  3   y:  0.77    z:  2
x:  3   y:  0.80    z:  2
x:  3   y:  0.83    z:  2