text:
EEPROM endurance and page size
I would like to estimate the effective (minimum) endurance of the EEPROM of the Arduino in terms of single-byte writes.
The datasheet of the ATmega used on many Arduino boards says (page 20):

The ATmega48A/PA/88A/PA/168A/PA/328/P contains 256/512/512/1Kbytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles.

Consider the ATmega328P with 1 kB of EEPROM. As I can write single bytes, if I loop through the EEPROM, writing every byte position the same number of times, that would make 1024 * 100,000 writes (assuming the nominal endurance).
But as far as I know not single bytes are erased before a write, but pages / cells. On page 285 / table 28.12 of the datasheet, the page size is specified to be 4 bytes. Does that mean the specified minimum endurance amounts to 1024 * 100,000 / 4 single-byte writes?

That story goes around, but it appears not to be true.

I'm doing my own test on this right now. So far I am up to a million writes on a single byte, with it reading back correctly. Once I get it to fail (which might be in 7 hours judging by the AVR Freaks posting, I'll see if an adjacent byte fails, or not. Both my own test, and the AVR Freaks one, seem to confirm that you can probably get somewhat more than 100,000 writes from a single address.

Testing a single byte write
I ran some test code overnight to try to get to the bottom of this. Somewhat surprisingly perhaps, I got up to over 11 million writes before a read-back failed:
Current count = 11514199
Writes per minute: 17550
....................
Current count = 11538199
Writes per minute: 17550
....................
Current count = 11562199
Writes per minute: 17549
...................
Failed readback!
Expected: FF
Got: 7F
Current count = 11585314
Halted.

So, 11.5 M writes. Still, as pointed out on the AVR Freaks thread, the guarantee of 100,000 writes to EEPROM gives you a data retention time of 20 years. Possibly if you exceed that limit, the data retention time will go down. It isn't particularly practical for me to test whether or not the EEPROM will still be valid after 20 years. ;)
Interestingly, the next day (as I write this) the EEPROM seems to have recovered and is now still writing and reading back OK. So it would appear that after 11 M writes you may sometimes get a bad read-back.
On the AVR Freaks thread they seemed to get somewhere between 5 M and 8 M writes before failure.

A number of hours later (2.4 hours), the same byte failed again, after a further 2,559,219 writes!
Current count = 14033314
Writes per minute: 17549
....................
Current count = 14057314
Writes per minute: 17549
....................
Current count = 14081314
Writes per minute: 17549
....................
Current count = 14105314
Writes per minute: 17549
....................
Current count = 14129314
Writes per minute: 17549
............
Failed readback!
Expected: FF
Got: 7F
Current count = 14144533
Halted.

Somewhat more quickly the third failure after a further 149,703 writes:
Current count = 14312533
Writes per minute: 17550
....
Failed readback!
Expected: FF
Got: 7F
Current count = 14318236
Halted.

And another failure (in 2.3 minutes) after a further 41757 writes:
Starting.
Current count = 14318236
Waiting for pin 2 to go LOW.
Started.
....................
Current count = 14342236
Writes per minute: 17551
..............
Failed readback!
Expected: FF
Got: 7F
Current count = 14359993
Halted.

Testing the adjacent byte
Now that I got a failure fairly quickly on the somewhat overworked byte, I adjusted the code to write to the next one up (1021) which would be in the same 4-byte "page".
Four hours later, the adjacent byte has been written to 4.36 million times without any errors, so this would appear to support the idea that each byte of EEPROM can be written individually without affecting its neighbours.
Next morning
The adjacent byte (address 1021) finally failed after 12,161,565 writes. So the proposition that each byte can be individually addressed, and has an individual lifetime, seems to be supported.
Current count = 12120000
Writes per minute: 17562
....................
Current count = 12144000
Writes per minute: 17562
..............
Failed readback!
Expected: FF
Got: 7F
Current count = 12161565
Halted.

Code
Main sketch
// EEPROM tester

// Author: Nick Gammon
// Date: 22 August 2015

// Connect a jumper from GND to pin D2 when ready to run.
// Remove the jumper for a clean wrap-up (saving the current count into EEPROM)

// Single flash, repeated every half second: ready to go
// Two flashes, stopped on request
// Three flashes, error
// Occasional flash: working

#include <EEPROMAnything.h>
#include <EEPROM.h>

const unsigned int WRITE_COUNT_ADDRESS = 1010;
const unsigned int TEST_ADDRESS = 1020;
const unsigned int ITERATIONS = 200;
const unsigned long MAX_DOTS = 20;
const byte TESTS [] = { 0x55, 0x00, 0xFF, 0x66, 0xAA, 0x11 };
const byte ACTIVATE_PIN = 2;
const byte LED = 13;

unsigned long dots = 0;
unsigned long writeCount;
unsigned long startTime;
unsigned long initialCount;

void showCount ()
  {
  Serial.print ("Current count = ");
  Serial.println (writeCount);
  } // end of showCount

// flash the LED the required number of times
void flashLED (const int times,
               const unsigned long interval = 100,
               const unsigned long delayTime = 500)
  {
  for (int i = 0; i < times; i++)
    {
    digitalWrite (LED, HIGH);
    delay (interval);
    digitalWrite (LED, LOW);
    delay (interval);
    }  // end of for each iteration
  delay (delayTime);  // delay between iterations
  }  // end of flashLED

// check our memory agrees with what we expect
void checkMemory (const byte target)
  {
  byte found = EEPROM.read (TEST_ADDRESS);
  if (found != target)
    {
    Serial.println ();
    Serial.println ("Failed readback!");
    Serial.print ("Expected: ");
    Serial.println ((int) target, HEX);
    Serial.print ("Got: ");
    Serial.println ((int) found, HEX);
    showCount ();
    EEPROM_writeAnything (WRITE_COUNT_ADDRESS, writeCount);
    Serial.print ("Halted.");
    Serial.flush ();
    while (true)
      flashLED (3);  // three flashes
    }
  }   // end of checkMemory

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  // get write count from previous run
  EEPROM_readAnything (WRITE_COUNT_ADDRESS, writeCount);
  initialCount = writeCount;

  // if all 1 bits, variable was never initialized
  if (writeCount == 0xFFFFFFFF)
    writeCount = 0;

  // tell them we are starting
  Serial.println ("Starting.");
  pinMode (2, INPUT_PULLUP);
  pinMode (LED, OUTPUT);
  showCount ();

  // wait for them to unplug pin 2
  Serial.println ("Waiting for pin 2 to go LOW.");
  while (digitalRead (ACTIVATE_PIN) == HIGH)
    flashLED (1);  // one flash

  Serial.println ("Started.");
  startTime = millis ();
  }  // end of setup

void loop ()
  {

  // write to EEPROM, checking each write
  for (unsigned int i = 0; i < ITERATIONS; i++)
    {
    for (unsigned int j = 0; j < sizeof (TESTS); j++)
      {
      EEPROM.write (TEST_ADDRESS, TESTS [j]);
      writeCount++;
      checkMemory (TESTS [j]);
      }  // end of doing each test pattern
    }  // end of loop of x ITERATIONS

  // save the current write count so we can pick up the count next time
  EEPROM_writeAnything (WRITE_COUNT_ADDRESS, writeCount);
  Serial.print (".");
  dots++;

  // confirming we are working
  flashLED (1, 10, 0);  // flash once, for 10 ms, no extra delay

  // newline, show counter
  if (dots >= MAX_DOTS)
    {
    Serial.println ();
    dots = 0;
    showCount ();
    unsigned long writes = writeCount - initialCount;
    unsigned long timeTaken = millis () - startTime;
    float writesPerMinute = float (writes) / float (timeTaken) * 60.0 * 1000.0;
    Serial.print ("Writes per minute: ");
    Serial.println ((int) writesPerMinute);
    }  // end of needing a newline and counter output

  // check if user wants us to stop by disconnecting the jumper from Gnd to D2
  if (digitalRead (ACTIVATE_PIN) == HIGH)
    {
    Serial.println ();
    Serial.println ("Stop request detected.");
    showCount ();
    Serial.print ("Halted.");
    Serial.flush ();
    while (true)
      flashLED (2);  // two flashes
    }
  }  // end of loop

EEPROMAnything.h
#include <Arduino.h>  // for type definitions
#include <EEPROM.h>

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

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

The code is designed to wait until you connect pin 2 (digital pin 2) to ground before starting. This is to stop it executing immediately after being uploaded, before you start the serial monitor. So, upload the code, open the serial monitor, and then connect Gnd to pin D2, and watch the results.

Error correction
If the concern is that the EEPROM reads may deteriorate, once could use Reed Solomon error correction to recover. That is the method used for correcting bad reads on compact disks, and also QR codes. It can recover from a number of errors (you choose the level of error correction you want - the more error correction, the more memory it takes).
My tests so far have shown that failure involves single bits (as did the AVR Freaks tests) so this may well be a way of extending EEPROM life and reliability.
Testing of some Reed Solomon code that I found, would appear to indicate that adding the encoding and decoding would take around 4800 bytes of program memory, plus around 600 bytes of RAM (512 bytes needed for the internal tables, plus some extra work space). In addition you need 256 bytes of RAM for the code block. Those figures could be reduced by using less bits per "symbol". For example, if you stored 4-bit symbols (such as BCD numbers) then the memory requirements would reduce somewhat.

See edited reply. The second byte failed after 12.16 million writes, so it appears that even bytes in the same 4-byte page have individual lifetimes.

In the arduino forum
http://forum.arduino.cc/index.php?topic=293472.0
someone states that is 1 byte size (each "page") - each write writes and spends a cycle for a single byte.
There it also says that SPI access to eeprom uses a 4 bytes page size.
I did not went further reading since my doubt was same as here, writing a byte to arduino eeprom.


text:
Mega <> esp8266 comms sending baffling data
I have Wemos Mega-ESP8266 board. I have uploaded a simple WebSocket server on the ESP...

#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>

const char* ssid     = "SKYNET";
const char* password = "yourdogsfavouriteauntysmaidenname";

WebSocketsServer webSocket = WebSocketsServer(81);

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {

    //Serial.printf("[%u] get Message: %s\r\n", num, payload);

    switch(type) {
        case WStype_DISCONNECTED:
            break;

        case WStype_CONNECTED:
            {
              IPAddress ip = webSocket.remoteIP(num);
              Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
            }
            break;

        case WStype_TEXT:
            {
              String _payload = String((char *) &payload[0]);
              Serial.print(_payload);
            }
            break;

        case WStype_BIN:
            {
              hexdump(payload, lenght);
            }
            // echo data back to browser
            webSocket.sendBIN(num, payload, lenght);
            break;

    }
}

void setup() {

  // Set up serial comms
  Serial.begin(115200);

  // Set up WiFi
  WiFi.begin(ssid, password);
  while(WiFi.status() != WL_CONNECTED) {
     Serial.print(".");
     delay(200);
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  delay(500);

  // Set up web socket
  Serial.println("Start Websocket Server");
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}

void loop() {
  webSocket.loop();
}

I upload via the Arduino IDE & everything looks fine except the ESP doesnt send any information back through the serial monitor (yes I have the DIP switches correct for serial <> ESP comms).
I tried to see if was sending anything through the Mega via Serial3, the mega code (DIP switches set accordingly & ESP serial switch set to RX3). Mega code...
// Input buffer from ESP8266
String temp;

void setup() {
  // Set up serial comms
  Serial.begin(115200);   // Debug to Serial Monitor
  Serial3.begin(115200);  // From ESP8266
}

void loop() {
  while (Serial3.available()) {
      Serial.println(".......");
      Serial.println("In from ESP8266");
      temp = Serial3.readString();
      Serial.println(temp);
      Serial.println(".......");
  }
}

So now I get 2 one time messages to the serial monitor..
.......
In from ESP8266
[WS-Server] Server Started.

.......
.......
In from ESP8266
pm open,type:2 0

.......

I have no idea where these messages are being generated or why the ESP isnt sending the serial messages on set up eg the IP address for the ESP etc.
Any idea what's going on here?
Edit 1: Addition info asked for in comments (or at leat I think this is what was asked for)

Edit 2:
DIP switch settings for flashing the ESP - OFF, OFF, OFF, OFF, ON, ON, ON
DIP switch settings ESP > serial monitor - OFF, OFF, OFF, OFF, ON, ON, OFF (RX switch to TX0)
DIP switch settings for ESP > Mega > serial monitor - ON, ON, ON, ON, OFF, OFF, OFF (RX switch to TX3)
Edit 3 I have to press the red reset button after flashing the ESP8266 & it works BUT as soon as I unplug & restart nothing again! The client connects, sends the same data but it doesnt get echoed back via the serial comms. The only way to get to work again is to reflash the ESP8266 and hit the reset button.
Edit 4 Swapped out the board & now nothing works again. Uploads look fine but no serial comms at all from the ESP8266.

@Juraj have added (I think) the information you requested to the OP

sorry. I read then the question again and it is not about logging. (but set "Debug port" to None and don't use "Wemos D1 R1". use "Generic esp8266")

@Juraj just reflashed using "Generic esp8266" & no debug port & got a string of gibberish but nothing else. Flash mode set to DOUT (compatible)

ahh right OFF, OFF, OFF, OFF, ON, ON, ON to flash the ESP

@Juraj DIP switch info added to OP

The esptool auto-reset feature by default sets io 0 LOW over the RST line and then makes a reset over the DTR line to put the esp8266 into flashing mode. After the upload the esptool resets the board over the DTR line.
On this board Mega+WiFi, only the DTR line is wired like for AVR MCU. For flashing the io 0 pin is put LOW with the pin 7 of the DIP switch manually. So the reset after upload sets the esp8266 back to flashing mode.
The esp8266 arduino package changed from version 2.5.0 the upload tool to the python version of the esptool which makes this reset after upload. This reset can be turned off by changing the command line of the esptool in platform.txt (--after no_reset in tools.esptool.upload.pattern before write_flash)

if you don't like the DIP switches, you can upload to esp8266 over the ATMega https://forum.arduino.cc/index.php?topic=519181.0

source: Stack Exchange

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

sort: votes


text:
Two pots controlling 2 servos -- odd behavior
I'm trying to control 2 servos with 2 pots. I thought I could just amend the tutorial code by adding in the extra pot on a1 and extra servo on d8 (am using a Nano).
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
Servo myservo_2;

int potpin = 0;  // analog pin used to connect the potentiometer
int potpin_2 = 1;
int val;    // variable to read the value from the analog pin
int val_2;

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo_2.attach(8);
}

void loop() {
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  val_2 = analogRead(potpin_2);
  val = map(val, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
  val_2 = map(val_2, 0, 1023, 0, 180);
  myservo.write(val);                  // sets the servo position according to the scaled value
  myservo_2.write(val_2);
  delay(15);                           // waits for the servo to get there
}

...but the servos only respond to one of the pots (on a0) & both move to the same position regardless of what value is on a1.
Am I missing something really obvious? Why is the value on a1 ignored & why is the value mapped from a0 sent to both d8 & d9?
I have swapped out the pot on a1 just in case it was faulty but I get the same behavior.
EDIT: Added schematic

EDIT: I swapped out the Nano for another Nano but that failed to upload the sketch. So I put the original back in & now evrything is working fine!
Darn'd if I can get my head around it, possibly a bad connection with the bread board?
Anyway all working now thanks for your suggestions.

How are your potentiometers connected?

between the + & - rails with the sliders connected to a0 & a1. Works fine for the unaltered single servo code from the tutorial

added schematic for clarity

Use A0 and A1 in your code for the analog pins instead of 0 and 1.

Using A0 & A1 has made no difference to the behavior

That the reading from a0 and send it to both servos but reverse one of them (180-value).

I have no idea whats wrong with your system, but this might help you diagnose it.
#include <Servo.h>

static const size_t MaxServos = 2;              // The number of pots and servos attached
const int servoPins[MaxServos] = {9, 8};        // The pins that the servos are controlled through
const int potpins[MaxServos] = {A0, A1};        // analog pin used to connect the potentiometer
Servo myservo[MaxServos];                       // create servo object to control a servo

void setup ()
{
    for (size_t index = 0; index < MaxServos; ++index)
    {
        myservo[index].attach (servoPins[index]);
    }
}

void loop ()
{
    for (size_t index = 0; index < MaxServos; ++index)
    {
        readAndSet (potpins[index], myservo[index]);
    }
    delay (15);                           // waits for the servo to get there - might want to multiply a value by the number of degrees turned to give a better value.
}

// \brief   Read the specified analog pin and set the server proportionally
// \param   The analog pin that the pot is connected to.
// \param   The servo that will be moved
void readAndSet (const int& pin, Servo& servo)
{
    const int value = analogRead (pin);            // reads the value of the potentiometer (value between 0 and 1023)
    const int mappedValue = map (value, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
    servo.write (mappedValue);                  // sets the servo position according to the scaled value
}

I have refactored your code to eliminate the duplication.  This means you will get more test coverage and you should find the bug quicker.  You could add a Serial print statement to the readAndSet function to ensure that you are passing and calculating the right values, but I suspect you are.
There appears to be nothing wrong with the code, so is it possible that there is some hardware limitation?  Is there a short between the lines that causes the pot on A1 to be bypassed?

thanks, what is size_t? I edited my question, once I swapped out then replaced the orignal Nano the system works as expected.

its an unsigned int.  You only need to count from 0 to +0xffff so don't bother using an int.

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


text:
Mapping values from analog input giving unexpected values?
Mega 2560
I am reading in values from 3 pots then mapping them to values between 0 - 255
#define REDPIN   7
#define GREENPIN 8
#define BLUEPIN  9

int red_pot   = A0;  // analog pin used to connect the potentiometer
int green_pot = A1;
int blue_pot  = A3;

void setup() {

  pinMode(REDPIN,   OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN,  OUTPUT);

  Serial.begin(38400); //Debug port
  Serial.setTimeout(50);
}

void loop() {

  int red, green, blue;

  red   = analogRead(red_pot);
  green = analogRead(green_pot);
  blue  = analogRead(blue_pot);

  Serial.print(" r = ");
  Serial.print(red);

  Serial.print(" b = ");
  Serial.print(blue);

  Serial.print(" g = ");
  Serial.print(green);
  Serial.print("\n\n\n");

  // map values
  red   = map(red,   20, 650, 0, 255);
  green = map(green, 20, 570, 0, 255);
  blue  = map(blue,  20, 570, 0, 255);

  Serial.print("red map : ");
  Serial.print(red);

  Serial.print(" green map : ");
  Serial.print(green);

  Serial.print(" blue map : ");
  Serial.print(blue);
  Serial.print('\n\n\n');

  analogWrite(REDPIN,   red);
  analogWrite(GREENPIN, green);
  analogWrite(BLUEPIN,  blue);
}

red & green behave as expected but blue is not, from the serial monitor...
When blue is at its lowest value,

When blue is at its highest value,

I have changed blue's analog pin assignment but the same issue.
Any clues what's happening?
EDIT #1
I thought it might be some int sign error so I changed the map operation to,
blue  = map(abs(blue), 20, 670, 0, 255);

It made no difference.

In your print statement first r, b and g are printed but in your output it shows first the mapping. Are you sure the boxed values belong to each other?

yes if I leave the pots at a setting the values are stablish +/-5 on the input but pretty much the same values

Note that the Arduino function "map" is really this:
long map(long x, long in_min, long in_max, long out_min, long out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

...so, if you pass a "minimum from" value which is less than the actual value you are mapping from you will get a negative number given your "minimum out" is zero.
In several of your examples you have set the minimum to 20 but pass a value of 19.  If your program is intolerant of negative numbers (for instance, how would a negative number effect the PWM hardware), consider testing for lower than minimum and higher than maximum values before using the map function.

I realize this does not directly address your example code combined with your output.  However, it is obvious the output is not directly from the code as it is printed in reversed order.  Try running your code again and verifying the output.  If it indicates something different, please modify your question.  If it confirms your original post - then I'll have to think this over a bit more and revise my answer.

its definitely the output from the code, I have no idea why the serial monitor is outputting in the format as it is. Also can confirm that min(blue) == 22 but to make sure I lowered the range from 20 to 10 but still the same ouput.

@DrBwts - The constrain() function can be used to ensure the proper range of "numbers" is passed to the map() function: https://www.arduino.cc/reference/en/language/functions/math/constrain/

But in the code you print r, b, g before you print red map, green map then blue map.  In addtion there should be 3 lines in-between.  So the order you print values out in your question makes the reader think the r, b & g values relate to the next set of red map, green  map & blue map values.  Not previous red map, green map & blue map values as you are indicating with your red and yellow boxes.   I would try to lower the "minimum map from" value to zero just to make sure. If the problem persists, I then would simplify the code and only process the "blue" POT's input.

weirdly I amended the code to get a sensible serial output literally changing "\n\n\n" to '\n' & now its working fine

That is good news!  I will have to check my Arduino setup to be sure, but "\n" is normally just a carriage return while "\r" is a line feed.  Combined they give you both a return to the beginning of a line and advance to the next line.  But Unix (aka Linus, Android, Solaris, ect) and Windows pulls a fast one on us.  In Unix the "\r" is assumed and not needed while in Windows the "\n" is assumed and not needed.   Confused?  Most everyone was.  So, over the ensuing decades, much software was written to automatically (badly) deal w/this.  So may be true with the Arduino Serial Monitor.


text:
Eeprom write function does not seem to write in more than 100 locations
I am trying log my sensor data (1 byte each) on my Arduino Uno Eeprom. I have an ATmega328 on it, so it should allow me to write up to 1Kb on it, however I've tried the Eeprom write command and it does not seem to write to more than 100 locations on it (the first 100 bytes!)
I am using the Eepromex library.
Any thoughts on what's causing this?
Edit:
These are the excerpts from my code related to Eeprom logging:
int addr1 = 0;
int addr2 = 256;

  // Store Data in EEPROM

  EEPROM.write(addr1,FinalMoisture[0]);

    delay(5);

  EEPROM.write(addr2,FinalMoisture[1]);

    delay(5);
  // advance index pointer to the next location.  There are 256 bytes assigned for each sensor in the EEPROM, so go back to 0 when we hit 255/511.

  addr1 = addr1 + 1;

  if (addr1 == 255)
    addr1 = 0;

  //same for addr 2 :

   addr2 = addr2 + 1;

  if (addr2 == 511)
    addr2 = 256;

  // delay until next measurement (msec)
 Sleepy::loseSomeTime(30000);

PS: As mentioned earlier I've included the EepromEx library. Each sensor stores only first 50 locations. Also, I've noticed that if I run a single loop instead of storing data in two locations, I can write 100 straight entries. In any case it seems that the write function is limited to 100?
Could this be a setting in the library? How to disable/modify it? I tried looking at the info on the lib author's postings but didn't help.

Are you sure it is failing to write, or could it be failing to read? can you post the code? Does the stock eeprom library have the same issue?

When the simple eeprom write and read commands didnt work beyond 50 locations in my sensor logger code, I tried using the standard samples from the Arduino Website and same thing...  ...Tried pasting the code in here but the formatting  screws it up (never done this before!)

@Ameya, you can edit your question, and add the code there.

@Gerben thank you for the suggestion. Please find the code  included in the original question.

Try using no library. eeprom_read_byte((const uint8_t *)addr1,FinalMoisture[0]);

The address is a single byte, so you can only access the first 256 bytes of eeprom.

Looking at the library at https://github.com/thijse/Arduino-EEPROMEx/blob/master/EEPROMex.cpp it seems they limit the number of writes to 100:
EEPROMClassEx::EEPROMClassEx()
  :  _allowedWrites(100)
{
}

There seems to be a way of changing that:
/**
 * Set global maximum of allowed writes
 */
void EEPROMClassEx::setMaxAllowedWrites(int allowedWrites) {
#ifdef _EEPROMEX_DEBUG
    _allowedWrites = allowedWrites;
#endif
}

Perused the source there... the '100 write limit' should ONLY be enforced when the _EEPROMEX_DEBUG macro is defined.  Sounds like the copy of the library OP is using has the debug macro defined, thus limiting usage.

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


text:
How to program an empty Mega2560 with an Arduino sketch?
I am writing code on Arduino mega. My current code is working fine. However, I'm not using all the pins.
My question is:

I have the hex file for my code and I can purchase a Mega2560 MCU. Is there any way to upload the hex file to it and how?
What are the circuits I would need to to build?
Eagle files of the Arduino mega are available here. Is this circuit more than enough?

The Arduino circuit is overkill for production use.

@IgnacioVazquez-Abrams I didnt understand what you are saying

Last time I checked, the chip on the Mega was SMD only; that's hard to solder, and would be difficult to load a bootloader on the chip soldered to some PCBs.

@AnnonomusPenguin - the Mega2560 chip is relatively low density for a surface mount device, and fairly easy to solder once one learns that it is done by using flux and surface tension to place the solder with a normal (1-3mm) tip, not by trying to touch single pins with a tiny iron.  Secure it with a thin piece of tape diagonally, solder ONLY one corner, check alignment, solder the opposite, check alignment, then wipe solder all around.  Any bridge that won't clear with flux will clean up with fine desolder braid.

@AMPS - I've rolled-back your recent edit on this question because it substantially changed the content (including going from a 2560 to a 328, which is a different chip entirely). Editing your question to clarify it is OK, but changing it entirely (especially after there is already an answer) is not OK.

@but i found that if i post question eqicalent of that all saying replicate question. So i am changing here  itself. Yes i accept fact IC are change.

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


text:
Arduino Servo.h library returns error in compilation
I have a problem with Servo library. This is my (very short XD) "code":
#include <Servo.h>

void setup() {
  Servo.attach(9, 554, 2400);
}

void loop() {
  Servo.write(2000);
}

And it returns:
Arduino:1.6.5 (Windows 7), Board:"Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

sketch_aug24a.ino: In function 'void setup()':
sketch_aug24a:4: error: expected unqualified-id before '.' token
sketch_aug24a.ino: In function 'void loop()':
sketch_aug24a:8: error: expected unqualified-id before '.' token
expected unqualified-id before '.' token

Like there is no included library. What can I do with it ?

Servo is a class not an object. You have to instantiate it, and then call the functions on the instance. For example:
#include <Servo.h>

Servo sv;

void setup() {
  sv.attach(9, 554, 2400);
}

void loop() {
  sv.write(2000);
}

(Unlike some other libraries, it's done this way so that you can use more than one servo at the same time. You'd make one instance for each servo you want to control.)

Oh, I get it :o Clever!

But I think, my servo is broken ;_;, dammit xd


text:
What do symbols like UCSR0C, UMSEL01, etc. means?
I have a code with a connection to serial port:
// Set baud rate
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
// Disable USART rate doubler (arduino bootloader leaves it enabled...)
UCSR0A &= ~(1 << U2X0);
// Set async, no parity, 1 stop, 9bit
UCSR0C = (0<<UMSEL01)|(0<<UMSEL00)|(0<<UPM01)|(0<<UPM00)|(0<<USBS0)|(1<<UCSZ01)|(1<<UCSZ00);
UCSR0B |= (1<<UCSZ02); // 9bit
// Enable rx/tx
UCSR0B |= (1<<RXEN0)|(1<<TXEN0);

I see the comments but I want to know exactly what does these chunks means. Is there any complete documentation about these symbols?

Take a look in the datasheet under the "20. USART0" section:
http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
I will list the names of the registers, what they are called, and then what your code is doing specifically:

UBRR0H and UBRR0L together form the baud rate divider.  Your program probably uses F_CPU and <util/setbaud.h> to calculate a divider and set the baud rate.  For more information see Table 20-12.
UCSR0A  "USART Control and Status Register n A"  --  This line is enabling the U2X0 which doubles the transmission speed
UCSR0C  "USART Control and Status Register n C" --  This line is enabling the UCSZ01 and UCSZ00 bits to set parity check to "Enabled, Odd Parity".  See Table 20-9.  This line has extra information, all the statements with 0<< actually do nothing.
USCR0B " USART Control and Status Register n B" -- This line is setting the UCSZ02 bit which is described here: "The UCSZn2 bits combined with the UCSZn1:0 bit in UCSRnC sets the number of data bits (Character SiZe) in
a frame the Receiver and Transmitter use. "  This basically allows you to select 9 bit wide serial if you would like (8 bit is more common)
The final USCR0B line enables tx and rx

Thanks a lot!
How can I setup which arduino mega rx/tx port (0-usb, or 1,2,3-gpio) will it use?

@asiniy: By changing the numeral in the symbol. All 4 USARTs work exactly the same way.

Should I use USCR1B for gpio rx1/tx1?

I strongly recommend you to read the datasheet. You are confusing UART module with GPIO module. Once you use one pin for one purpose (say serial comunication) you cannot use it for another thing (say general I/O to read a physical button state). Of course it is possible if you write your code in a way it changes all the registers (the ones you call "symbols") on excecution time. But just be carefull that the routines that used those pins for UART don't execute meanwhile!


text:
Arduino Laser Trip Wire with Analytics
I've done this laser trip wire:
http://www.instructables.com/id/Another-Arduino-Laser-Tripwire/
Got it working, and now I'd like to send info to analytics - to measure how many times I enter the kitchen...
I tried to take bits of code and add it to my code from:
http://bigsnarf.wordpress.com/2013/12/24/arduino-sensor-python-and-google-analytics/
and one more which I can't post due to permissions....
but neither will work and adding this code breaks my basic functionality (I know as I measure it via the buzzer, it stops responding once I add this new code...
Is there anyone able to help?

Here is my basic working code for the laser trip wire that makes buzzer noise if someone walks through it:
/*
Jonathan Robson Feb 09.
Laser tripwire activates a buzzer. adapted from
http://www.instructables.com/id/Arduino_Laser_Tripwire/
*/

int buzzPin = 11; // buzzer connected to digital pin 11

void setup() {
  pinMode(buzzPin, OUTPUT); // sets the digital pin as output
}

void loop(){
  if(analogRead(0) < 850){ // this number depends on calibration of the photocell
    digitalWrite(buzzPin, HIGH); // turns buzzer on
    delay(1000); // waits for 1 second
    digitalWrite(buzzPin, LOW); // turns buzzer off
  } else{
    digitalWrite(buzzPin, LOW);
  }
}

Here is the code with analytics additions I’ve added:
/*
Jonathan Robson Feb 09.
Laser tripwire activates a buzzer. adapted from
http://www.instructables.com/id/Arduino_Laser_Tripwire/
*/
#include <SPI.h>
#include <Ethernet.h>

byte mac[]     = {  0x0C, 0xD2, 0x92, 0xAC, 0x75, 0x0B };

// To skip the DNS
IPAddress server(173,194,40,97); // www.google-analytics.com => 173.194.40.97
EthernetClient client;

int buzzPin = 11; // buzzer connected to digital pin 11

// Global switch (debug mode without API call)
boolean netword_enabled = true;

int sendEventToGA() {
  int responseCode      = 0;

  if (!netword_enabled) {
    return responseCode;
  }

  // open the connection
  if (client.connect(server, 80)) {
    int responseSize      = 0;
    int responseSizeMax   = 1024;
    char response[1024];
    String eventData = "v=1&tid=UA-51525058-1&cid=123&t=event&ec=home%20movement&ea=door%20open&el=bedroom"; // Refer to the Google documentation

    Serial.println("Connection opened!");

    // Write the HTTP request to the Client
    client.println("POST /collect HTTP/1.1");
    client.println("Host: www.google-analytics.com");
    client.print("Content-Length: ");
    client.println(eventData.length());
    client.println("Content-Type:application/x-www-form-urlencoded");
    client.println();
    client.println(eventData);

    Serial.println("Request sent.");

    // Wait a little bit
    delay(1000);

    // Read the response, looking for the Response Code.
    while (client.available() && client.connected() && responseCode < 100 && responseSize < responseSizeMax) {

      response[responseSize] = client.read();
      responseSize++;
      response[responseSize] = '\0'; // Set manualy the end of string char

      // Here is the magic!
      sscanf (response, "HTTP/1.%*d %d", &responseCode);

      Serial.print("HTTP code ");
      Serial.print(responseCode);
      Serial.print(" founded in ");
      Serial.println(response);
    }
  }

  Serial.println("End of communications.");

  client.stop();
  return responseCode;
}

void setup() {
  pinMode(buzzPin, OUTPUT); // sets the digital pin as output
  Serial.begin(9600);

  // start the Ethernet connection
  if (netword_enabled && Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");

    // no point in carrying on, so do nothing forevermore:
    for(;;)
      ;
  }

  // give the Ethernet shield a second to initialize:
  delay(1000);
}

void loop(){
  int responseCode;
  if(analogRead(0) < 850){ // this number depends on calibration of the photocell
    digitalWrite(buzzPin, HIGH); // turns buzzer on
    responseCode = sendEventToGA();
    delay(1000); // waits for 1 second
    digitalWrite(buzzPin, LOW); // turns buzzer off
  } else{
    digitalWrite(buzzPin, LOW);
  }
}

Welcome to Arduino SE! Can you please add your code? If you "can't post it because of permissions," you probably can't even use it. Also, it's generally okay if you cite your source (although it's your call). Either way, it's impossible to tell you how to fix your code without seeing it. If you can narrow it down to a small section and post that, it'd be fine to do so (along with any dependencies/extra functions it calls). Until then, we can't really help you. The only advice I can give you is this: does the code sending it to the serial port block the checking function? Is there a delay()?

I'm trying but my code is over 2k characters and there's a limit here to 600 characters per response.....

I also started reading an arduino book and it mentions Ethernet shield - so I ordered that... Here is a link to my code hosted on Google docs (I couldn't figure out how to use github) https://docs.google.com/document/d/19zs9w6boCrlycgCAMj2P_llAl-arpekeR1IbDxO4J70/edit?usp=sharing

Do you get no buzzer? Or does the buzzer start, but not stop?

in my current code - everything works fine. in the version with updated analytics - the buzzer doesn't stop when hovered by laser. But again - as above, I don't even have the ethernet shield addon  - so maybe when I have that it will work? Maybe that's why there's a conflict.

@KrystianS Did you ever end up trying this with the Ethernet shield? Did it make a difference?

I'm voting to close this question as off-topic because it has been abandoned for 3 years without information to make it answerable ever being provided.

As with any piece of code that doesn't work, it is very easy to troubleshoot using the Serial.println() statement.
The big clue here is that the buzzer turns on but never turns off. Go ahead and add unique Serial.println() statements between each statement in the loop() function.
My guess is that the digitalWrite(buzzPin, HIGH) executes but it never exits the sendEventToGA() function.
If this is the case, then go ahead and add unique Serial.println() statements in between each line of the sendEventToGA() code.
Again, my guess is that the code goes into the while() statement and never comes out. This while statement is waiting for a response from the server. If you never get a response it won't exit.
Perhaps add a timeout or determine why Google Analytics isn't returning a response.
Help on the topic can be found at the Arduino Libraries reference pages:

EthernetClient()
Ethernet Library


text:
GSM dongle instead of GSM shield?
I googled for this problem many times and ended up with no results, so I decided to post it here.
Can we use a GSM Dongle (usb dongle) instead of a GSM shield (like SIM900 module) to send and receive SMS in Arduino? If so how it is possible?

YES you can with an Arduino Yùn
The dongle will have to be handled by the linux part of the board and doing so will leave you all the I/O pin free for your project.
You might want to check out this for the howto:
https://n00bsys0p.wordpress.com/2009/08/26/sending-recieving-sms-with-a-3g-device-in-linux/

this link was drives me to the correct track.i have done it in Ubuntu in my laptop and it was successful. next i gonna try it on my Galileo board

Not directly. The standard Arduino Uno doesn't have the hardware/software necessary to act as a USB host, which means it can't talk directly to other USB devices.
You might be able to get it work via a USB Host Shield. I don't know how compatible that is with GSM dongles though because I assume you can't install drivers on it. Additionally, if you're using a shield anyway, you might as well use a GSM shield.
If you're able to get an alternative board then another possibility might be the Arduino Yún. It has a USB host built-in which is operated by the Linux part of the board. I don't know for certain that it would handle a GSM dongle, but it may be worth looking into.

So all we need to accomplish  above task is a USB host port. i think Intel galileo generation 2 boards have a USB host port.that is the board which I going to use in my project.

No, not "all you need" - you need the port, and you need a software stack to drive it.

You can search for, or create your own 'breakout' board.
You could actually get an sim900 chip running on a breadboard.
I think  this might be most usefull to you: http://img01.cp.aliimg.com/imgextra/i2/87365807/T267qSXa4aXXXXXXXX_!!87365807.jpg
http://www.aliexpress.com/store/product/Gprs-module-gsm-gprs-module-sim900-development-board-mini-v2-module/124015_1030035160.html
Though this one is quite expensive. (As it doesn't even has a SIM900 on it?)
There is no reason the SIM900 can't work withouth arduino board..
But the reason it's used with an 'shield' is because it's easier to connect and enables to draw power from the arduino. (You do need a good supply for the sim900, it can have peak-power levels, which might reset your arduino)

So yes, you could make your own dongle based on a SIM900! Which works great for Embedded/Realtime (UNO).
But also, you might want to use a board that has Linux (But bear in mind that this is 'completely' different from the UNO. Check the other answer in this case.
Edited, Chris explained me you simply can't use an usb device withouth a USB host with USB driving software.

A USB stick would not work at all with a another USB peripheral such as a "serial TTL converter" - it requires not only a USB host, but software to drive that.

@ChrisStratton I failed common sense there.
Edited my answer.
Also, you could make a SIM900-based 'dongle' (not for usb, but UART)?
Using the Yún could be overkill?

Usually, these usb dongles consist of two parts: the usb part, and the gsm part. If you can find the spec on the gsm chip, you might be able to bypass the usb part.
Unfortunately, these circuits are usually surface mount - tiny pins, tiny traces, and lots of them. Soldering them will probably be tricky.

also im in the try of that.YOU HAVE TO USE USB TO SERIAL CONVERTOR CIRCUIT TO ACCESS ARDUINO BY UART (mosi....... miso) connections .and the software in the dongle is the problem here.the difference between the gsm shield and the dongle is .........the SOFTWARE  FIREWALL you have to flash the dongle by your own risk.........try this


text:
What are the current limits on an Arduino Micro?
Just to make sure I don't set my board on fire, is there any information out there about the maximum current per pin/pin group on an Arduino Micro?
This page states I can get 40mA per pin, but are there limits on group of pins?
As stated here, there are pin groups which should not exceed 100mA. But could not find anything about that in the ATmega32u4 datasheet, or any other Arduino Micro related websites.

It's in the notes in section 29.2:

Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state
  conditions (non-transient), the following must be observed:
  ATmega16U4/ATmega32U4:
  1.)The sum of all IOL, for ports A0-A7, G2, C4-C7 should not exceed 100 mA.
  2.)The sum of all IOL, for ports C0-C3, G0-G1, D0-D7 should not exceed 100 mA.
  3.)The sum of all IOL, for ports G3-G5, B0-B7, E0-E7 should not exceed 100 mA.
  4.)The sum of all IOL, for ports F0-F7 should not exceed 100 mA.
  If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
  than the listed test condition.
Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady
  state conditions (non-transient), the following must be observed:
  ATmega16U4/ATmega32U4:
  1)The sum of all IOH, for ports A0-A7, G2, C4-C7 should not exceed 100 mA.
  2)The sum of all IOH, for ports C0-C3, G0-G1, D0-D7 should not exceed 100 mA.
  3)The sum of all IOH, for ports G3-G5, B0-B7, E0-E7 should not exceed 100 mA.
  4)The sum of all IOH, for ports F0-F7 should not exceed 100 mA.

Note that the device will likely not fail if these are exceeded, but the rest of the numbers in the table may no longer apply.


text:
Code for four road junction
This is the Arduino code for a four road junction. In the below code, the if case must be tested after every road without delay. Can any one guide me?
int redLed1 = 7;
int yellowLed1 = 6;
int greenLed1 = 5;
int redLed2 = 4;
int yellowLed2 = 3;
int greenLed2 = 2;
int redLed3 =8 ;
int yellowLed3 =9;
int greenLed3 =10;
int redLed4 = 14;
int yellowLed4 = 15;
int greenLed4 =16;
int THRESHOLD=700;
int soundvalue=0;
void setup()
{
    pinMode(redLed1, OUTPUT);
    pinMode(yellowLed1, OUTPUT);
    pinMode(greenLed1, OUTPUT);
    pinMode(redLed2, OUTPUT);
    pinMode(yellowLed2, OUTPUT);
    pinMode(greenLed2, OUTPUT);
    pinMode(redLed3, OUTPUT);
    pinMode(yellowLed3, OUTPUT);
    pinMode(greenLed3, OUTPUT);
    pinMode(redLed4, OUTPUT);
    pinMode(yellowLed4, OUTPUT);
    pinMode(greenLed4, OUTPUT);
}

void loop()
{
    digitalWrite(redLed2,HIGH);
    digitalWrite(redLed3,HIGH);
    digitalWrite(redLed4,HIGH);
    digitalWrite(redLed1,HIGH);
    digitalWrite(yellowLed1,HIGH);
    delay(5000);
    digitalWrite(redLed1,LOW);
    digitalWrite(yellowLed1,LOW);
    digitalWrite(greenLed1,HIGH);
    if(analogRead(A0)>=THRESHOLD)
    {
        digitalWrite(greenLed2,LOW);
        digitalWrite(greenLed1,HIGH);
        delay(10000);
        digitalWrite(greenLed1,LOW);
    }
    delay(30000);
    digitalWrite(greenLed1,LOW);
    digitalWrite(redLed1,HIGH);
    digitalWrite(yellowLed2,HIGH);
    delay(5000);
    digitalWrite(redLed2,LOW);
    digitalWrite(yellowLed2,LOW);
    digitalWrite(greenLed2,HIGH);

    delay(30000);
    digitalWrite(greenLed2,LOW);
    digitalWrite(redLed2,HIGH);
    digitalWrite(yellowLed3,HIGH);
    delay(5000);
    digitalWrite(redLed3,LOW);
    digitalWrite(yellowLed3,LOW);
    digitalWrite(greenLed3,HIGH);

    delay(30000);
    digitalWrite(greenLed3,LOW);
    digitalWrite(redLed3,HIGH);
    digitalWrite(yellowLed4,HIGH);
    delay(5000);
    digitalWrite(redLed4,LOW);
    digitalWrite(yellowLed4,LOW);
    digitalWrite(greenLed4,HIGH);
    delay(30000);
    digitalWrite(greenled4,LOW);

    }
}

It's hard to tell what you're asking. Can you edit your question to explain it more clearly please?

NOTE: all the code below is thrown together; it is there to show you what to do. It will probably require some fixing before it works. The intent should be clear.
From what I read in your code, mostly what you are doing is setting the traffic lights in particular combinations, several times over, with delays in between.
In general, any time you do the same thing, conceptually, several times, it should either be in a loop, or in a function.
In this case, the first thing that (to me) looks like it belongs in a function is: set all the lights in a particular pattern, and wait for a while. I would call this function something like set_lights_and_delay (or, perhaps setLightsAndDelay depending on your coding style). It would take 5 parameters: the state of each light (red, green, or yellow/red, which I would just call yellow), and the time to delay (which may be 0). In this function, you would set ALL the pins, high or low, as appropriate (since your function shouldn't assume the previous state), then delay the appropriate amount of time.
enum colors {yellow, red, green, yellowred};

void loop()
{
    set_lights_and_delay(yellow,red,red,red,5000);
    if(analogRead(A0)>=THRESHOLD)
    {
      set_lights_and_delay(green,red,red,red,40000);
    } else {
      set_lights_and_delay(green,red,red,yellowred,30000);
    }

... and so forth (or whatever light combinations you want).
Now, how would you write this function? This function does the same thing for each light, so it sounds to me like you would want to make a function that takes a color, and the 3 pins to use:
void setLightsAndDelay(color northlight, eastlight, westlight, southlight; int delaytime)
{
    setOneLight(northlight, redLed1, yellowLed1, greenLed1);
    setOneLight(eastlight, redLed2, yellowLed2, greenLed2);
    setOneLight(westlight, redLed3, yellowLed3, greenLed3);
    setOneLight(southlight, redLed4, yellowLed4, greenLed4);
    delay(delaytime);
}

Now, setOneLight is pretty simple to write:
void setOneLight(color thisLight; int redled, yellowled, greenled)
{
    if (thisLight==green) // always do the easiest one first.
    {
        digitalWrite(greenled,HIGH);
    } else {
        digitalWrite(greenled,LOW);
    }

    if (thisLight==yellow) || (thislight==yellowred)
    {
        digitalWrite(yellowled,HIGH);
    } else {
        digitalWrite(yellowled,LOW);
    }

    if (thisLight==red) || (thisLight==yellowred)
    {
        digitalWrite(redled,HIGH);
    } else {
        digitalWrite(redled,LOW);
    }
}

In practice, there would be a lot of other things I'd do: I'd put all the things I know about a single traffic light into a struct; this means I could pass the struct to a function, in one go. I'd put the four traffic lights in an array; this means I could go through them in a loop, rather than calling the same function 4 times individually (great when your city ends up with 1,000 traffic lights!). I would probably put the pattern of lights (green/30000, yellow/10000, red/30000, yellowred/10000) into an array (made a little more difficult by the sensor).

I'm not sure what a “road” condition is, so I don't know where the “after every road” points in your code are located.  However, you can write a properly-parameterized function to do tests, or a subroutine to do tests and perform actions.  Then place a function or subroutine call whereever you need to perform the test.
Note, the first 14 lines of your code (which define 14 variables that you probably should have defined as constants) could be replaced by an enum statement (which defines integer constants) like
enum { redLed1=7, yellowLed1=6, greenLed1=5, redLed2=4, yellowLed2=3, greenLed2=2, redLed3=8, yellowLed3=9, greenLed3=10, redLed4=14, yellowLed4=15, greenLed4=16, THRESHOLD=700, soundvalue=0 };

or (because enum will advance by 1 unit when a value isn't specified) you could say
enum { greenLed2=2, yellowLed2, redLed2, greenLed1, yellowLed1, redLed1, redLed3, yellowLed3, greenLed3, redLed4=14, yellowLed4, greenLed4, THRESHOLD=700, soundvalue=0 };

For a short sketch like this, the compiler can detect that some of your variables actually are constants, but in general using constants as constants and variables as variables will produce smaller and safer code.


text:
Parallel servo control?
I have an Arduino Nano & am success fully controlling 4 servos from it but it then occurred to me that I am controlling these in a serial manner, ie I set 1 position then the next then the next....
I would like the servos to act in a parallel manner i.e. that their motions can happen at the same time but at different speeds or different position.
Is this possible using just 1 controller (maybe some sort of polling/interrupt setup?) or will I need to run separate controllers for each set of servos & synchronize them?
EDIT: Added the PC side code & the Arduino side code
PC Python code:
from Tkinter import *
import serial

usbport = 'COM5'
ser = serial.Serial(usbport, 9600, timeout=1)

def init():
    for servo in range(1, 5):
        print servo
        ser.write(chr(255))
        ser.write(chr(servo))
        ser.write(chr(90))

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()
        self.scale1 = Scale(master, from_=0, to=180, command=lambda ev: self.getAngle(1), bd=5, bigincrement=2, length=360, width=30, label='Servo 1')
        self.scale1.set(90)
        self.scale1.pack(side=LEFT)
        self.scale2 = Scale(master, from_=0, to=180, command=lambda ev: self.getAngle(2), bd=5, bigincrement=2, length=360, width=30, label='Servo 2')
        self.scale2.set(90)
        self.scale2.pack(side=LEFT)
        self.scale3 = Scale(master, from_=0, to=180, command=lambda ev: self.getAngle(3), bd=5, bigincrement=2, length=360, width=30, label='Servo 3')
        self.scale3.set(90)
        self.scale3.pack(side=LEFT)
        self.scale4 = Scale(master, from_=0, to=180, command=lambda ev: self.getAngle(4), bd=5, bigincrement=2, length=360, width=30, label='Servo 4')
        self.scale4.set(90)
        self.scale4.pack(side=LEFT)
        self.centre = Button(frame, text="Centre All", command=self.centre)
        self.centre.pack(side=TOP)

    def getAngle(self, slider):
        if slider==1:
            ang = self.scale1.get()
        if slider==2:
            ang = self.scale2.get()
        if slider==3:
            ang = self.scale3.get()
        if slider==4:
            ang = self.scale4.get()
        ser.write(chr(255))
        ser.write(chr(slider))
        ser.write(chr(ang))

    def centre(self):
        for servo in range(1, 5):
            ser.write(chr(255))
            ser.write(chr(servo))
            ser.write(chr(90))
        self.scale1.set(90)
        self.scale2.set(90)
        self.scale3.set(90)
        self.scale4.set(90)

init()
root = Tk()
app = App(root)
root.mainloop()

Arduino code
*
 * ------------------------------
 *   MultipleSerialServoControl
 * ------------------------------
 *
 * Uses the Arduino Serial library
 *  (http://arduino.cc/en/Reference/Serial)
 * and the Arduino Servo library
 *  (http://arduino.cc/en/Reference/Servo)
 * to control multiple servos from a PC using a USB cable.
 *
 * Dependencies:
 *   Arduino 0017 or higher
 *     (http://www.arduino.cc/en/Main/Software)
 *   Python servo.py module
 *     (http://principialabs.com/arduino-python-4-axis-servo-control/)
 *
 * Created:  23 December 2009
 * Author:   Brian D. Wendt
 *   (http://principialabs.com/)
 * Version:  1.1
 * License:  GPLv3
 *   (http://www.fsf.org/licensing/)
 *
 */

// Import the Arduino Servo library
#include <Servo.h>

// Create a Servo object for each servo
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;

// Common servo setup values
int minPulse = 600;   // minimum servo position, us (microseconds)
int maxPulse = 2400;  // maximum servo position, us

// User input for servo and position
int userInput[3];    // raw input from serial buffer, 3 bytes
int startbyte;       // start byte, begin reading input
int servo;           // which servo to pulse?
int pos = 90;        // servo angle 0-180
int i;               // iterator

// LED on Pin 13 for digital on/off demo
int ledPin = 13;
int pinState = LOW;

void setup()
{
  // Attach each Servo object to a digital pin
  servo1.attach(3, minPulse, maxPulse);
  servo2.attach(4, minPulse, maxPulse);
  servo3.attach(5, minPulse, maxPulse);
  servo4.attach(9, minPulse, maxPulse);

  // LED on Pin 13 for digital on/off demo
  pinMode(ledPin, OUTPUT);

  // Open the serial connection, 9600 baud
  Serial.begin(9600);
}

void loop()
{
  // Wait for serial input (min 3 bytes in buffer)
  if (Serial.available() > 2) {
    // Read the first byte
    startbyte = Serial.read();
    // If it's really the startbyte (255) ...
    if (startbyte == 255) {
      // ... then get the next two bytes
      for (i=0;i<2;i++) {
        userInput[i] = Serial.read();
      }
      // First byte = servo to move?
      servo = userInput[0];
      // Second byte = which position?
      pos = userInput[1];
      // Packet error checking and recovery
      if (pos == 255) { servo = 255; }

      // Assign new position to appropriate servo
      switch (servo) {
        case 1:
          servo1.write(pos);    // move servo1 to 'pos'
          break;
        case 2:
          servo2.write(pos);
          break;
        case 3:
          servo3.write(pos);
          break;
        case 4:
          servo4.write(pos);
          break;

        // LED on Pin 13 for digital on/off demo
        case 99:
          if (pos == 180) {
            if (pinState == LOW) { pinState = HIGH; }
            else { pinState = LOW; }
          }
          if (pos == 0) {
            pinState = LOW;
          }
          digitalWrite(ledPin, pinState);
          break;
      }
    }
  }
}

How are you currently controlling them? With buttons or through USB with a PC? Or just hardcoded movements? What type of servo's do you use? The servo's I usually use have just 1 speed and don't give any feedback. With moving slow you would mean delaying between small steps of rotation?

I assume you are using a library for this. All the libraries already do this for you. As you need to continuously send position data (once every 20ms) to the servo.

Thanks for the replies. I have made an edit to the OP with the relevant code added. I'm controlling the servos from a PC using Tinker's sliders. I think I'm just having a conceptual block here. Would I be right in saying that the above code controls the servos in a serial fashion (eg the centre() function in the Python code the servo's are looped through)?

The python code is polling through the servos sequentially/serialy, but the arduino code looks parallel.  The arduino will parse the string and pass the command to the servo code, passing control back to the loop() command before the servo reaches its assigned position.  Maybe that is your question: "is servo.write(position) a blocking call?"  If so, the answer is no, it is non-blocking, the motors will drive at the motors speed to the final positions independently.  If you want coordinated movement through this scheme, you have to break the  movements up and coordinate it on the python side.

In my opinion your code already does what you want to do. It's just that you can't move the sliders "in parallel" cause you, as human, are too slow.  If you want to be able to make sinchronized movements, you can put a button on the UI which sends the sliders positions to the arduino instead of sending them when the sliders position change. This way you can set the coordinated moves. As for the speed, you'll have to slow down the movements making small increments instead of setting the final value to the servo. If you need it I can write some pieces of code for this

The python code is polling through the servos sequentially/serialy, but the arduino code looks parallel. The arduino will parse the string and pass the command to the servo code, passing control back to the loop() command before the servo reaches its assigned position. Maybe that is your question: "is servo.write(position) a blocking call?" If so, the answer is no, it is non-blocking, the motors will drive at the motors speed to the final positions independently. If you want coordinated movement through this scheme, you have to break the movements up and coordinate it on the python side without feedback.
For instance, if you want to go from position (90,90,90,90) to position (81,0,90,90) you will need to know it takes 900ms (for example) to complete the -90 move, and break it up into 10 segments of 100ms to coordinate the (-1,0,-10,0) steps.  Doing the coordination without feedback will be awkward, and might be better handled from your python/UI side.

You can use an interpolation library and interpolate in-between as many servos as you like. The YouTube channel James Bruton does it on a lot of his robots so you can probably learn from his code. Also check out this GitHub repository:
https://github.com/luisllamasbinaburo/Arduino-Interpolation


text:
Mega code not compiling on Wemos Mega board
Hi I have some code that I'm trying to port from a Mega 2560 R3 to a Wemos Mega.
#include "SoftPWM.h"
#include ESP8266WiFi.h

// Outputs to PWM & H bridge direction
// PWMs:
// DC_pwm, left_pwm, right_pwm = 3, 4, 5
int pwm_out[] = {3, 4, 5};
const int num_pwm = sizeof(pwm_out) / sizeof(pwm_out[0]);

// H bridge direction control:
// dc_1, dc_2, left_1, left_2, right_1, right_2 = 6, 7, 8, 9, 10, 11
int dir_pins[] = {6, 7, 8, 9, 10, 11};
const int num_dir_pins = sizeof(dir_pins) / sizeof(dir_pins[0]);

// Variable for reading pin inputs
int from_r_pi_pwm = 0;
int from_r_pi_dir = 0;

void setup() {

  // Inputs from Raspberry Pi
  Serial.begin(38400);

  // Set up PWM pins
  SoftPWMBegin();
  for (int i = 0; i < num_pwm; i++)
  {
    SoftPWMSet(pwm_out[i], 0);
  }

  // Set up H bridge direction pins
  for (int i = 0; i < num_dir_pins; i++)
  {
    pinMode(dir_pins[i], OUTPUT);
    digitalWrite(dir_pins[i], LOW);
  }
}

void loop() {

  // Check input from R Pi & send it to the H bridges
  while (Serial.available() < 2){}

  if (Serial.available()) {
      // read the incoming bytes:
      from_r_pi_dir = Serial.read();
      from_r_pi_pwm = Serial.read();
      Serial.print("Serial in: directions - ");
      Serial.print(from_r_pi_dir);
      Serial.print(" PWM - ");
      Serial.print(from_r_pi_pwm);
      Serial.println();
  }

  // Set direcions on H bridges
  for (int i = 0; i < num_dir_pins; i++)
  {
    digitalWrite(dir_pins[i], bitRead(from_r_pi_dir, i));
    Serial.print("pin ");
    Serial.print(dir_pins[i]);
    Serial.print(" : ");
    Serial.print(digitalRead(dir_pins[i]));
    Serial.println();
  }

  // PWM to motors
  for (int i = 0; i < num_pwm; i++)
  {
    analogWrite(pwm_out[i], from_r_pi_pwm);
    Serial.print("pin ");
    Serial.print(pwm_out[i]);
    Serial.print(" : ");
    Serial.print(digitalRead(pwm_out[i]));
    Serial.println();
  }
}

This compiles and runs fine on a Mega & is my go to code for setting up pwm & h bridges.
So when I was playing with WiFi I selected the Wemos R1 board from the programmer & everything worked fine but if I try that with this code I get,
#include <avr/io.h>
                    ^
compilation terminated.

exit status 1 Error compiling for board WeMos D1 R1.

So after a bit of searching I found that I should be selecting Arduino/Genuino Mega 2560 but now the upload keeps timing out,
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
An error occurred while uploading the sketch

Anybody come across this before?
Edit #1:  As per the comment below I tried setting DIP switches 1 & 2 ON and all the rest OFF (I also tried 1, 2, 3 & 4 ON and the rest OFF) but still the same compliation error if I select Wemos board.
If I select the Mega 2560 I get ESP8266WiFi.h: No such file or directory which is a new error!

You cannot simply compile code for the Mega also for the WeMos. It is complete different hardware. The Arduino Mega uses an Atmega chip, while the WeMos is an ESP. You will have to go through the whole code, change the pins, check if the required hardware is available in this chip and check, if the used libraries are compatible with the ESP. Porting is mostly not an easy task.

the wemos board is a Mega & an eps on the same board. See here

switch the dip switches 1 and 2 ON all other OFF

@Juraj tried that but still the same compliation error if I select Wemos board & if I select the Mega 2560 I get ESP8266WiFi.h: No such file or directory

The Wemos/Mega board and IDE setup is complex and not for the faint hearted. Here is the table for the DIP switch setting:
1=ON  2=ON  3=OFF 4=OFF 5=OFF 6=OFF 7=OFF 8=OFF (ATmega2560<->ESP8266)
1=OFF 2=OFF 3=ON  4=ON  5=OFF 6=OFF 7=OFF 8=OFF (USB <->ATmega2560)
1=OFF 2=OFF 3=OFF 4=OFF 5=ON  6=ON  7=ON  8=OFF (USB<->ESP8266 (Update firmware or sketch))
1=OFF 2=OFF 3=OFF 4=OFF 5=ON  6=ON  7=OFF 8=OFF (USB<->ESP8266 (communication))
1=OFF 2=OFF 3=OFF 4=OFF 5=OFF 6=OFF 7=OFF 8=OFF (All independent)

Table DIP switch Special Solution:
1=ON 2=ON 3=ON 4=ON 5=OFF 6=OFF 7=OFF 8=OFF (USB <-> ATmega2560<-> ESP8266)
USB converter CH340G connect to RX0/TX0 of ATmega2560
ESP8266 connect to RX3/TX3 of ATmega25

https://arduino-esp8266.readthedocs.io/en/latest/index.html for ESP8266 documentation.
Set the Additional Boards URL to http://arduino.esp8266.com/stable/package_esp8266com_index.json in preferences
Under Tools select Board then Board Manager, then install the esp8266 by ESP8266 Community
The Arduino IDE setup requires understanding what board setting and communication setting to use to build and upload a sketch.
Under Tools select Board then select the "Arduino/Genuino Mega or Mega 2560"
Set the DIP switches on the actual board to 1=OFF 2=OFF 3=ON 4=ON 5=OFF 6=OFF 7=OFF 8=OFF (USB <->ATmega2560)
That was the DIP switch and USB setup.
Ref. https://forum.arduino.cc/index.php?topic=578430.0
The error ESP8266WiFi.h: No such file or directory is easy. The file name should be a string: #include "ESP8266WiFi.h".


text:
help with input in a Simon arduino uno game
I' making a Simon game with the arduino uno.
I know something is wrong with the inputs but i don't know why or how to fix it.
The problem is the program takes an input and says it is correct no matter what it is or the length
#define NOTES

int tones[] = {NOTE_E5, NOTE_E6, NOTE_CS6, NOTE_A6};
String sequence;

void setup() {
    pinMode(13, OUTPUT); //green
    pinMode(12, OUTPUT); //yellow
    pinMode(11, OUTPUT); //blue
    pinMode(10, OUTPUT); //red
    pinMode(7, INPUT); //green
    pinMode(6, INPUT); //yellow
    pinMode(5, INPUT); //blue
    pinMode(4, INPUT); //red
    Serial.begin(9600);
}

void loop() {
    while(true) {
        delay(1000);
        randomSeed(random(random(1000000000)));
        sequence = String(random(4));
        boolean run = true;
        while(run) {
            for(int i = 0; i < sequence.length(); i++) {
                simonOut(sequence.charAt(i) - '0');
                delay(500);
                simonClear();
                delay(100);
            }
            for(int i = 0; i < sequence.length(); i++) {
                int input = simonIn();
                while(input < 0 || input > 3) {
                    delay(50);
                    input = simonIn();
                }
                if(sequence.charAt(i) - '0' == input) {
                    flash(0);
                    run = false;
                    goto reset;
                }
                else if(i = sequence.length() - 1)
                    flash(3);
            }
            sequence += random(4);
        }
        reset:;
    }
}

void boolOut(long pin, boolean val) {
    digitalWrite(pin,val ? HIGH : LOW);
}

void simonOut(long num) {
    boolOut(num + 10, true);
    tone(2, tones[num]);
}

 void flash(int led) {
     delay(300);
     for(int i = 0; i < 5; i++) {
         simonOut(led);
         delay(100);
         simonClear();
         delay(100);
     }
 }

 void simonClear() {
     for(int i = 0; i < 4; i++){
         boolOut(i + 10, false);
     }
     noTone(2);
 }

 int simonIn() {
     int ret = -1;
     for(int i = 0; i < 4; i++) {
         if(simonIn(i)){
             ret = i;
         }
     }
     if(ret != -1) {
         simonOut(ret);
         delay(500);
         simonClear();
         delay(100);
     }
 }

 boolean simonIn(long num) {
     return digitalRead(num + 4) == HIGH;
 }

Schematic where?

i already thoroughly tested the schematic it is good. pins 10 - 13 are light outputs; pins 4-7 are push button inputs.

So then your inputs and outputs are working perfectly?

yes, a test program was created so that when button pressed corresponding lights were turned on and outputted corresponding sound, and it worked as intended.

Please provide us of a schematic. With a schematic we've got a reference how your hardware setup is and how the programming should be. We don't know anything. Have you included other libraries into your sketch? That's important to know when we want to try to debug your sketch. When I get a full documentation of your script and a schematic I can try to help you, but I can't now.

The problem in your code is there:
int simonIn() {
    int ret = -1;
    for(int i = 0; i < 4; i++) {
        if(simonIn(i)){
            ret = i;
        }
    }
    if(ret != -1) {
        simonOut(ret);
        delay(500);
        simonClear();
        delay(100);
    }
}

This method never returns any value, so that means the caller will just tke whatever is in the stack at that time:
            int input = simonIn();
            while(input < 0 || input > 3) {
                delay(50);
                input = simonIn();
            }

input could be anything there.
So the fix should be easy:
int simonIn() {
    int ret = -1;
    for(int i = 0; i < 4; i++) {
        if(simonIn(i)){
            ret = i;
        }
    }
    if(ret != -1) {
        simonOut(ret);
        delay(500);
        simonClear();
        delay(100);
    }
    return ret;
}

It's surprising you did not get a warning from the compiler on that one, which IDE do you use?
Finally, regarding your code, I would also advise you the following improvements:

break down the loop() code further into functions that do ONE thing, e.g. showSequence(sequence), checkInput(seuquence), readSimonInput() (this last function would only return a value between 0 and 3 included. That would make your code much clearer.
use the right types for your variables: I see you abuse usage of long where int or byte, or you mix different types for the same data, thus forcing the compiler to cast data on some function calls.
avoid hardcoding constants in your code, e.g. you could define the number of buttons, the first pin of buttons, the first pin of LEDs, the various delays.

Is it possible that your problem might be just a typo?

#define NOTES
int tones[] = {NOTE_E5, NOTE_E6, NOTE_CS6, NOTE_A6};

In your array you talk about NOTE and you defined NOTES (See the S?)

that was shorthand because i didn't want to copy and past all 100+ lines of note definitions from my code


text:
MOSFET to dim LED backlight
I have built the following to dim the brightness of the LED backlight of a display:

I am using a BS170 MOSFET (the diode is no extra part but included in the MOSFET, according to the datasheet). The BL pin is the supply of the LED backlight. (I have left out all other pins.)
Unfortunately, it does not work. Even if I set the PWM pin to 255, the backlight does not light (actually it's completely off). If I short BL and Vcc, it lights up as it should.
Also, the voltage readings confuse me: I measure 3.3 V on the gate and drain against ground, 1.5 V on source against ground (= the voltage across the backlight) but only 1 V if I measure drain against source.
So my questions are:

Shouldn't this add up to 3.3 V?
More importantly, why do I get only 1.5 V at BL?
Most importantly, what do I need to change? Different MOSFET? No MOSFET?

The primary aim of controlling the backlight is to be able to switch in off completely, thus reducing power consumption. (Being able to dim it is only a plus.)
EDIT
I should have added details about the display. It's one of those:

I haven't found a datasheet / specs for exactly this model. Most datasheets I found refer to a different version that is not 5 V compatible. A very similar model is described here.
Concerning my question I haven't found information on how much current the backlight would draw. Therefore I didn't want to drive it directly from the PWM pin. (Actually I could just measure it...)

Summary:
It looks as though you can just drive BL directly with the PWM-output.
What happens when you do?

Details:
(1)  As shown, even  if the circuit did what you wanted, all you would be doing is providing a rail to rail (0V to 3.3V ) signal to the BL pin. You can do this by connecting PWM-out to BL directly.
Does this work?
If the LCD and Arduino used differing power supplies the MOSFET may be useful.
(2) To use circuit almost as-is you need a PChannel FET.
Swap Drain and Source and it will provide PWM to the BL pin. When BL is high the FET is off. When BL is low the FET is on. The FET used must turn on with about 3V between gate and source.
(3) To use the N Channel BS170 you must drive the gate +ve above the source by an amount that is enough to just turn it one "plus a little more". This is called Vth (Vthreshold). The BS170 has Vth ~= 1.8V at low currents. Vth varies somewhat between samples. When you connect the gate to +3.3V the FET tried to turn on but as the source rises it reduced Vgs until it reaches about Vth. Raising the source above this level reduced Vgs to below Vth so the FET is not turned on.
ie this is what a=accounts for the 1.5V that you see as 3.3V - 1.8V = 1.5V.
To use the BS170,
connect the source to ground,
connect drain via a say 1k resistor to +3.3V,
connect drain to BL,
drive gate with PWM.
BUT why does not just driving BL with PWM do what you want?
A data sheet for the display would be useful.

Driving BL directly from the PWM might actually work, I will consider that. But what I was trying to learn is what I was doing wrong when using the BS170 like that, and you answered that nicely!

It turns out the backlight draws 4.5 mA @ 3.3 V. So I can get rid of the MOSFET altogether.

Since you are switching on the high side, you need a P-channel mosfet, not an N-channel like the BS170. (Or you need a higher voltage on the Gate to reach the VGS(th)).
I have a similar display, but mine will light up if BL is connected to ground. For these kind of displays you'd use a N-channel mosfet.


text:
Can't figure out the error to this code
I've written up this very simply code to control transistors in an inverter circuit. The editor is flagging up errors which I can't see myself. I'm pretty new to Arduino programming but it's very simple code and can't see why it's being shown as having errors.
At first glance, what am I missing? I've pasted a section below:
int Phase1pos = 13;
int Phase2pos = 12;
int Phase3pos = 11;
int Phase1neg = 10;
int Phase2neg = 9;
int Phase3neg = 8;

void setup() {
pinMode(Phase1pos, OUTPUT);
pinMode(Phase2pos, OUTPUT);
pinMode(Phase3pos, OUTPUT);
pinMode(Phase1neg, OUTPUT);
pinMode(Phase2neg, OUTPUT);
pinMode(Phase3neg, OUTPUT);
}

void loop() {
    delayMicroseconds(16);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(16);

    delayMicroseconds(7);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(7);

    delayMicroseconds(2);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(2);

    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(104);
    digitalWrite(Phase2pos, HIGH);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(208);
    digitalWrite(Phase1pos, LOW);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(104);
    digitalWrite(Phase3neg, LOW);

    delayMicroseconds(2);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase3neg, LOW);

    delayMicroseconds(7);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(7);

    delayMicroseconds(16);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase3neg, LOW);
    digitalWrite(16);

    delayMicroseconds(28);
    digitalWrite(Phase3neg, HIGH);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(180);
    delayMicroseconds(180);
    digitalWrite(Phase1pos, LOW);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(28);

    delayMicroseconds(16);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(16);

    delayMicroseconds(7);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase1pos, LOW);

    delayMicroseconds(2);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(2);

    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(104);
    digitalWrite(Phase2neg, HIGH);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(208);
    digitalWrite(Phase3neg, LOW);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(104);
    digitalWrite(Phase1pos, LOW);

    delayMicroseconds(2);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(2);

    delayMicroseconds(7);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(7);

    delayMicroseconds(16);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(16);

    delayMicroseconds(28);
    digitalWrite(Phase1pos, HIGH);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(180);
    delayMicroseconds(180);
    digitalWrite(Phase2neg, LOW);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(28);

    delayMicroseconds(16);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(16);

    delayMicroseconds(7);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(7);

    delayMicroseconds(2);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(2);

    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(104);
    digitalWrite(Phase1pos, HIGH);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(208);
    digitalWrite(Phase3pos, LOW);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(104);
    digitalWrite(Phase2neg, LOW);

    delayMicroseconds(2);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(2);

    delayMicroseconds(7);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(7);

    delayMicroseconds(16);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase1pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase1pos, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(16);

    delayMicroseconds(28);
    digitalWrite(Phase2neg, HIGH);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(180);
    delayMicroseconds(180);
    digitalWrite(Phase3pos, LOW);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(28);

    delayMicroseconds(16);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(16);

    delayMicroseconds(7);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(7);

    delayMicroseconds(2);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(2);

    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(104);
    digitalWrite(Phase1neg, HIGH);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(208);
    digitalWrite(Phase2neg, LOW);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(104);
    digitalWrite(Phase3pos, LOW);

    delayMicroseconds(2);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(2);

    delayMicroseconds(7);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(7);

    delayMicroseconds(16);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase2neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(16);

    delayMicroseconds(28);
    digitalWrite(Phase1neg, HIGH);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(180);
    delayMicroseconds(180);
    digitalWrite(Phase3pos, LOW);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(28);

    delayMicroseconds(16);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(16);

    delayMicroseconds(7);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(7);

    delayMicroseconds(2);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(2);

    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(104);
    digitalWrite(Phase2pos, HIGH);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(208);
    digitalWrite(Phase3pos, LOW);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(104);
    digitalWrite(Phase1neg, LOW);

    delayMicroseconds(2);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(80);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(47);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(159);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(47);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(80);
    digitalWrite(Phase2neg, LOW);
    delayMicroseconds(2);

    delayMicroseconds(7);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(93);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(108);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(93);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(54);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(7);

    delayMicroseconds(16);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase3pos, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3pos, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(16);

    delayMicroseconds(28);
    digitalWrite(Phase1neg, HIGH);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(180);
    delayMicroseconds(180);
    digitalWrite(Phase2pos, LOW);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(28);

    delayMicroseconds(16);
    digitalWrite(Phase2pos, HIGH);
    delayMicroseconds(27);
    digitalWrite(Phase1neg, HIGH);
    delayMicroseconds(138);
    digitalWrite(Phase3neg, HIGH);
    delayMicroseconds(54);
    digitalWrite(Phase3neg, LOW);
    delayMicroseconds(138);
    digitalWrite(Phase1neg, LOW);
    delayMicroseconds(27);
    digitalWrite(Phase2pos, LOW);
    delayMicroseconds(16);
}

Welcome to Arduino SE. It would be helpful if you could post the error messages that you're getting.

Hi, thanks!  In function 'void loop()':
99: error: too few arguments to function 'void digitalWrite(uint8_t, uint8_t)'
109: error: at this point in file

I've found the one at line 109 but the one at 99 I can't seem to see

I copy/pasted it, fixed 109, it compiled...

Here's line 109:
 digitalWrite(16);

As the error message says, there aren't enough arguments. It looks like you meant to call delayMicroseconds() there instead of digitalWrite().


text:
while compare, something is wrong
I have 5 LDR and Arduino Mega. I connect them and get light level.
void loop() {
// print the analog output in milli volts
int w=analogRead(west);
Serial.print("west = ");

Serial.print(w);
Serial.println(" mv");

int e=analogRead(east);
Serial.print("east = ");

Serial.print(e);
Serial.println(" mv");

int n=analogRead(north);
Serial.print("north = ");

Serial.print(n);
Serial.println(" mv");

int s=analogRead(south);
Serial.print("south = ");

Serial.print(s);
Serial.println(" mv");

int c=analogRead(control);
Serial.print("control = ");

Serial.print(c);
Serial.println(" mv");

delay(1000);

if(e > w)
Serial.println("west");

else if(e < w)
Serial.println("east");

else if(s > n)
Serial.println("south");

else(s < n);
Serial.println("north");

Serial.println("\n");
}

This is my loop and I always see east-north. When west is bigger than east I also see east. What

What indeed @user3748265, what indeed.

It would help to post (under your code) what you see in the serial prints.

You should write out in plain English/language what you want to happen and then translate that to code. Your current program doesn't seem to follow any logic and it's hard for us to know your intentions. For example, your first if statement says if E is greater than W then print *west* - that's why you see "west" when E is bigger, but you are saying you don't want that.

Nick Gammon correctly points out a problem due to an extra semicolon, but you should also note what the construct else(s < n) is doing.  When the if condition that this else gives an alternative to is false, the statement   (s < n) gets executed.  That statement is an expression statement, and its value is the evaluation of s<n, either true or false.
If the semicolon after (s < n) weren't there, you'd get a compile error because (s < n) serial.println("north") is not a valid statement.  You may have meant to say else if(s < n) instead of else(s < n).
Note, in the sequence
if (e > w)
   Serial.println("west");
else if (e < w)
   Serial.println("east");
else if (s > n)
   ...

that last else typically is reached only rarely, because the only condition to get to it is e and w being equal.  Due to sensor noise and signal processing noise, the chance of e and w being equal is probably at most a few percent.
If your north/south test sequence is supposed to be independent of your east/west test sequence, leave out the second if and second else .  That is, instead say:
if (e > w)
   Serial.println("west");
else
   Serial.println("east");
if (s > n)
   ...

There is another issue I didn't want to comment on. E and W are read from different sensors, so you might conceivably have E == 1023 and W == 1023 which doesn't make a lot of sense. That's why I asked to see the actual serial output.

@NickGammon, I think user3748265 hasn't given enough info for us to say if equal values do or don't make sense.  In a suntracker, for instance, equal values are desired.   (If you're spotlighting maxed-out sensor values, I agree that's usually a problem.)

I won't contradict you. :)

Here:
else(s < n);
-----------^

That is wrong. See Arduino programming traps, tips and style guide.

Trap #13: Don't put a semicolon at the end of every line
Semicolons end statements. However if, for and while are compound statements, so they should not have a semicolon after them like this:
Wrong! ...
  if (temperature > 40);    // <----- this semicolon is incorrect!
    {
    digitalWrite (furnaceControl, LOW);
    digitalWrite (warningLight, HIGH);
    }

  for (int i = 0; i < 10; i++);   // <----- this semicolon is incorrect!
    digitalWrite (i, HIGH);

The semicolons above (as indicated) terminate the if and for so they don't do anything useful. The lines following them are just unconditional blocks of code which are always executed, once.
Correct:
  if (temperature > 40)
    {
    digitalWrite (furnaceControl, LOW);
    digitalWrite (warningLight, HIGH);
    }

  for (int i = 0; i < 10; i++)
    digitalWrite (i, HIGH);


text:
How to convert a String number Into a int value?
I want to convert a string into a int value. in my real code, I receive a string "Slider 255" the number after slider changes from 0 to 255, so I want a int value to be equal to that number. This is a small example of the code:
#include <Servo.h>
Servo myServo;

int val = 0;
String s = "";
void setup() {

  Serial.begin(9600);
  myServo.attach(9);
}

void loop() {
  while(BT.available() >0){
  s =  Serial.read(); // which wiil be a number between 0 and 255
  // So I want val to be = to ehatever the string is. So far I have try this but it doesn´t work.
  // first attempt # 1
  val = s:
  myServo.write(val);

  // Second attempt # 2
  Serial.println(s)
  val = Serial.read();
   myServo.write(val);
  }
}

The easiest way is to use the parseInt method available to Serial like this
int val = Serial.parseInt()

But, you will have to be sure that the non-number part of the message ("Slider") has already been dealt with.
You could also put the data into an arduino String Object and use it's toInt method, or put it in a C style string and use the atoi method.