text:
Arduino nokia 5110 lcd screen problem
Hello I have a nokia 5110 lcd display connected to my Arduino. I have looked at so many tutorials and none of them work for me. I am trying to get a bitmap displayed in the screen but only the lights light up and nothing else happens.
I have the lcd connected to the following Arduino pins:

vcc -- 3.3v
gnd -- gnd
sce -- pin 7
rst -- pin 6
d/c -- pin 5
DN -- pin 4
sclk -- pin 8
led -- 100ohm resistor --pin 11

here is an image

Nothing will display on the screen could someone please help me here is my code:
 #include "U8glib.h"
 #include "dht.h"

 #define dht_apin A1
 #define backlight_pin 11

 dht DHT;

 U8GLIB_PCD8544 u8g(8, 4, 7, 5, 6);  // CLK=8, DIN=4, CE=7, DC=5, RST=6

 const uint8_t brainy_bitmap[] PROGMEM = {
  0x00, 0x00, 0x03, 0xB0, 0x00, 0x00, 0x00, 0x00,
  0x07, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x46,
  0x00, 0x00, 0x00, 0x00, 0xFC, 0x47, 0xC0, 0x00,
  0x00, 0x01, 0xCE, 0x4C, 0x60, 0x00, 0x00, 0x03,
  0x02, 0x58, 0x30, 0x00, 0x00, 0x03, 0x02, 0x58,
  0x10, 0x00, 0x00, 0x02, 0x02, 0x58, 0x18, 0x00,
  0x00, 0x03, 0x06, 0x4C, 0x18, 0x00, 0x00, 0x07,
  0x04, 0x44, 0x18, 0x00, 0x00, 0x0D, 0x80, 0x40,
  0x3C, 0x00, 0x00, 0x09, 0xC0, 0x40, 0xE6, 0x00,
  0x00, 0x18, 0x78, 0x47, 0xC2, 0x00, 0x00, 0x18,
  0x0C, 0x4E, 0x02, 0x00, 0x00, 0x1F, 0x86, 0x4C,
  0x7E, 0x00, 0x00, 0x0E, 0xC6, 0xE8, 0xEE, 0x00,
  0x00, 0x18, 0x43, 0xF8, 0x82, 0x00, 0x00, 0x10,
  0x06, 0x4C, 0x03, 0x00, 0x00, 0x30, 0x0C, 0x46,
  0x01, 0x00, 0x00, 0x30, 0x18, 0x46, 0x01, 0x00,
  0x00, 0x10, 0x18, 0x43, 0x03, 0x00, 0x00, 0x18,
  0x10, 0x43, 0x03, 0x00, 0x00, 0x1C, 0x70, 0x41,
  0x86, 0x00, 0x00, 0x0F, 0xE0, 0x40, 0xFE, 0x00,
  0x00, 0x09, 0x1E, 0x4F, 0x06, 0x00, 0x00, 0x08,
  0x30, 0x43, 0x86, 0x00, 0x00, 0x0C, 0x20, 0x41,
  0x86, 0x00, 0x00, 0x06, 0x60, 0x40, 0x8C, 0x00,
  0x00, 0x07, 0x60, 0x40, 0xB8, 0x00, 0x00, 0x01,
  0xE0, 0x41, 0xF0, 0x00, 0x00, 0x00, 0x38, 0xE3,
  0x00, 0x00, 0x00, 0x00, 0x0F, 0xBE, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0xCF,
  0x82, 0x0C, 0x86, 0x46, 0x1F, 0xEF, 0xC3, 0x0C,
  0xC6, 0xEE, 0x1C, 0xEC, 0xC7, 0x0C, 0xE6, 0x7C,
  0x1C, 0xED, 0x8D, 0x8C, 0xFE, 0x38, 0x1C, 0xED,
  0x8D, 0xCC, 0xDE, 0x38, 0x1D, 0xCD, 0xDF, 0xCC,
  0xCE, 0x38, 0x1F, 0x8C, 0xF8, 0xEC, 0xC6, 0x38,
  0x1F, 0xEC, 0x08, 0x0C, 0xC2, 0x18, 0x1C, 0xEC,
  0x00, 0xC0, 0x00, 0x00, 0x1C, 0xFD, 0xFB, 0xC0,
  0x00, 0x00, 0x1C, 0xFC, 0x63, 0x00, 0x00, 0x00,
  0x1C, 0xEC, 0x63, 0xC0, 0x00, 0x00, 0x1F, 0xEC,
  0x60, 0xC0, 0x00, 0x00, 0x1F, 0xCC, 0x63, 0xC0,
  0x00, 0x00, 0x1F, 0x0C, 0x63, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x28, 0x2B, 0x4F, 0x67,
  0x42, 0x38, 0x7B, 0xEA, 0x86, 0xB2, 0x28, 0xC7,
 };

 void draw(void) {
   u8g.drawBitmapP( 0, 0, 6, 50, brainy_bitmap);  // put bitmap
   u8g.drawStr(10, 10, "% ");

 void loop(void) {

   u8g.firstPage();
   do {
     draw();
   } while( u8g.nextPage() );

     delay(5000);  // Delay of 5sec before accessing DHT11 (min - 2sec)
   }

I have the same problem ....with NOKIA5110 display ,I gave it a slight downwards press just as I upload the code and then it works ,but as soon as I release it just goes blank.
Hooked up my resistors and made sure wires in correct pins ,so this is what I experience.

There are several possibilities.
Arduino GPIO pins drive outputs to ground or 5V.
The pins on the Nokia 5110 LCDs boards I have are not 5V tolerant. So you might have damaged them when the Arduino's GPIO connected to 5V.
A simple fix is to put a 10k ohm resistor in each signal path, i.e.

sce -- pin 7
rst -- pin 6
d/c -- pin 5
DN -- pin 4
sclk -- pin 8

You could get a level-shift chip, or build a circuit, but resistors are quick, cheap and easy.
I would strongly recommend using a very simple Arduino library to get the display working. Then, once everything is working, continue with your current approach. All you need is a simple test; something which turns pixels on and off to check that it works.
I have had good results with the Arduino Playground Philips PCD8544 (Nokia 3310) driver
I have several Nokia 5110's. A few needed the values loaded at initialisation to be tweaked, to make the display visible.
Specifically in void LcdInitialise(void):
  LcdWrite(LCD_C, 0x21 );  // LCD Extended Commands.
  LcdWrite(LCD_C, 0xB1 );  // Set LCD Vop (Contrast).
  LcdWrite(LCD_C, 0x04 );  // Set Temp coefficent. //0x04
  LcdWrite(LCD_C, 0x14 );  // LCD bias mode 1:48. //0x13
  LcdWrite(LCD_C, 0x20 );  // LCD Basic Commands
  LcdWrite(LCD_C, 0x0C );  // LCD in normal mode.

I have had to tweak Set Temp coefficent, LCD bias mode 1:48 and Set LCD Vop (Contrast) to get make the display clear, without looking washed-out, or all-dark. Using a very simple library like the Philips PCD8544 (Nokia 3310) driver should make it easy to adjust this until things work well.

ok I did this and I used a multimeter to measure the voltage it was 5.01 volts. I didn't have 10k resistors so I used a 6k leading to a 4k and then to the sreen, should that work?

You're just trying to reduce the input current so that nothing gets damaged. So 10k made from two resistors should be fine.

Assuming you got your code from this site: https://brainy-bits.com/tutorials/how-to-use-the-nokia-5110/, it seems you edited the code from there to display only the bitmap, but you didn't get rid of everything. You have no DHT temperature sensors, so get rid of all DHT references in your code, including the 5 seconds delay at the bottom of loop(). If you intend to use the code from that site, then use it this way:
void draw(void) {
  u8g.drawBitmapP( 37, 0, 6, 50, brainy_bitmap);  // put bitmap
}

void setup(void) {
  analogWrite(backlight_pin, 50);  /* Set the Backlight intensity */
}

void loop(void) {
  u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );

}

Make sure to get rid of the #define, #include and constructor referring to DHT.

Change your pinouts. HW SPI needs 13 and 11, not 8 and 4. Try this short bit of code:
#
include <U8glib.h>

#define RST 6
#define CE  7
#define DC  5        //  D high is data, C low is command.
#define DIN 11
#define CLK 13
#define Backlight 9  // Don't forget the 330 ohm resistor.

//Declare the display and assign the pins.
  U8GLIB_PCD8544 u8g(13, 11, 7, 5, 6);  // CLK=13, DIN=11, CE=7, DC=5, RST=6

void draw() {
  u8g.setFont(u8g_font_profont11);      // Select font
  u8g.drawStr(0, 15, "Nokia 5110...");  // Put string of display at position X, Y.
  u8g.drawStr(29, 35, "HELLO!!!");
}

void setup() {
    analogWrite(Backlight, 80);  // Set Backlight Intensity, 0 is fully bright, 255 is off.
}

void loop() {                    // Enter the U8Glib Picture Loop
 u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );
}


text:
Push-Pull tone code
I wanted to use a piezo sounder to sound an alarm in an application. Testing indicated that tone() was not very loud.
I could use some external circuitry to swing the pins ±5V but as I have plenty of spare pins, it seemed feasible to use 2 pins driven in anti-phase to increase the power by 4.
I looked at the source Tone.cpp but the code is somewhat intimidating. Before I start to modify it I was wondering if anyone else has already done something like this.

Wouldn't you still end up with the total voltage difference across the two pins being at most 5V?

@dlu No The swing is 10V. Think about it - this is a standard technique.

-1. No, the swing is 5V, unless you generate 10V with a boost converter or generate a -5V rail. Fundamental flaws in your plan aside, yes it's possible to add an anti-phase pin to the mix a few edits to the Tone library.

@CharlieHanson No, the swing is 10V. At any moment in time the instantaneous voltage between the two outputs is 5V, but into an inductive load (speaker, moving coil) the displacement is double since you are inverting the polarity all the time, and first pushing the coil with +5V and then pulling the coil with -5V giving the equivalent drive displacement of 10V with a -5V offset.

Yes, Tim Eckel has already published a library "toneAC" on the Arduino website at http://playground.arduino.cc/Code/ToneAC
All of the syntax is there too.

source: Stack Exchange

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

sort: votes


text:
constant current or constant voltage power supply to use with RGB shield with high power LEDs
So, I got an arduino uno and a RGB shield from velleman for christmas because I mentioned I might want to do a project with high power LEDs - a neat surprise, but now I have to use it (:
The shield can do PWM on an external power supply and this can be wired through to the high power LEDs itself. I aim to power about 10W of LED light in total, with different colors in order to make good use of the board. Can I go for Option 1? If not, what would you advise?
Option 1
As high power LEDs need a constant current, I am inclined to connect a constant current supply as the external supply of the board (assuming all channels' LEDs need the same current).
Update: I talked to an electrician and a constant current supply typically works on a PWM basis; putting this in series with the PWM of the shield is not smart.
Option 2
Alternatively I could connect a standard constant voltage supply and make sure that the current is within limits:

One option would be to use resistors; but, with 12V DC and 350mA I would need like 33 Ohm resistance dissipating 4 Watts of power, which is inefficient.
Alternatively there are DC voltage to constant current LED drivers which will take care of the constant current for me; I could put those at the exits of the shield for the LEDs. They supposedly have a better conversion efficiency than the resistors, but I do have any knowledge about their performance with PWM as input; but I have serious doubts they would like that type of input. Furthermore, these drivers also often have PWM capabilities. This kind of module would render the shield functionality largely useless.

What kind of led(s) are you using?

@Gerben I did not buy a specific LED yet, I was looking into the star platine LEDs, say, xcree or the ones I linked. I heard from LEDs with included current limiters but did not find any (and I do not know how they will react to PWM signals). I would prefer RGB LEDs as I want to mix colors. I am very open to suggestions (:

Option 1 is a boost circuit. At least it says it is. So you can't use it for a single led. I'd go with the last option. If you want something cheaper, you could use this board though you have to solder to the PWM directly, as there isn't a pad/connector for it.

Uhm, I think you'd better go with the solution velleman propose you, so use a common RGB strip. I think you can use a 5m 5050 rgb strip with 60 leds/m (they usually take 40mA/m/channel, so it is 6A in total). Put a 12V 10A supply and you have a lot of RGB leds. Avoid the 3825 led strips (what they call 3825 rgb led strip actually has R, G and B separated leds; you want the 5050 version, which have R,G and B in the same package)

Your thinking and reasoning is pretty much spot on.
The board you have is basically a trio of high current low side switches. So yes, you need something to limit the current, and as you have noted resistors are not going to be very efficient.
The best way to drive high power LEDs is, as you know, with constant current. However, you need a constant current source per LED channel, not one single one for the whole board. That means three individual constant current sources, each providing the right current for the LEDs you are driving on that channel.
It's possible to roll your own cheap constant current sources using LM317T linear voltage regulators (http://diyaudioprojects.com/Technical/Current-Regulator/). It's a cheap option, though pretty much as in-efficient as using resistors, just easier to deal with the heat sinking.  Note that on the LM317T the tab is live, so you must use three separate heat sinks for each channel.
My personal preference though is to use PWM capable constant current sinks. My favourite is the CAT4101 which can deal with up to 1A per channel (more if you parallel them) and uses a single resistor to set the current. It has a PWM input that you can drive direct from an Arduino's PWM pin. Of course, as you note, that then makes your nice shield redundant.

Now that I have the board I feel kind of inclined to use it (:
I understand you correctly, that I should not use the board with a constant current source (even per channel) as they will likely not be able to handle the fast PWM input voltages well?
Given the effort of the LM317T, I am more prone to use resistors; I might put LEDs parallel, each line with its own resistor. Choosing a low supply voltage should further limit unwanted power dissipation.

Resistors are by far the simplest solution, yes. Spreading the load as much as possible can only be a good thing :)

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


text:
Making AC current with pin 11
I'm trying to make AC current (50Hz) with an Arduino Uno. It seems to be not working (or wrong code).
int up;
int down;
int out = 11;
void setup() {
  pinMode(out, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  for (up = 0; up <= 255; up++) {
    analogWrite(out, up);
    delay(1);
  }
  for (down = 255; down >= 0; down--) {
    analogWrite(out, down);
    delay(1);
  }
}

Update:

Now the code above is giving output voltage of 0-5V (getting increased from 0 to 5 and then decreased) not giving a negative cycle (-5V).
After setting the minimum delay of 1, the output wave is still half wave rectifier with frequency 2Hz.
Without delay LED is blinking so fast I don't know what's its frequency.

How do I make make 50Hz AC current a with negative cycle?

The UNO doesn't have a DAC. So you need to filter the PWM output to get an analog AC voltage.

What you have there (apart from your lack of brackets on the for which breaks it all) is code for a saw-tooth wave (if you filter it) at 1.95Hz.

Your code shows a real lack of understanding of the basics of C programming.

ohhh, i thought arudino analogWrite output is sin wave. After watching this https://www.arduino.cc/en/Tutorial/PWM it's seems like arduino gives output only in digital wave.

It's digital (as in Pulse Width Modulation) but when filtered (low pass filter) it forms an analog voltage. By setting the duty cycle (analogWrite) in the right way you can form one discrete part of an AC waveform. If you want a sine wave then you have to form a sine wave out of discrete values.

Normally that is done using a look-up table (LUT) since calculating values of sin is far too slow on a little 8-bit MCU.

@Majenko updated the for loop and also code. Checked with multimeter on AC it's showing around 5V and on DC it's showing around 2.5V. seems like half AC current at 50Hz is created. now working on low pass filter.

Your code is still far from correct. There's bits there that aren't wanted, and the bits that are wanted are in the wrong place (and the wrong value, and just plain wrong).

I ran your sketch and this is the output signal:

analogWrite produce a square wave.
As Majenko said, you have to add a low pass filter to get that sine wave.

If you are not critical on the waveform you can use a transformer where the secondary has a center tap. The primary should have one as well. Tie the input center tap to +12 or whatever is available but DO NOT use the arduino 5 volt pin. Then using two avalanche protected N channel MOSFETs you them to drive the remaining two input leads.  The output will be a pseudo sine wave, far from perfect but it will have the negative excursion you want.This type of circuirity can be found in Switch Mode Power Supplies (SMPS). Note the transformer winding ratio will determine your output voltage. You will need a little dead time between turning one MOSFET off and the Other on.  A single mosfet would work but there would only be two connections to the transformer primary not 3 and the wave form will be a lousy.

You do realize you're answering a more than 4 year old question, I hope. Your answer would benefit greatly from a schematic.

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


text:
Arduino TMP36 sensor
I am following the tutorial Tiny WiFi Temperature Sensor with Arduino. everthing works fine, but I have a little problem.
When the serial monitor is opened the sensor is reading fine like 23.20, 20.25 etc.,  but when I closed the serial monitor window I got wrong values, for example, 289.34, 289.90.
What does the serial monitor do?
I am stuck with this problem for last two days. Please give me a hand.

The baud rate is as you can see 115200 and i have changed it various time but it doesn't do anything.
I haven't test commenting out the Serial.println() lines
The values i can see at my server (see the function send_request).
The problem is when i am testing the program opening the serial monitor windows everything works fine for example: 29.20, 30.12, 28.12 but when i close the windows i start getting wrong values for exmaple: 289.45, 289.89 , etc... .

Here is my code.
#include <Adafruit_CC3000.h>
#include <Adafruit_CC3000_Server.h>
#include <ccspi.h>

/*
   Tiny WiFi temperature sensor with Arduino, the TMP36 sensor & the CC3000 chip
   Writtent by Marco Schwartz for Open Home Automation
*/

// Include required libraries

#include <SPI.h>
#include <string.h>
#include "utility/debug.h"
#include<stdlib.h>

// Define CC3000 chip pins
#define ADAFRUIT_CC3000_IRQ   2
#define ADAFRUIT_CC3000_VBAT  A3
#define ADAFRUIT_CC3000_CS    8

// WiFi network (change with your settings !)
#define WLAN_SSID       "ssid"        // cannot be longer than 32 characters!
#define WLAN_PASS       "password"
#define WLAN_SECURITY   WLAN_SEC_WPA2 // This can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2

// Create CC3000 instance
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                         SPI_CLOCK_DIV2);

// Local server IP, port, and repository (change with your settings !)
uint32_t ip = cc3000.IP2U32(10,0,129,108);
int port = 8080;
String repository = "/tiny-wifi-temperature/";

void setup(void)
{

  Serial.begin(115200);
  Serial.println("Start setup");

  // Initialise the CC3000 module
  if (!cc3000.begin())
  {
    Serial.println("Impossible to start");
    while (1);
  }

  Serial.println(F("\nDeleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  listSSIDResults();
  connectNetwork();
  displayConnectionDetails();
  /*
  while(!displayConnectionDetails())
  {
    connectNetwork();
  }*/

}

void connectNetwork(void)
{
  Serial.println(F("Trying to connect wifi ")); Serial.println(WLAN_SSID) ;

  /*
  uint32_t ipAddress = cc3000.IP2U32(10, 0, 130, 200);
  uint32_t netMask = cc3000.IP2U32(255, 255, 0, 0);
  uint32_t defaultGateway = cc3000.IP2U32(10, 0, 1, 1);
  uint32_t dns = cc3000.IP2U32(10, 0, 1, 1);
  if (!cc3000.setStaticIPAddress(ipAddress, netMask, defaultGateway, dns)) {
    Serial.println(F("Failed to set static IP!"));
    while(1);
  }
  */

  /*
  if (!cc3000.setDHCP()) {
    Serial.println(F("Failed to set DHCP!"));
    while(1);
  }*/

  // Connect to  WiFi network
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }
  Serial.println("Connected to WiFi network!");

  // Check DHCP
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100);
  }

}

void loop(void)
{

  // Measure the temperature
  int sensorValue = analogRead(A4);
  float milliVoltsValue = sensorValue * 5000. / 1024.;
  float temperature = (milliVoltsValue - 500.) / 10.;

  // Print the result
  Serial.println(temperature);

  // Transform to string
  char temp[5];
  dtostrf(temperature, 5, 2, temp);

  // Send request
  String request = "GET " + repository + "sensor.php?temp=" + String(temp) + " HTTP/1.0";
  send_request(request);

  // Update every second
  delay(1000);
}

// Function to send a TCP request and get the result as a string
void send_request (String request) {

  // Connect
  Serial.println("Starting connection to server...");
  Adafruit_CC3000_Client client = cc3000.connectTCP(ip, port);

  // Send request
  if (client.connected()) {
    client.println(request);
    client.println(F(""));
    Serial.println("Connected & Data sent");
  }
  else {
    Serial.println(F("Connection failed"));
  }

  while (client.connected()) {
    while (client.available()) {

      // Read answer
      char c = client.read();
    }
  }
  Serial.println("Closing connection");
  Serial.println("");
  client.close();
}

void listSSIDResults(void)
{
  uint32_t index ;
  uint8_t valid , rssi, sec ;
  char ssidname[33];

  if (!cc3000.startSSIDscan(&index)) {
    Serial.println(F("SSID scan failed!"));
    return;
  }

  Serial.print(F("Networks found: ")); Serial.println(index);
  Serial.println(F("================================================"));

  while (index) {
    index--;

    valid = cc3000.getNextSSID(&rssi, &sec, ssidname);

    Serial.print(F("SSID Name    : ")); Serial.print(ssidname);
    Serial.println();
    Serial.print(F("RSSI         : "));
    Serial.println(rssi);
    Serial.print(F("Security Mode: "));
    Serial.println(sec);
    Serial.println();
  }
  Serial.println(F("================================================"));

  cc3000.stopSSIDscan();
}

bool displayConnectionDetails(void)
{
  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

  if (!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
  {
    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
    return false;
  }
  else
  {
    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
    Serial.println();
    return true;
  }
}

Even though you've provided a link to the circuit (sort of) and the code that you think you're using, it would be good to include the actual code and some kind of documentation of the circuit – maybe a photo of what you've built. Also tell us what you've done so far towards debugging the problem. That will help us to focus and also to avoid telling you what you already know…

The incorrect values, I presume after reading the article, are seen on the browser at localhost?

The serial monitor gives you a way to "talk" relatively directly with the Arduino – in this case it give you a way to easily confirm that the basic circuit is working and that you are getting sensible temperatures. That's a foundation on which you can build.
It is unlikely – I think – that the serial monitor is causing the problem. But before you believe me, there is one thing you should consider. The serial monitor runs relatively slowly, so outputting the temperature via the serial monitor introduces a delay in your code. That could explain the difference.
So your next step is to trace your bad value. So, first more questions:

What baud rate are you running the serial monitor at? Does changing the baud rate affect the result? That would point to a timing related issue.
Is there any code that writes to the serial monitor (e.g., a call to Serial.println())? If there is what happens when you comment it out?
Where are you seeing the two values (the correct and incorrect values)? I assume that both are at the web server, but I want to confirm this.
Can you explain more clearly the process to demonstrate the problem? In the tutorial that you link to I don't think that the code pathway is the same to see the value on the serial monitor as it is on the server, so I'm wondering if an error was made as you changed the code.


text:
Arduino compiler uploading last saved version of sketch, not current
Is this an issue or a defined behavior? I am using Arduino IDE 1.6.6
Sometimes I made changes in code, and immediately upload them to the Arduino board. And many times issues already fixed are persisting, leaving me that feeling of "the uploaded code has not the changes I have just made". Then I save my sketch, compile and upload again and the issue vanishes. As long as the issue get someway fixed, I tend to forgot about it.
As software engineer, most of the times I assume the code I am compiling and uploading / publishing to any platform is always the latest, not the latest saved. I believe this is not the behavior of the Arduino IDE. It uploads the last saved version of code, not the last modified.
In summary: I believe the Arduino IDE uploads to the board the last saved version of the sketch, not the current one being modified. Can anyone confirm this?
Thanks in advance.

I can't confirm that since I use an external editor, which necessitates saving before compiling.  I sometimes use a menu which I wave the mouse over to compile+upload.  ¶  See the last post or two in topic #46983 in forum.arduino.cc which depending on interpretation may or may not suggest that in 2010 it did not work as you say.

I can't prove it (i.e., I haven't looked at the code), but it seems to me that 1.6.6 saves before uploading – seems worth a test. Also worth mentioning the platform where you're seeing this behavior. I'm on a MacBook Pro running OS X 10.11.2.

Yeah, the option is on. I am on Windows 10. If it's working correctly, then I probably had some issue with the upload, or simply believing I uploaded the last version when actually didn't. I would like to discard as much clues as possible, I hate this kind of "magic" fixes. Thank for your replies!

If you were not using an external editor, it would be the latest, whether it is saved or not.  In that case, just use Ctrl-S before the Ctrl-U when uploading.  It will save it and upload it.  If an external editor, do the Ctrl-S there, then Ctrl-U in the IDE.  Don't trust the auto-save option when using an external editor.

I haven't tried it but it would be an easy experiment to make on some throw-away code.
However, do note that saving before compiling or uploading is optional in the Arduino IDE. That may very well be the key to what you observed. I keep mine enabled, i.e., to save before any compile or upload. The option is in the Preferences dialog accessed from the menus, not in the manually-edited preferences.txt file. That might be the key to what you observed.
Update:
In that case, including the pre-defined macros __DATE__ and __TIME__ (of the pre-processor run) and __TIMESTAMP__ (of the file's last modification) in a "Hello" string can help debug this.
These pages list the standard, and common predefined macros implemented in gcc's pre-processor.
Note also that most version control systems offer similar macros that get replaced at checkout to embed a revision number and other version-control information.

Thanks for your reply. Apparently I have the option to save when compiling or uploading on, but I still face some "outdated code" like issues. They got fixed after save, compile and upload. I am guessing now that I may had an upload error. Or not uploading at all. But I would like to discard as most clues as possible. Apparently, the IDE is saving my files as expected... (assuming there is no open bugs on that feature).

In the general sense things like __TIME__ may not fairly depict the compilation flow as these would not cause the editor aspect of the IDE to report that there have been any program changes to invalidate a cached compilation.  For example with a traditional Makefile setup timestamps like this don't work unless something else forces a rebuild of the code where they appear.  So this isn't really a good test; making a trivial change for example to a printed string would be.


text:
Nothing is working even though every thing is right & it is new?
I have bought a new 'SunFounder Arduino uno R3' and started learning, the first lesson was 'Blinking LED' of course.
I have done it all, connected Jumper-Wires and the Sensor and the LED light, I wrote the code:
const int ledPin = 9;
void setup()
{
   pinMode(ledPin,OUTPUT);
}
void loop()
{
   digitalWrite(ledPin,HIGH);
   delay(500);
   digitalWrite(ledPin,LOW);
   delay(500);
}

BUT NOTHING HAPPENS !!!, I checked out every thing over and over, it just does not work ???
Every thing is well about the board and the UNO R3 it is new.
I have checked the code and the connections and checked the Device Manager to know that the serial port of the arduino is 'COM3'...
I dont know what is wrong with it ?!!

have you tried the built in LED on pin 13?

I did just now "Changed the Wire from 9 to 13 and on the code too. nothing happened

No wire should be necessary; leave the arduino disconnected from everything but the PC and set ledPin to 13.

As mentioned by BrettAM, pin 13 is good for testing since nothing needs to be hooked up. Also, be sure that the Arduino IDE has been set to the correct COM port and that the model of the device has been set correctly in the menus before uploading the sketch. You did upload the sketch, right? (compiling is not enough) When you upload the sketch, does the serial transfer light blink rapidly for a brief moment to show that the upload is taking place?

I did it worked with the light inside the arduino but what about the led ? Still not working!

Yeah Every thing u said I have done it... All right but led not blinking

Can you post a good quality, well focused picture of your setup, showing where all the wires are connected?

Try another LED (of which you know is working). Don't forget the current limiting resistor. And check some other pins. Try to invert the LED, they only work one way.

Oh sorry Guys I just figured out that the bread board sends electric power in line so I have to connect every wire with the same line that fits (+side of the LED or -side) yeah I didn't know that... So sorry for westing ur time and thanks u all.

In these cases it helps to break down the problem in pieces.
If the internal LED on pin 13 blinks with your code it means that the software side is OK so far (code, Arduino type, compiling, uploading etc), so I suggest looking at the physical side of things.
Do you have a multimeter available? If so, connect it between pin 13 and ground and it should show you if the output works.
Finally, is the LED working? When you connect it between 5V and GND (with a resistor!) it should light up.

Sorry for westing ur time friend, I just didn't know that the bread board sends power in lines my bad sorry and Thank u...


text:
Programing in Assembly for the Digispark
I've been given a digispark and am looking to write straight assembly code for it. Anyone know how to get started with this? I've been successful in getting the Arduino IDE set-up but would really like to avoid writing assembly in-line...

If you want to write assembly, ditch the arduino IDE and just use the avr toolchain straight.

@BrettAM I've really been trying to figure it out. Know of any good tutorials that might help? Appreciate the response.

Why do you want to? Seriously.

There seems to be some specific attiny flag required but by the gcc in order to make the genereated hex file work with digispark. Take a look here https://github.com/pda/digispark-asm.

A specific flag? You mean -mmcu=attiny85?

I've been given a digispark and am looking to write straight assembly code for it. Anyone know how to get started with this? I've been successful in getting the Arduino IDE set-up but would really like to avoid writing assembly in-line...

The Arduino IDE build support assembly files (.S). Nerd Ralph has written a  blog on the subject. There you will find all the details and how to write both inline and pure assembly files. He is really god at digging out all the details and sharing his findings.

In 2021, I use VSC + Platformio.
I create a main.asm file in which I put the code from https://github.com/pda/digispark-asm.
In the "platformio.ini" file I define the digispark as :
[platformio]
default_envs = digispark-tiny
[env:digispark-tiny]
platform = atmelavr
board = digispark-tiny
I run the code, upload it to a digispark and this works amazingly well.


text:
Arduino raise the error "variable-sized object 'my2dArray' may not be initialized" while trying to change the elements of 2d array
I' m trying to change 1 to 0 in two-dimensional (5x5 matrix) for specific servo positions.First, i tried to program forward movement of my robot.  My code is like this:
#include <Servo.h>
#define x 5
#define y 5

Servo myServo;
Servo myServo2;

int pos = 0;

int counter1;
int counter2;
int integer;

void setup() {
  Serial.begin(9600);
  myServo.attach(9);
  myServo2.attach(10);
}

void loop() {

  int my2dArray[x][y]= {
  {1,1,1,1,1},
  {1,1,1,1,1},
  {1,1,0,1,1},
  {1,1,1,1,1},
  {1,1,1,1,1},
  };

  int robot = my2dArray[2][2];

   if (counter1 > 0){
     for (integer = 0;  integer <2; integer +=1){
      int my2dArray[2 + integer][2] = robot * my2dArray[2 + integer][2];

     }
 }
}

  int moveForward(){
  for (pos = 0; pos <= 360; pos += 1) {
    myServo.write(pos);
    myServo2.write(pos);
    delay(15);
    if (pos == 360){
    counter1 += 1;
    }
    return counter1;
}
}

int moveBackward(){
  for (pos = 360; pos <=0; pos -= 1) {
    myServo.write(pos);
    myServo2.write(pos);
    delay(15);
    if (pos == 360){
    counter2 += 1;
    }
    return counter2;
}
}

But i can' t change the [3][2] and [4][2] elements from 1 to 0. I get an error:
 error: variable-sized object 'my2dArray' may not be initialized

Can you help me?
Thanks.

Apart from the error mentioned below, you're using counter1 and counter2 before they are initialised.

The error is in this line:
  int my2dArray[2 + integer][2] = robot * my2dArray[2 + integer][2];

The presence of the word int there tells it to try and make a new variable. You don't want to do that, since it's an error.  Lose the int and it might work.

Yes @Majenko is correct - You're re-declaring another array of the same name.  The loop counter "integer" is confusing too, since it sounds a little like "int".  It's common practice to use i, j and k as simple for() loop variable names.


text:
Trouble when avoiding delays
I am new to Arduino and I am learning how to avoid using delay.
I have written some code to move my servo by 20° using delays, but can only move the servo once with my current code. In setup(), I assign the servo 150. The next value the servo receives is 15, which it performs. It does not iterate through the following values though. I have been using this guide, BlinkWithoutDelay, with no luck.
Here is my code:
#include <Servo.h>
Servo myservo;
unsigned long previousMillis = 0;
const long interval = 1000;

    void setup() {
       myservo.attach(9);
       myservo.write(150);
    }

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

       if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            myservo.write(15);
       }
       if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            myservo.write(35);
       }
       if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            myservo.write(65);
   }

You are resetting the timer on the first phase [write(15)] instead of after the last phase [after write(65)]! The previousMillis = currentMillis should be only after the last phase, before the loop repeats. Not only that, but the time at which each phase executes needs to be different. Currently every if() statement is set to run after interval has elapsed. If, for example, you wanted interval to be the delay between each phase, you could use interval*1 on the first phase, interval*2 on the second, and interval*3 on the third. For example:
   if (currentMillis - previousMillis <= interval * 1) {
        // Runs from interval*0 to interval*1;
        myservo.write(15);
   }
   else if (currentMillis - previousMillis <= interval * 2) {
        // Runs from interval*1 to interval*2;
        myservo.write(35);
   }
   else if (currentMillis - previousMillis <= interval * 3) {
        // Runs from interval*2 to interval*3;
        myservo.write(65);
   }
   else {
        // Runs once after interval*3;
        // *or* runs on first iteration when previousMillis is zero;
        previousMillis = currentMillis;// Reset the loop;
   }

To put the above logic in English:

write(15) while time is between 0 and 1 intervals;
write(35) while time is between 1 and 2 intervals;
write(65) while time is between 2 and 3 intervals;
reset the loop once time reaches 3+ intervals.

Note the use of else if instead of simply if on consecutive statements. This prevents more than one code block from running on the same iteration of the loop().
Edit: I highly recommend having a small delay (like 1ms) somewhere in the loop(), such as at the end. It would be a bad idea to constantly run the write() function when the value is the same as on the last call.
On the other hand, if your starting value is indeed 150 and the loop should start only after interval*1, you may want to iterate from interval*2 through interval*4:
   if (currentMillis - previousMillis <= interval * 1) {
        // Runs from interval*0 to interval*1;
        // Do nothing; servo is set to either 150 or 65 during this time;
   }
   else if (currentMillis - previousMillis <= interval * 2) {
        // Runs from interval*1 to interval*2;
        myservo.write(15);
   }
   else if (currentMillis - previousMillis <= interval * 3) {
        // Runs from interval*2 to interval*3;
        myservo.write(35);
   }
   else if (currentMillis - previousMillis <= interval * 4) {
        // Runs from interval*3 to interval*4;
        myservo.write(65);
   }
   else {
        // Runs once after interval*4;
        // *or* runs on first iteration when previousMillis is zero;
        previousMillis = currentMillis;// Reset the loop;
   }

If you want to change the servo every second, try to use a conditional expression in the timing structure. If you want to use more parallel structure with multiple intervals use different counters (example see: here).
Here is an example of the every second version:
#include <Servo.h>
Servo myservo;
unsigned long previousMillis = 0;
const long interval = 1000;
int angle = 150;

void setup() {
   myservo.attach(9);
   myservo.write(angle);
}

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

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

        switch (angle) {
            case 150:
            case 65:
              angle = 15;
              myservo.write(angle);
              break;
            case 15:
              angle = 35;
              myservo.write(angle);
              break;
            case 35:
              angle = 65;
              myservo.write(angle);
              break;
        }
    }
}

EDIT: Add variable assignment angle in conditional expression.

You should probably also set the angle to the one you have just written in each switch case.

If instead of "previousMillis = currentMillis;" you do a "previousMillis -= interval'; then your intevals will absorb the other processing times and won't drift.


text:
Menu system without libraries
I was wondering if there are a way to do a menu system for arduino UNO using buttons and without libraries.
I tried to do it by myself but the code was too long and heavy.
I don't want full code, just a pseudo-code idea and how does it works.
I know there are libraries that to this, but I want to practise C++.
Thanks!

Interactive menus are certainly not a "simple" task. That is why people use libraries.
Whatever you try you will end up with complex code - either long winded with lots of duplication, or somewhat cryptic with lots of pointers, arrays, and structures. Not an easy task for a beginner in C++.
How I would set about it would involve the following things:

A structure that defines a menu entry, including pointers to one of: sub-menu array, numeric variable (including max/min limits), option array, function to execute.
Arrays of the above structure to define each menu
Array or linked list of "breadcrumbs" through the menu to track where you are and go back up properly
Functions to display and navigate the menu arrays on an LCD.

All of that uses fairly advanced C coding techniques, especially when it comes to managing all the pointers, etc.
The "simpler", though more long winded way, would be to write individual functions for each menu and sub-menu, but that would make your program incredibly long and prone to have errors when duplicating (copy/paste) code.

agree, i would add that all those structures probably will end up taking a lot of ram.. and sooner or later you will end up wanting them on flash memory, bringing even more complexity to your code, but yes, go for it! its a good chance to later appreciate a library and still learn a lot of c++ :D


text:
Which Bluetooth Module can I use with Arduino Micro/Mini?
I need to use a Bluetooth module with an Arduino Micro/Mini.
Please suggest which one would be the best, HC 05/06, or any other?

It depends on what you want the module to do. For just serial communication the HC modules are fine. For anything more complex you may want to look at BLE.

What research have you done so far?

I have had good results using the Bluefruit LE UART Friend module from Adafruit with a 32u4 micro Arduino type module, there are only a few pins to connect up to get things going (do remember to follow the instructions to pull the CTS pin to ground).
As per the previous answer it really does depend on what you want to do with it - but this module does Low Energy, can be configured as a "Beacon" and there is a companion App for Android/iOS.

Do you require slaves or masters?
Both modules are actually the same, it is just the firmware that is different, and in turn that changes how they use the pins. HC05 can be both Master and Slave, and has a full set of AT commands, whereas HC06 can only be a slave, and has a more limited set of AT commands at its disposal.
Otherwise, for low power projects, then BLE modules, such as HC-10 or HC-11 might be worth considering.
Really, it all depends on what you want to do with them, what is the overall project? You could get away with one HC-05 and one HC-06, but it is really task dependant. It is probably worth you having a read up of some articles on the web, and looking at some example projects to see other people's configurations. This will hopefully help you to see what you actually require for your project.
FWIW, I looked into this a few months back and wrote a short blog, BlueMoon, on it, which contains some example projects and links to video tutorials - this may help give you an insight...


text:
Explanation for micros function
I was trying to understand the working of micros() function internally and I had a look at the function in Arduino.h
This is the code:
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;

    cli();
    m = timer0_overflow_count;
 #if defined(TCNT0)
    t = TCNT0;
 #elif defined(TCNT0L)
    t = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

#ifdef TIFR0
        if ((TIFR0 & _BV(TOV0)) && (t & 255))
        m++;
#else
        if ((TIFR & _BV(TOV0)) && (t & 255))
        m++;
#endif

    SREG = oldSREG;

    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

Can someone please explain me what this line is doing :
  if ((TIFR0 & _BV(TOV0)) && (t & 255))
   m++;

If the timer 0 has overflowed (TIFR0 & _BV(TOV0)) and there is at least a count of 1 in the timer count register (t & 255) then increment the local copy of the overflow count.
That overflow count is used later on to add an upper 8 bits to what is basically an 8 bit counter to turn it into a 16 bit one ((m << 8) + t).

can you please explain me "timer0_overflow_count" too?

It's the current count of timer overflows - it's incremented in an interrupt routine elsewhere.

Since at the start of this function interrupts have been disabled by the cli() function it is possible that the timer TCNT0 has overflowed yet this event has not been processed and included in the value of timer0_overflow_count that has been read into m. Therefore the line that you are asking about is checking for this condition and incrementing the local copy m if necessary before using it to calculate the number of microseconds since startup.


text:
LCD does not work with if condition
#include <LiquidCrystal.h>
#include <Wire.h>

LiquidCrystal lcd(2, 3, 4, 5, 11, 12);// initialize the library with the numbers of the interface pins

int pirPin = 7; //Variable that will receive the digital signal from the sensor
int LEDgreen = 6; //LED addressed to the digital pin 6
int speaker = 8; //speaker addressed to the digital pin 7
int buttonPin = 9; // the pin that the pushbutton is attached to

void setup(){
  pinMode(buttonPin, INPUT);// Initialize the button pin as an input:
  pinMode(pirPin, INPUT);  // declares variable pirPin as an input
  pinMode(LEDgreen, OUTPUT); // declares variable LEDgreen as an output
  pinMode(speaker, OUTPUT); // declares variable speaker as an output
  lcd.begin(16, 2);
  // turn on the cursor:
  lcd.cursor();
  Serial.begin(9600);
}

void loop(){
  int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
  int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal
  if(buttonState == LOW){
    if(digitalRead(pirPin) == LOW){
      /*The LED Blinks once with the command digitalWrite
      the LED keeps turned on after blink during the motion cycle*/
      digitalWrite(LEDgreen, HIGH);
      delay(1000);
      digitalWrite(LEDgreen, LOW);
      delay(500);
      digitalWrite(LEDgreen, HIGH);
      /*speaker plays frequency, the number 7 is the digital pin,
      the second number is the frequency played and the third number is the sound duration
      we repeated this command with different frequency and varying the time in order to create a
      pleasant sound */
      tone(4,261,300);
      delay(200);
      tone(4,329,300);
      delay(200);
      tone(4,392,600);
      delay(200);
      tone(4,329,300);
      delay(200);
      tone(4,392,300);
      delay(200);
      tone(4,493,600);
      delay(200);
      tone(4,392,300);
      delay(200);
      tone(4,493,300);
      delay(200);
      tone(4,294,600);
      delay(200);
      lcd.setCursor(0,0);
      lcd.print("  Motion  ");  // Print a message to the LCD.
      lcd.setCursor(0,1);
      lcd.print(" Detected ");
    } else if(digitalRead(pirPin) ==  HIGH) {
       digitalWrite(LEDgreen, LOW); // Turn off the LED in the case where no motion is detected
       lcd.setCursor(0,0);
       lcd.print("No Motion  ");
       lcd.setCursor(0,1);
       lcd.print(" Detected ");
     }
   } else if(buttonState == HIGH) {
     if(digitalRead(pirPin) == LOW) {
       digitalWrite(LEDgreen, HIGH);
       delay(1000);
       digitalWrite(LEDgreen, LOW);
       delay(500);
       digitalWrite(LEDgreen, HIGH);
       tone(4,261,300);
       delay(200);
       tone(4,329,300);
       delay(200);
       tone(4,392,600);
       delay(200);
       tone(4,329,300);
       delay(200);
       tone(4,392,300);
       delay(200);
       tone(4,493,600);
       delay(200);
       tone(4,392,300);
       lcd.setCursor(0,0);
       lcd.print("  Motion  ");
       lcd.setCursor(0,1);
       lcd.print(" Detected & door ");
     } else if(digitalRead(pirPin) ==  HIGH) {
       digitalWrite(LEDgreen, LOW);
       // Turn off the LED in the case where no motion is detected
       tone(4,329,300);
       delay(200);
       tone(4,392,300);
       delay(200);
       tone(4,493,600);
       delay(200);
       tone(4,392,300);
       lcd.setCursor(0,0);
       lcd.print("No Motion  ");
       lcd.setCursor(0,1);
       lcd.print(" Detected but door ");
     }
   }
   delay(2000); // wait for 1 seconds before compare again
 }

I think you forgot to ask a question there...

This is a summary of your basic loop logic:
void loop() {
  int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
  int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal
  if (buttonState == LOW) {
    if (digitalRead(pirPin) == LOW) {
        // buttonState is LOW
        // pirPin is recently read as LOW
        // ... Motion Detected ...
    }
    else if (digitalRead(pirPin) ==  HIGH) {
        // buttonState is LOW
        // pirPin is recently read as HIGH
        // ... No Motion Detected ...
    }
  }
  else if (buttonState == HIGH) {
    if (digitalRead(pirPin) == LOW) {
        // buttonState is HIGH
        // pirPin is recently read as LOW
        // ... Motion Detected & Door ...
    }
    else if (digitalRead(pirPin) ==  HIGH) {
        // buttonState is HIGH
        // pirPin is recently read as HIGH
        // ... No Motion Detected but Door ...
    }
  }
  delay(2000); // wait for 1 seconds before compare again
}

However, this is bad code:
if (digitalRead(pirPin) == LOW) {
    // ... Motion Detected ...
}
else if (digitalRead(pirPin) ==  HIGH) {
    // ... No Motion Detected ...
}

because each time the digitalRead(..) function is called, it can give a different value. So even though your intention is clear, this code won't work the way you expect. Consider what happens if the first digitalRead(pirPin) is high, so digitalRead(pirPin)==LOW is false, but then the second digitalRead(pirPin) is low, so digitalRead(pirPin)==HIGH is also false. Then neither block of code runs. Instead, use:
if (digitalRead(pirPin) == LOW) {
    // ... Motion Detected ...
}
else {
    // ... No Motion Detected ...
}

Or since you already sampled it at the start of the loop with int pirVal = digitalRead(pirPin);, simplify the logic as:
void loop() {
  int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
  int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal

  if (buttonState == LOW) {
    if (pirVal == LOW) {
        // buttonState is LOW
        // pirPin is LOW
        // ... Motion Detected ...
    }
    else {
        // buttonState is LOW
        // pirPin is HIGH
        // ... No Motion Detected ...
    }
  }
  else {
    // buttonState is HIGH
    if (pirVal == LOW) {
        // buttonState is HIGH
        // pirPin is LOW
        // ... Motion Detected & Door ...
    }
    else {
        // buttonState is HIGH
        // pirPin is HIGH
        // ... No Motion Detected but Door ...
    }
  }
  delay(2000); // wait for 1 seconds before compare again
}

By the way, if you're using the Arduino IDE, you can easily clean up the indentation to make these control structures easier to see, by using Tools | Auto Format.

hi thanks MarkU the problem is that my lcd does not work maybe it is the setup or the loop i do not know

In future, it would be useful to write a trivial program to confirm that your hardware works before moving on to driving it with new software that might itself not work. A simple "Hello, World!" program to write on the display would tell you very quickly whether you have a hardware or a software error.

The standard "hello world" example for LCD display is in the Arduino IDE under File | Examples | LiquidCrystal | HelloWorld. Note that your example code uses a different pinout, LiquidCrystal lcd(2, 3, 4, 5, 11, 12) instead of the normal configuration LiquidCrystal lcd(12, 11, 5, 4, 3, 2). Is it possible that your LCD connections are not what you intended?

hi thanks a lot MarkU it is a software error it was the configuration LiquidCrystal lcd it is working now :)

The code LiquidCrystal lcd(12, 11, 5, 4, 3, 2); defines which arduino pins are connected to the LCD hardware -- RS=12, Enable=11, D4=5, D5=4, D6=3, D7=2; with R/W grounded. Connect your LCD exactly this way and run the HelloWorld example, to verify that your LCD hardware is working. Once you get that working, then fix your code to use the same configuration lcd(12, 11, 5, 4, 3, 2) instead of what you had before, lcd(2, 3, 4, 5, 11, 12). You've got the same pins but in a different order, and I assume your LCD is connected with the normal connections.


text:
What is the memory expense of creating a String from a char array?
I'm writing a little API for processing email messages in Arduinos. Obviously, I need to keep memory use down, but I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.
My logic uses char arrays (so that memory is statically allocated). If my end user converts a char array to a String (so that they can easily see if an email subject startsWith() a particular word) will this result in doubling the character memory used? .. or will the String class simply include a pointer to the original char array (and just add some cruft)?
What would be the best-practice in this kind of situation?

What would be the best-practice in this kind of situation?

To not use String.

I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.

There's nothing wrong with providing an indexOf function in your API.  But you don't have to use String to implement that function when called.  You can just use the strstr function on char arrays (reference here).
I should also point out that most Arduinos do not have enough RAM for storing an email.
UPDATE 07-01-2016:
To answer the titular question, the fixed cost of using String is at least 1600 bytes of program space, more if you use more than a few methods.  The linker can throw out methods you don't use.
Then for each String variable you declare, the recurring cost is 8 bytes for the variable itself, plus the variable-size memory chunk for your character data.  This chunk is allocated from the heap, and is the size of your string plus 4 more bytes to manage the chunk within the heap.  That's a total of 12 extra bytes per String instance.
However, I did not originally answer that question because you explicitly asked about the memory expense.  This ignores other expenses that should not be ignored:

execution time - Allocating memory from the heap is really a search for a chunk of the requested size.  At the beginning it can be quick, but as the heap gets fragmented (small chunks build up) it takes longer to find a chunk.  And when the String is emptied or destroyed, the memory chunk gets put back into the heap and (possibly) merged with adjacent chunks.  Reducing the size of a String does not free up any memory.  The String maintains its maximum size until it is emptied or destroyed.
long-term stability - Embedded Systems are supposed run forever.  A primary characteristic of a system that can run forever is "deterministic."  For whatever inputs it receives, it has a predictable response and end state.  When you use the heap via String, the heap gets fragmented according to the data it handles.  This is not predictable, and it may get into a state where no memory chunk of the requested size is available.  Choke.
maintenance - because the heap state depends on the processed String data, finding the cause of the failure can be difficult.  It can fail at different times because the input data is different, and it can fail at different places in the program.

Because of these expenses, String is rarely used by an experienced developer.  Unfortunately, String is tempting to the beginner because it is easy to understand.  What is difficult to understand is the complicated, non-deterministic behaviour under the hood that inevitably leads to system failure, rending of garments and gnashing of teeth.

thanks slash-dev. I know about Arduino's limited RAM. I'm working on a Mega so it is not too bad. I am limiting the amount of text that can be read from the email. The idea is to be able to "send commands" to an Arduino via email. So the email body might only contain the text "turn thingy on"

Could I just state that I'd still like to know what is the memory expense of turning a char array into a String ...

@Etienne, response added above.  BTW, if you parse the email as it is received, character-by-character, you may not need to store and search the email text.  Instead, you only have to store the command "number" and appropriate parameter values.  Finite-State Machines are very powerful for these kinds of applications.

[I'm a year late but this or a related question gets asked often enough, I think it's worth another answer.]
With a Mega, there's enough memory to consider doing what you propose if we make some assumptions and modifications:

We know or can accept a maximum size of a string, above which, memory allocation will fail, detectably (the allocator returns a NULL pointer and the object handles the failure gracefully);
We use a non-fragmenting allocation method - statically allocated buffer pools of one or more fixed sizes - that are allocated and returned intact. No splitting or merging will take place. A given request will be filled with a buffer of the requested size or larger, if one is available.
Either the String object is modified to only use the new allocator or the system 'new()' is replaced by it.

The obvious disadvantages are:

The entire heap will not be eaten up by a fragmented memory pool. ("Heap" is that space between the statically allocated memory and dynamically growing and shrinking stack. When the stack and heap meet, your application fails).
You'll need to know something about your application's memory needs to plan the buffer pools.
You'll have to plan to prevent or handle allocation failure.

In exchange, you get:

The allocator won't crash your system.
The String object's programming advantages become available.
You'll write better code since you had to think about and plan for its needs rather than let a dumb and fragmenting allocator blindly consume the heap.

So... if you perform the analysis required to not use String (i.e., sizes and lifetimes), change the implementation of String (not the interface), and replace malloc with God's Algorithm, you could use String?  That's not String, that's the Hypothetical String of Theseus that someone could write in the future.  -_-

Are you being facetious? I have implemented just this sort of thing; not for String Object but for other allocate/deallocate system requirements. If the allocator is reimplemented, String need not be. This is not vaporware or blue sky-ing. It's quite real. Why not try it first, then critique it?


text:
Arduino Yún shield password reset
I'm using a Yún shield from Dragino with an Arduino Uno, but the default wifi password for the shield (which should be "dragino") isn't working.
I tried the wifi reset (holding down the reset button for 5 seconds) and a factory reset (holding down the reset button for 30 seconds) but the password still seems to be incorrect.
Is there any way I can reset the password?

Can you describe how you're determining that the password isn't working?

Try connecting via ethernet to 192.168.255.1 with root/root
The SSH access for Dragrove is:
IP: 192.168.255.1 on LAN port. If you want to connect to the Dragrove via WiFi, the IP should be 192.168.1.108.
Username: root
Password: root
http://www.seeedstudio.com/wiki/Dragrove_-_Generic_gateway_for_internet_of_things

Dragino is just the password for the first initial setup. You probably set a new password. Even if you reset the shield, it keeps your password. This happened to me to and then I put in my password and it worked.


text:
How to send an email via Arduino without an email account?
Assuming I have all the necessary hardware...
I want to develop a system where you type in an email address and the Arduino will send hourly updates on attached sensors to the provided email address.
I can only get this to work if I enter my email account's username and password and send the email from the authenticated account. There's tons of examples online of this. However, I want to share it with others and I do not want my email authentication to be accessible or be attached with sending the emails.
For example, I want the email to be from a generic service like email@web-mail.com that no one can sign into and not my personal email or a Gmail account I made for the project.
Anonymous email senders have the right method, but they require human interaction to bypass Captcha or similar.
Does anyone have an idea of how to do this? Or should I make a separate webserver that handles the requests made by the Arduino and send emails through a Gmail account I made for the project?

Even if you can get a basic SMTP connection going as per the answers already given, unless you use a registered domain with the correct SPF and/or DKIM settings etc, you may well find a lot of your emails rejected, and your "from" address blacklisted as a spammer.

You may be able to do this by running the SMTP transaction yourself. You don't actually need a valid from address (though I probably shouldn't be saying that). There are a number of resouces for how to do this, here's a quick list:

Arduino Playground Email Client page
Adafruit
How to send an email with Arduino and a WiFi shield?

If you read an article telling you how to do SMTP in a generic sense (not using a particular provider's infrastructure) and it looks like they want a "real" e-mail address, you can try with a fake one. Chances are decent that it may work.
There are some fine points that may cause you grief if you go for the most simple of implementation (for example, just because my e-mail address is foo@bar.org doesn't mean that bar.org will accept an SMTP connection, the "right" way to do it is to check DNS for an MX record for bar.org).
It would be best to do (and log) any errors that you encounter. There are plenty of things that can go wrong, so tracking where it blows up will help you – or anybody who's trying to help you debug.
If you don't want to roll your own SMTPClient and FullIP look worth checking out.

I am thinking that you will have a few issues in doing this,
If you wish to, as mentioned by dlu, run the SMTP Transaction from the device yourself, you are free to do that, however, most SMTP Relays will require some sort of authentication; this is to prevent me from using a random relay to send out millions of messages.
Another issue may be that if you do setup a local relay, your ISP will block traffic on port 25, which is common; this means your mail can never be delivered to an external server.
My thoughts on the simplest way to do this would be getting a Virtual Private Server that will run the mail service and a webserver; you could then make a simple PHP script that will accept a few parameters, and send an email.
Following the above, you would only need to make an HTTP request to your server for the mail to be sent,
http://web-mail.com/sendmail.php/?to=someone@somewhereelse.com&subject=Wooo&Message=This%20is%20a%20message.


text:
Is it possible to reduce the size of this program to 1KB
I want to use attiny13 in my project but this program is going over 1KB
void setup()
{
  Serial.begin(9600);
  delay(2000);
  Serial.println("AT+CMGF=1");
  delay;
}
void loop()
{
  for (int i=0 ;i < 1 ;i++)
  {
    delay(1500);

    Serial.print("AT+CMGS=\"");
    Serial.print("+918269394684");
    Serial.println("\"");
    while(Serial.read()!='>');
    {
      Serial.print("22.7010709,75.9372517");
      delay(500);
      Serial.write(0x1A);
      Serial.write(0x0D);
      Serial.write(0x0A);
      delay(5000);
    }
  }
}

"Serial" Well there's your problem...

There are several problems with your program as shown that make a good answer impossible.  After I list those problems, I'll then proceed to give an answer, partly good, partly bad.  The good part is that the 432-bytes-of-code program shown below should send all the indicated text strings, in the proper order and separated by appropriate delays.  The bad part is that it sends at 115200 bps instead of 9600.  Depending on point of view, it may be good or may be bad that the code doesn't look for absence of '>' on Serial input; as I note in discussion of problems, the original code's unclear.
As promised, here are several problems with your program as shown, and how to fix them:

The statement delay; is a constant expression [address of the delay() function rather than a call to delay()] so take it out.
The statement for (int i=0 ;i < 1 ;i++) is a do-nothing so take it out.
The sequence while(Serial.read()!='>'); { is confusing – it compiles but isn't something a rational programmer would write – so take it out.  (As written, with a semicolon directly between the right parenthesis and the left brace, it busy-waits until it reads '>' on Serial input.  Then the unnecessarily-blocked block of statements within the matched braces executes one time and loop() exits its current pass.  If the semicolon weren't there, the statements within the braces would execute repeatedly until a '>' appears on Serial input.)

Anyhow, with the minor fixes outlined above, and using the BasicSerial library from nerdralph's writing AVR assembler code with Arduino page, we get the following message for the program shown below.

Sketch uses 432 bytes (42%) of program storage space. Maximum is 1,024 bytes.  Global variables use 68 bytes of dynamic memory.

#include <BasicSerial.h>
char *text = "AT+CMGF=1\n\0"    "AT+CMGS=\"+918269394684\"\0"
  "22.7010709,75.9372517\0" "\033\r\n";
#define send(item) while (*item) TxByte (*item++)
void setup() {
  //Serial.begin(9600);
  delay(2000);
  //Serial.write("AT+CMGF=1\n");
  send(text);
  //delay;
}
void loop() {
  char *msg = text;
  delay(1500);          // took out `for`
  //Serial.write("AT+CMGS=\"+918269394684\"");
  send(msg);
  //while(Serial.read()!='>'); {
  //Serial.write("22.7010709,75.9372517");
  send(msg);
  delay(500);
  //Serial.write("\033\r\n");
  send(msg);
  delay(5000);
  //}
}

Program Notes:

The string text contains all the text from your original Serial prints and writes.  With the text organized as a single string, the program only needs to set its character pointer msg once per loop, saving perhaps half a dozen bytes of code.
The commented-out Serial.write statements are equivalents of your various Serial.println, Serial.print, and Serial.write statements, with adjacent strings lumped into single writes, thus for example using one write instead of three to write the Esc, CR, LF sequence just before delay(5000).  Just changing those printlns, prints and writes all to writes reduces code size  by about 150 bytes, which might be enough of a reduction to get you by, depending where you start from.  But in my tests, substituting BasicSerial in place of Serial saves over a thousand bytes so is likely to be a requirement.
You probably can modify the code in BasicSerial.S for other data rates, or perhaps can substitute one or another of the small Serial replacements listed in ernstc's Serial communication with the Tiny's webpage, to get different data rates and/or receive as well as transmit.

Edit:  As Edgar Bonet noted in a comment, an ATtiny13 has 64 bytes of RAM, so the above program (using 68 bytes of RAM) will fail.  RAM usage can be reduced by copying string characters individually from program memory, instead of copying the string into RAM (per Arduino default).  See the following revision of the program, which also corrects a problem (leaving msg pointed at a null byte) that would keep the former program from working.  Note, with these changes, we have:

Sketch uses 456 bytes (44%) of program storage space. Maximum is 1,024 bytes.     Global variables use 6 bytes of dynamic memory.

#include <BasicSerial.h>
#include <avr/pgmspace.h>
const char text[] PROGMEM = "AT+CMGF=1\n\0"
  "AT+CMGS=\"+918269394684\"\0"
  "22.7010709,75.9372517\0" "\033\r\n";
char *front = (char*)text;
#define send(item) while (pgm_read_byte(item)) TxByte (pgm_read_byte(item++))

void setup() {
  delay(2000);
  send(front);  ++front;
}
void loop() {
  char *msg = front;
  delay(1500);
  send(msg);   ++msg;
  send(msg);   ++msg;
  delay(500);
  send(msg);
  delay(5000);
}

“Global variables use 68 bytes of dynamic memory.” Since the ATtiny13 has only 64 bytes of RAM, you may want to put text in PROGMEM.

Nicely optimized! But I think like better static void send(const char * &item) { while (char c = pgm_read_byte(item++)) TxByte(c); }, as it avoids all the ++front and ++msg.


text:
ACS712 sensor reading for AC current
I'm trying to track down a clearly/simply articulated piece of code to take a reading from the ACS712 current sensor (link to download PDF data sheet).
I understand that these sensors are noisy, and that reading AC current is quite different to DC current.
After looking at a range of examples in a variety of forums etc., I've based the following on http://henrysbench.capnfatz.com/henrys-bench/acs712-arduino-ac-current-tutorial/
void ac_read() {
  int rVal = 0;
  int maxVal = 0;
  int minVal = 1023;
  int sampleDuration = 100; // 100ms

  uint32_t startTime = millis();
  // take samples for 100ms
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(A0);
    if (rVal > maxVal)
      maxVal = rVal;

    if (rVal < minVal)
      minVal = rVal;
  }

  // Subtract min from max to determine the peak to peak range
  // 1023 = the max value we'll get on the input (1024, zero indexed)
  // 5.0 = 5v total on adc input
  double volt = ((maxVal - minVal) * (5.0/1023.0));

  // div by 2 is to calculate RMS from peak to peak
  // 0.35355 is factor to calculate RMS from peak to peak
  // see http://www.learningaboutelectronics.com/Articles/Voltage-rms-calculator.php
  double voltRMS = volt * 0.35355;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // the 20A module 100 mv/A (so in this case ampsRMS = voltRMS
  double ampsRMS = (voltRMS * 1000)/100;
  Serial.println(ampsRMS);
}

I unfortunately don't have sufficient test equipment at present to validate this, but I'm getting a value of around 8.9 for a 2300W device, which afaict is roughly accurate (based on this calculator http://www.rapidtables.com/calc/electric/Watt_to_Amp_Calculator.htm).
Is anyone able to confirm the above makes sense/is logical/sane?  Is there anything obviously incorrect?

I think I've just worked it out—typo in my code should have been x 1000 for millivolts (which I copy and pasted into the comments).  Will update the example in a sec.

Is anyone working with ACS 712 current measurement module with Arduino? I saw some emote on http://www.instructables.com/id/How-to-Measure-AC-Current-using-Hall-Effect-Sensor/?ALLSTEPS which uses the differential amplifier after the module. I want to know , we should use the differential ckt or no/? Currently I didnt used the ckt and use the module alone and I have the 2.68 v permanently even after the load connection. I checked the module with a magnet and responds properly.

Hi Ata—yes, I've successfully got the ACS712 working with AC on Arduino—see the answer marked as "correct" below, as this was the basic approach I used.  You don't need a differential amplifier, but if you don't use that you need to do extra work in code.  Assuming you're working with AC not DC (DC is much more straightforward).

Measuring the peak-to-peak current and scaling the result will get you an answer which will at least go up and down with the magnitude of your average AC current, so yes it is NOT incorrect.  As you suggested it will be sensitive to noise from the sensor - in fact as you are taking the highest and lowest single readings the noise will always cause the measurement to be higher than actual.
However, I think you could do better.  Given that the code is already having to take many samples (basically as fast as it can) for 100mS (which will sample 5 cycles of the waveform if it is 50Hz and 6 if it is 60Hz, depending on where you are in the world), then you could actually do the maths to measure the RMS value and by basing this on all of the signal the effect of the noise will be reduced.
You need to know the ADC reading when there is no current rZero (which should be around 511 but could be off a bit due to offset errors) - you could measure this with nothing connected to calibrate the sensor, or take a long term average even with the AC signal present.
As the henrysbench tutorial points out it is important that the Arduino samples the signal at a high enough frequency (say 1000Hz - hence 100 samples for your 100mS sample duration)- the count of the number of times that the while loop executes sampleCount will confirm if this still the case even with the extra computation time of this code.
Also if you increase the sample time please be careful that the unsigned long rSquaredSum can't overflow, but I would avoid use of doubles within the while loop as they will definitely slow it down a LOT.
void ac_read() {
  int rVal = 0;
  int sampleDuration = 100;       // 100ms
  int sampleCount = 0;
  unsigned long rSquaredSum = 0;
  int rZero = 511;                // For illustrative purposes only - should be measured to calibrate sensor.

  uint32_t startTime = millis();  // take samples for 100ms
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(A0) - rZero;
    rSquaredSum += rVal * rVal;
    sampleCount++;
  }

  double voltRMS = 5.0 * sqrt(rSquaredSum / sampleCount) / 1024.0;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // the 20A module 100 mv/A (so in this case ampsRMS = 10 * voltRMS
  double ampsRMS = voltRMS * 10.0;
  Serial.println(ampsRMS);
}

Thanks @c-barnes.  I'd seen something akin to this approach in my initial research (yours is clearer than other examples I'd seen, so thanks!), but given the need for the rZero value I hadn't pursued it.  As I expect this code to run on a number of devices/with a variety of sensors, I'm interested in how I could "take a long term average even with the AC signal present".  Are you able to point to an example or explain how this would be done with the AC present?  The other option would be to implement a "calibrate" mode when no devices are attached to get this value.

I'm pretty sure you've got to use rZero – the sensor (if is the one I'm thinking of, haven't looked specifically for it tonight) reads +/- current, since the ADC can't give you a negative value the sensor uses Vcc/2 as the quiescent (0 A) voltage. Subtracting rZero gives you the negative part of the range.

You mention that you don't have much test equipment, but you don't need any to measure rZero – just let the device run for a bit with no load (disconnect or turn it off) and average a few readings – they should be close to 511/512 but may be off by a bit. The average is rZero.

The beauty of AC is that it averages out to nothing, which is why you needed to measure RMS in the first place.  So even when AC is present if you just accumulate the sampled values and, as above, divide by the number of samples at the end of the period you will get an estimate of rZero.  The only issue is that the AC only averages out to zero if you measure over a whole number of cycles.  If you know the AC frequency you can set sampleDuration accordingly, or sample over a much longer time (few seconds) so that any non whole cycle is a small proportion of the total.


text:
Industrializing Arduino - 24V io? (Electronics)
I would like to make an arduino board that is capable of handling 24V i/o.
Powering the Arduino would be done through either a linear or switching regulator of some sort. Low amperages, so efficiency isn't the main problem.
For input:
24v to 5v input scaling could be created with a voltage divider.
As far as I know, there will never run a high current into the arduino? So the power loss is minimal?
For output:
5v to 24v can be easily achieved using a MOSFET? Since this will ramp up the possible load (higher amperages) given that I'm using a 24v supply/separate line.
So I could choose to make half the I/O only input and half only output.

Could I combine the MOSFET and voltage divider, and in what way?
Are my "assumptions" about the I/O correct, or are there beter ways of handling it?
What other things should I think of? Over voltage protection? Polarity inversion? Protection against too high currents?

Sounds like you want isolated level switching, not just voltage dividers and MOSFETs. At least, that's what I hear when someone says "industrialize"...

Like this.

Sound more like a job for opto-isolators.

Or this: http://www.rugged-circuits.com/ruggeduino/

Very good points, indeed, putting opto-isolators in might be a better move. I kinda want to abstain from using a relais as I heard they can burn so that they won't stop outputting signal.
So my best shot would be 2-way opto-isolators that can work with 5V at one side and 20V (larger amperes) at the other side?
This would make it unable to use analog inputs for other than 0-5V though, but I'm not sure if it's neccesary to have those. The voltage dividor with an overvoltage protector might do for analog inputs?
I guess I'm going to check more of those other designs, before I try to make my own

You mentioned 2 items: the supply voltage to the Arduino and scaling up to 24V output.
If the supply voltage you have available is 24V, then I would suggest you look for a DC-DC converter that scales down to 12V. Or, if you are looking to design your own PCB then perhaps use a 78xx voltage regulator. The 78xx are 3 pin devices and only require 2 caps to operate - I suppose a heat sink will not be needed.
To scale up the outputs to 24V I would suggest one of the following options:
a) Relay board /
These will take the 5V from your Arduino and close a mechanical switch. If the relays are good quality they will go on for ages. And you can switch loads from 0 to 240V and more, DC or AC.
Plus of the relays are sturdiness and that they are quite forgiving for short current overloads. Minus are that relays are " slow" when compared to semiconductors and they can arce when the contacts open - especially when driving inductive loads and that. Arcing will wear down your contacts and in extreme cases generate EMI that might interfere with your electronics. Arcing can be remediated in AC with a capacitor accross the contacts or in DC with a flyback diode.
If you will make your own PCB don't forget the flyback diode on pins connecting to the relay coils or you will possibly fry the Arduino due to a voltage spike!
Many of these boards are available on the web, so it's a quick solution.
b) Optocouplers /
Also a good option. Functionally they act as a relay. They are a bit less forgiving to current overloads, so chose them wisely.
They are silent and fast acting. Available for AC or DC and up to 600V.
Minus side is that the tend to be a bit more expensive than relay boards. I'm talking about industrial grade devices and not some el-cheapo web site :-)
c) MOSFETS or Bipolar transistors /
If you are designing your PCB then this could be an option.
Here you can use a MOSFET or a PNP transistor of the adequate ratings and you would be done. Though maybe considering yur time investment the options above could be less expensive in the end.
I this case you get complete control of PCB layout which might be a consideration.
If you go this way, don't forget to add a flyback diode to the output of these devices to protect from spikes when switching inductive loads (= motors, solenoids).
A big advantage of Relays and Optocouplers is the galvanic isolation they provide, both from the load to the board as between the loads themselves.
If you could supply more detailed specs of the loads, environments etc I can help you narrow down your choices.

I was indeed looking for a "broad" solution, as in using the arduino like a PLC. So at this point I don't have any more details on the environment. Also, I posted this to check if my ideas were right. I found that opto-couplers might fit best, or even in a combination with some relaises. I was unaware of the existence of optocouplers, so this really helped.

24 VDC industrial circuits are typically based around 4-20mA measurement (AI) transmitters and outputs (AO) to valves and other actuators. There are also 24 VDC DI & DO's. I believe that you should investigate Analog Devices and Texas Instruments chips for 4-20 mA interfacing.  They have a number of chips for reading in and outputting 4-20 mA.  You can get started if you Google "analog devices 4-20ma application note" or "texas instruments 4-20ma application note." If you Google "4-20mA application note," you will find that there are any number of people that make these chips and lots of people that provide application notes for 4-20mA loops.
Any information provided here is on a Caveat Emptor basis.

It just came to my mind that an PLC wouldn't directly power something. I always had that thought because it was 24V (but amperes would be critical, and nobody is going to run 2A through a PLC?)
So I could get some 2way opto-isolators and just hook them, like a regular PLC, as they aren't made for powering directly either.

This is a pretty old post but I'm sure people still search this topic from time to time. If what you are after is making an arduino into the plc replacement of sorts, look at these links. I've done these tasks and they worked pretty easyily for me. When you compare the cost of a plc to these alternatives, you won't find a new plc for the same price:
https://www.universal-solder.ca/product/canaduino-plc-mega328-programmable-logic-controller-electronics-diy-kit-for-arduino-nano-included/
and
https://www.visuino.com/ - A visual ide


text:
Is it possible to directly set the registers that control the ADC clock on the Arduino?
Is it possible to directly set the registers that control the ADC in an Arduino Yun (micro-controller side is essentially a Arduino Leonardo) from a sketch or is there a specific file somewhere you must edit?
I am working on a project that collects a signal digitizes it and sends it through a digital filter. I looked up the Datasheet for the micro-controller on the Yun and wrote the code setting the registers associated with the ADC portion of the micro controller. The code setting the registers was something like REGNAME = 0x01;. Yet when tested several of the associated registers were unaffected. Pointers on the process to set the ADC manually without using the analogRead() function would be appreciated.
Edit:
My original code looked something like this:
void setup(){
    // register to turn on ADC
    REG1 = REG1 | 0x01;

    //register to set sample rate and set ADC to Free Running Mode
    REG2 = REG2 & 0x30;

    // register to set other settings
    REG3 = REG3 | 0xF1;
}

void loop(){
    // code to take samples from ADC
    // and send them through a digital filter here.
}

Which part of the datasheet are you having trouble with?

The problem wasnt the datasheet. when I set the registers in the code they were not set on the microcontroller when I tested it.

the sketch recognized the register names and out of the 3 or 4 registers I set only one actually was altered. I debugged it by printing the values of the registers after being set to the console. The output of the ADC was not the same as the input signal either.

The Arduino libraries do things to the hardware. The key is to avoid using them.

I realized that after the fact. We needed a micro-controller and Ethernet in our project but because of time constraints, the research time requirement and budget constraints we could not use a pic micro-controller which would have been the ideal choice. do you know where the libraries do things to the ADC hardware? info on the process to replace  the actual library file would be helpful too.

Do you call analogRead after setting the registers? analogRead does change  the ADCSRB register. So if you are setting ADC High Speed Mode (ADHSM), that will be overwritten. The clock prescaler is only set in the init function, so you should be able to overwrite this in the setup function

What is it that you're trying to achieve that the Arduino library does not allow you to do?

I had intended to avoid the analogRead() method entirely. Because I was using Arduino as a prototyping platform to design the code only and later on I will refactor the code to work with hardware that will be mass producible. Therefore I had intended to directly control the registers so that when I port over the code to the final choice of micro-controller there will not be a relatively small amount of changes to make.

I had originally set the registers in the setup function and not in the running loop function.

There are several issues here. The first is understanding the difference between || and |, && and & in C/C++. Your should then take a look at the code for analogRead() to understand how the ADC is initialed. https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_analog.c#L38. This type of modification requires a lot of detailed insight into the underlaying implementation. You may need to implement your own version of analogRead().

I think I used bitwise operators in my code and made a mistake typing extra '&'s and '|'s in my example. I just edited the example to reflect that. Ill have to double check that. I am going to check the link you listed. It looks like I will have to overload the analog read function so that it works like I want it to. after that, I'll have to  figure out how to replace that part of the library and ill be good to go. @MikaelPatel if you can post an answer with the info you just commented and a link to a tutorial on how to compile a sketch with an edited library I'll accept your answer.

Ill follow up after with a comment listing everything I found out.  Unless it would be better to post the follow up as an answer.

Since your project is about acquiring signals I guess that the sample frequency is important for you. In fact you need to know exactly how much time passes from one sample to another. This cannot be achieved by simple reading the ADC in your loop(). The easiest implementation is to use an interrupt that occurs every n seconds (e.g. every overflow of timerX).
I'm going to write a pseudo-code for this:
void SetTimer()
{  TISREG |= 1<<Prescaler_bit   //set the prescaler
   TICNT = 0   //sdt the tarting value
   TIINT |= 1<<OVF_Interrupt_enable
   sei() //enable global interrupt
}

ISR(TIM1_OVF_vect)   //happens every [prescaler*2^bit_timer/F_CPU] seconds
{
   while( !(ADCSREG &= (1<<bit_is_ready)) ) ; //usually there is a bit that is 1 while the ADC has read the data, and 0 while it is doing the conversions

//imagine the ADC stores the 3 MSBits in the ADCHI
//and the LSBits in the  ADCLO

value_high = (ADCHI & 0b00000111);
value_low = ADCLO;

value = (value_high << 7) | value_low;

}

At high sampling rates, the best option is to set the ADC in the so called "free running mode". If you read the question carefully, you will notice that's exactly what the OP is doing.

I can see no problem with your pseudo-code. You should probably post a
complete testable code in order to get better feedback.
That being said, here are a few suggestions:

You should completely set the ADC registers to the values that suit
your application, instead of just changing a few bits here and there.
This is because you should not care about how the Arduino core
library initializes those registers, especially if this is a
prototype for a final product that will not use Arduino core. For
example, instead of

REG1 = REG1 | 0x01;

you can write something like this:
REG1 = _BV(FOO)   // use foo mode...
     | _BV(BAR);  // ...in the bar setting

where _BV(x) is a macro from avr-libc that expands to (1<<(x)),
   and the bit names are those of the datasheet, for better readability.

You may want to run the digital filter in the ADC interrupt service
routine. If you can split your processing into a fast filter
(processing every sample) and a slow filter (running on decimated
samples), then do only the fast one in the ISR and leave the slow one
to the main loop. I say this from experience: when I tried to do
all the processing in loop() I always lost samples, which did not
happen when I moved the filter to the ISR.
But then, make sure your filter is optimized to be fast. Avoid
floating point operations in the ISR if at all possible.

I have written a program that looks very similar to what you are trying
to do: it samples an analog input at 9.6 kS/s and runs an
homodyne detection
filter in order to extract the signal power in a very narrow band around
1 kHz. The ADC is set to free running mode. In the ADC ISR, I
retrieve the sample, run it through the filter, and store the result
into volatile variables. In loop(), I read these back from time to
time. Here is how I set the ADC:
static void configure_adc()
{
    ADMUX  = _BV(REFS0)  // ref = AVCC
           | _BV(ADLAR)  // left adjust result
           | analog_in;  // input channel
    ADCSRB = 0;          // free running mode
    ADCSRA = _BV(ADEN)   // enable
           | _BV(ADSC)   // start conversion
           | _BV(ADATE)  // auto trigger enable
           | _BV(ADIF)   // clear interrupt flag
           | _BV(ADIE)   // interrupt enable
           | 7;          // prescaler = 128
}

The complete program is available here:
homodyne.ino.
It was initially intended for an Arduino Uno, but it runs unmodified on
a Leonardo clone.