text:
'Servo_Pointer' was not declared in this scope
I can't seem to find the error I made; can anyone help me?
The error message: 'Servo_Pointer' was not declared in this scope
I get the error at the end of the code with the line: Servo_Pointer.write(servo_pos)
The code:
const int photo_left = A0;    // select the input pins for the photoresistor
const int photo_right = A1;
const int ledPin_1 = 2; // These leds will be used for the testing of the pointing of the servo motor
const int ledPin_2 = 4;
const int ledPin_3 = 7;
const int ledPin_4 = 8;
const int ledPin_5 = 12;
const int photoValue = 0;  // variable to store the value coming from the photoresistor
const int numReadings = 10;
int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(ledPin_1, OUTPUT);
  pinMode(ledPin_2, OUTPUT);
  pinMode(ledPin_3, OUTPUT);
  pinMode(ledPin_4, OUTPUT);
  pinMode(ledPin_5, OUTPUT);
  Serial.begin(9600);
  #include <Servo.h>
  Servo Servo_Pointer;
  Servo_Pointer.attach(9);
  int servo_pos = 0;
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading  ) {
    readings[thisReading] = 0;
  }
}

void loop() {
  Servo_Pointer.write(servo_pos); // tell servomotor to go to position in variable 'servo_pos'
  delay(15);          // waits 15ms for the servo to reach the position
  // turn the ledPin on
  delay(15);
}

Please don't make more work for other people by vandalizing your posts. By posting on the Stack Exchange (SE) network, you've granted a non-revocable right, under the CC BY-SA 4.0 license for SE to distribute that content. By SE policy, any vandalism will be reverted. If you want to know more about deleting a post, consider taking a look at: How does deleting work?

You should make Servo Servo_Pointer; global, i.e. place it outside the setupfunction, e.g. after the line int average = 0;.
In your code, it is a local variable within the setup function. When this function ends, the local variables within this function (such as Servo_Pointer ) do not exist anymore.
By making the variable global, you can use it anywhere. However, it's not a good coding practice to use global variables when not needed.
A benefit of making the variable global is that you can see the memory consumption of the instance of Servo_Pointer when compiling.
Also see the comment of timemage below: Don't put #include statements in the middle of your code, put them in the beginning of your code.

Might be worth adding that it's at least unconventional to have an #include directive in the middle of your function.

@timemage Good catch, I did a search on Servo_Pointer missing that line.

You need to place the decleration outside of your setup() function. In other words, you need to move the following 3 lines and place then above your setup() function:
#include <Servo.h>
Servo Servo_Pointer;
int servo_pos = 0;

Your code should look like this:
#include <Servo.h>

const int photo_left = A0;    // select the input pins for the photoresistor
const int photo_right = A1;
const int ledPin_1 = 2; // These leds will be used for the testing of the pointing of the servo motor
const int ledPin_2 = 4;
const int ledPin_3 = 7;
const int ledPin_4 = 8;
const int ledPin_5 = 12;
const int photoValue = 0;  // variable to store the value coming from the photoresistor
const int numReadings = 10;
int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average
int servo_pos = 0;

Servo Servo_Pointer;

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(ledPin_1, OUTPUT);
  pinMode(ledPin_2, OUTPUT);
  pinMode(ledPin_3, OUTPUT);
  pinMode(ledPin_4, OUTPUT);
  pinMode(ledPin_5, OUTPUT);
  Serial.begin(9600);
  Servo_Pointer.attach(9);
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading  ) {
    readings[thisReading] = 0;
  }
}

void loop() {
  Servo_Pointer.write(servo_pos); // tell servomotor to go to position in variable 'servo_pos'
  delay(15);          // waits 15ms for the servo to reach the position
  // turn the ledPin on
  delay(15);
}


text:
Why is Arduino resetting while driving motors?
I am driving motors for my line-follower project . The circuit schematic is given below
The power source is a 11.1V 2200mAh 25C Lipo . Practically the cells give 11.5-12V. I used a switching buck regulator to step down the voltage. However , when i run my robot on track after few seconds,the arduino tends to reset and run again. This problem typically arises when i drive the motors at higher PWM(above 180 on analogWrite function). Since i use PID, limiting the PWM means i have to drive at lower speeds which i do not want.
I am providing links for the items i used for my circuit:

buck converter;
motor driver;
IR sensor module;
DC motors.

The sensor array draws 150mA at peak. Any suggestions as to where the problem might lie would be of great help. Thank you .
EDIT 1: Changed the input voltage Vin to 7.9V through the buck converter .
        The problem still persists .

The buck converter is producing 5.5 V?  That may be too low for the VIN input on Arduino, where the voltage regulator needs at least 7 V and is therefore causing brown-out.

The VIN pin goes to a 5V voltage regulator on the Arduino and needs at least about 7V minimum to work properly.  If you want to supply 5V to an Arduino do it either on the 5V pin or via the USB connector.  The VIN pin should receive 7V to 12V.

This is the correct answer. VIN a high enough voltage to be regulated down to 5V. I suggest feeding 5V into your USB connector. That way you don't bypass the source switching and protection circuitry on the Arduino.

@DuncanC Doesn't the USB connector also have a regulator, or does it expect that the USB can consistently provide 5V?

@MindS1, read https://store.arduino.cc/mega-2560-r3

No, USB provides regulated 5V, and is fed through some logic and current limiting circuits to the +5V rail. The Arduino uses a linear regulator, which needs a couple of volts more than it's target voltage. (IT works by applying a variable resistance to the input, converting the excess voltage to heat. )

You might get away with feeding 5V into the VIN if you draw VERY low current from it, and if there is no voltage sag, but it's not recommended.

I changed the Vin to near 7V , but the resetting problem still persists . Yes , now it happens less frequently , but when the motor starts moving at full/high speed(PWM>210) after breaking , the mega resets .

It is likely your motors are drawing too much current from the battery when running at high speed.  What is the max continuous current rating for the battery?  How much current are the motors using at high speed?

@JeffWahaus , my motors draw 2-2.5A each when stalled running at full speed. Power source is 11.1V 2200mAh 25C 3cell Lipo battery.

Resetting is due either to a software bug or voltage sag, and since it correlates with driving the motors harder, it's almost certainly the latter. You probably suspected as much since you mentioned the current draw of the sensor array. A quick experiment - disconnecting the sensors (and possibly a software patch to keep the robot running straight, without them) might help you discover the reason.
Each chip and each of its pin drivers has a current budget. It would be a good idea to look at the max current spec of the Atmega2560 and its pin drivers, and any other current specs mentioned in the datasheet, and make sure you're not trying to run it out of spec. The buck converter will have a limit, too, so make sure you're within its spec. If the output regulation of the buck converter is good enough, you can regulate it to 5v and bypass the Mega's on board regulator, for another saving.

One major drawback to working with motors is the large amounts of electrical noise they produce. This noise can interfere with your sensors and can even impair your microcontroller by causing voltage dips on your regulated power line. Large enough voltage dips can corrupt the data in microcontroller registers or cause the microcontroller to reset. You can avoid this problem by soldering capacitors along your motor terminals. Use 1µF ceramic capacitors for example

Why the down-vote? Everything in this answer is good advice. Motors introduce a lot of noise on the power input. Adding filter capacitors is a very good idea. (That said, the biggest problem is likely too low an input voltage to VIN)

I've experienced this myself too.  Also vibration causing wires to become loose.

This might be a good idea . I noticed the voltage up/down surge problems on start-up initially or after breaking . On which type of motors do you use these capacitors ? Do they affect the motor performance ?

@user9999114 On brush motors mostly. They don't have an affect (that I one could notice) on the motor perfomance

This is the common issue when trying to connect power and digital circuits together. Probably, when motor starts, there is a short-time voltage drop in Vin due to high motor start current. Consider to use Schottky diode and capacitor to protect digital power circuit from transitional currents.

You should either feed the 5.5v from the buck converter to the 5v pin of the arduino, or the 11.5v to the Vin.
The arduino board contains its own 5v converter (and a 3.3v but that's not in question here). That takes the voltage of the Vin pin and converts it to 5v for the board to use. This regulated 5 v is available on the 5v pin for your sensors for example.
You can also power it directly on the 5v pin, but that requires regulated 5v. This is also how it is powered through USB which supplied regulated 5 v.
The 5.5 v from your buck should be fine for this, by you don't need it. Put the "raw" 11.5 to the Vin pin.

source: Stack Exchange

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

sort: votes


text:
Create a device to detect object and voice alert what kind of object it is
Here is what I want to do (since I'm not a embedded guy)

create a prototype with an Arduino to detect objects using camera(object classification?)
that prototype will detect objects and alert that object's name

My questions are....

Is it possible? :)
What things should I use to create a prototype?
What camera should I use?
Is it related to image processing?
Connection between object detection and voice alert?

I don't think arduino is sufficient for this. Maybe with camera which can detects objects itself and voice recognition module.

The Arduino is not the ideal platform for you since it is more "lightweight" and can't really meet the demand that your application is expecting.
A platform like for example Raspberry Pi that has a full-blown operating system and a lot of tools that fulfils your application needs.

Thank you so much sir!!

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


text:
Need help with DAC to show more than one output with SPI (stuck and need help please)
I want to take 2 different outputs from my DAC from void setDacOutput function (and it should be switching with/like the timer for both outputs. One output of 2.9375V for 0.9ms from ISR if statement and other of 2.5V for 1.6ms from else statememt) but my DAC only gives one output (in ISR - interrupt service routine only one of the if statement dacfunction or the else statement's (when if statement is commented) runs, not both). I want the DAC to give value for both if and else statement in ISR. For the given code it is only giving 2.9375Volts (called in isr-if statement). Not giving 2.5V (called in isr-else statement).
My timer is giving correct output when I connect oscilloscope to Pin9 and gnd (0.9ms on and 1.6ms off).I am using TLV5616 DAC from TI. And I’ve tried to print something in both if and else of ISR and they work but Dacfunction runs only once giving only one output. Maybe something wrong with SPI. Any help will be extremely appreciated please.
This is my code:
// TLV5616 DAC communication using SPI
#include <SPI.h>

/*  TI TLV5616CP (2.7 to 5.5V) LP 12-Bit Digital to Analog Converter
For sensor details see: http://www.ti.com/lit/ds/sbas415c/sbas415c.pdf

Circuit:
TLV attached to Uno pins as follows:
TLV Pin         Uno Pin
1 (DIN)         11 (MOSI - Output)
2 (SCLK)        13 (SCK - Output)
3 (/CS)          8 (Chip selec8t - Output)
4 (FS)          10 (SS - Output)

Note: TLV5616 has no provision for MISO pin 12, output is in volts

// Pin 8 = /CS, Pin 10 = SS
const int chipSelect = 8;
const int slaveSelect = 10;

// Variables for TLV5616 Testing
const unsigned int control = 0x4000;
const unsigned int msbMask = 0xFF00;
const unsigned int lsbMask = 0x00FF;
unsigned int command, data;
byte commandMsb, commandLsb;

//Variables for timers setting
uint16_t timerOneVal[] = {14400, 25600};
uint8_t timerTwoVal[] = {90, 160};
bool timerOneItr = 0;
bool timerTwoItr = 0;

void setup(void)
{
  Serial.begin(9600);
  /* To "condition" the hardware we begin with the call: SPI.begin()
  which configures the SPI pins (SCK, MOSI, SS) as outputs. It sets
  SCK and MOSI low and SS high. It then enables SPI mode with the
  hardware in master mode which has a side effect of setting MISO as
  an input.

  The SPI.transfer call does the actual transfer of bytes. I must
  set /CS and SS at the appropriate time */

  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV2);       // Freq SPI_CLK = 8MHz
  SPI.setDataMode(SPI_MODE1);                // CPOL = 0, CPHA = 1
  pinMode(chipSelect, OUTPUT);
  pinMode(slaveSelect, OUTPUT);

  pinMode(9, OUTPUT);

  digitalWrite(9, LOW);

  setTimers();

}

void setTimers()
{
  cli();

  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;
  OCR1A = 0xFFFF;                   // set compare match register first time to full value (change values later on in the Interrupt service routine - ISR)
  TCCR1A = 0x40;                    // toggle OC1A on compare
  TCCR1B = 0x09;                    // Set CS10 and WGM12 bits for no prescaling and turning on CTC mode
  TIMSK1 = 0x02;                    // enable timer compare interrupt

  sei();

}

void setDacOutput(unsigned int dacValue)
{
    digitalWrite(chipSelect, LOW);             // Enable TLV5616 /CS
    digitalWrite(slaveSelect, LOW);            // Enable TLV5616 FS

    /* The TLV5616 control bits are D14 and D13, D15 and D12 is don't care. The data
    to be written to the TLV5616 is in Bits D11 to D0. commandMsb is the (8-bit) MSB
    and commandLsb is the (8-bit) LSB of the 16-bit TLV5616 control word */

    command = control | dacValue;
    commandMsb = (command & msbMask) >> 8;
    commandLsb = command & lsbMask;
    SPI.transfer(commandMsb);
    SPI.transfer(commandLsb);
    delayMicroseconds(1);
    digitalWrite(slaveSelect, HIGH);            // Disable TLV5616 FS
    digitalWrite(chipSelect, HIGH);             // Disable TLV5616 /CS
//    SPI.end();
}

ISR(TIMER1_COMPA_vect)
{

  OCR1A = timerOneVal[timerOneItr];

  if(!timerOneItr){
    setDacOutput(0x0966);     // 2406/0x0966 for 2.9375V; 2045/0x0800 for 2.500V;
    timerOneItr = !timerOneItr;
  }
  else{
    setDacOutput(0x0800);
    timerOneItr = !timerOneItr;
  }

}

Majenko I accidentally deleted your answer. Can you kindly post again please?

Majenko Sir, I accidentally deleted your answer before even being able to read. Can you please post it again kindly?

you are mistaken about the answer from @Majenko .... you cannot delete someone's answer ... the answer would still be here

Perhaps Majenko removed the answer because it was not right? to be honest, you're asking about Dacfunction running once, but since there's no function called Dacfunction or even just Dac only you could possibly guess what you are referring to

@MuhammadUzairArif I did not write an answer. I edited your question to place your code in a code block. That is all.

The function name is void setDacOutput @JaromandaX


text:
Is Ticker.h really safe to use?
I have this code
#include <Ticker.h>  //Ticker Library
Ticker blinker;
/* ... */

//blinker.attach(1, []() { digitalWrite(LED,!digitalRead(LED)); }
while(!client.connect(laptop,port)) {
   Serial.println("Connecting...");
   delay(1000);
}

Which works fine, tries connecting, then eventually connects.
If I uncomment the line attaching to this 'blinker' Ticker, then I get a crash right after the first 'Connecting...' print. When I look at the stack trace, it mentions that the crash happens during the delay(1000) in my while loop (which is presumably the moment when the program yields and the blinker can do some work)
Is there anything I can do to make this timer work better?

What library is the blinker object from? Where does the Timer.h, from the title` come into play?

I was confused - I meant Ticker.h - I updated the code to make it more apparent - apologies for that

What's the boot message after the crash? You'll have to set the terminal speed to 74400 to see it. It'll look something like ets Jan  8 2013,rst cause:2, boot mode:(3,6) - the rst cause: number is the most important thing.

Couldn't get the rst cause thing for some reason...

Update: the original question mentioned timers, so this answer is for a hardware timer interrupt handler. It doesn't apply to Ticker, which is what the question is now about.
The callback that you attach to blinker will be called as an interrupt handler, so it's important to make sure it's already loaded into executable instruction memory (iRAM) on the ESP8266. When you pass anonymous function inline to blinker.attach() it won't tagged to be stored in iRAM.
Try this instead:
void ICACHE_RAM_ATTR blinker_handler(){
    digitalWrite(LED,!(digitalRead(LED)));  //Toggle LED Pin
}

...

blinker.attach(1, blinker_handler);

ICACHE_RAM_ATTR tells the system to keep the code in the instruction RAM. There's not a lot of iRAM (32Kbytes) so you don't want to do this too often, but it's important for interrupt handlers (another reason to keep them short and sweet).

oh that's very useful, thanks. I've used Tickers in other cases, and it seemed to work fine even though I was attaching callbacks to them instead of IRAM (which I had no idea about). I will try your suggestion.

What's the purpose of timer1_write(600000); please?

@MarkSmith I believe that was in the original example before it was updated.

@joelhoro with the update - now that we're talking about Ticker, not a timer - I don't think this is the right answer. I thought you were talking about a hardware timer's interrupt handler - this would be correct for that. But I'm sure Ticker's callback doesn't run as an interrupt handler. I'll edit the answer to point that out but I think there's going to be a different solution.


text:
client.connect() failing unless I ping my ESP
[EDIT] it seems like this has to do with my laptop's firewall settings rather than anything wrong with the ESP8266 [/EDIT]
I have a webserver on my laptop. When I do this on my ESP8266 (after the wifi has been connected)
while(!client.connect(laptop,port)) {
   Serial.println("Connecting...");
   delay(1000);
}

It loops forever. However, if I manually ping my ESP from my laptop, I initially get this
Pinging 192.168.1.7 with 32 bytes of data:
Request timed out.
Reply from 192.168.1.7: bytes=32 time=4ms TTL=255

And as soon as this happens, the ESP gets connected to the laptop, and all works fine.
So it seems to me like the client.connect is preventing the ESP from even registering to the network, and the pinging is somehow waking it up.

what if you ping something else instead?

tried that - it doesn't do anything

oh wait, you're right - if I ping something else, even an IP that does not exist, the ESP suddenly connects. OK this means there's something dodgy going on on my computer. Going to check if this happens with another device.

Just tried running the server from a raspberry PI, the ESP connects without trouble. There must be some firewall thing or something going on my laptop. Will check and revert

could not find the source of the issue - firewall is definitely off. I should try to get hold of another laptop (as opposed to PI) to check

Hmm, have you tried using a port above 1024? I once had trouble with that, but it's just an idea...

oh yeah that's one of the first thing I thought about, but I was already using 3000. I tried 8000, just in case that would help - no diff. And I should mention that when I ran the script on my PI, I had to do sudo otherwise it would not work.


text:
Does a delay in a loop save energy?
I've noticed most example snippets always have a delay in the loop even if it's not needed for proper execution of the program.
I can only assume this is added because people copy and paste without understanding what's going on but it got me thinking if adding a delay could possible save power too.
If I have a loop that checks some inputs for changes could it be possible that adding a delay(10) saves some cycles and thus power?

No. Even a delay "uses" cycles.

@MarkLakata Multithreaded? In Arduino? 99.99% of the time there is no real scheduler, and in any case in the other 0.01% of cases the delay function does not "free" the calling thread (the delay implementation is just like a for loop doing nothing)

No, it burns energy by doing nothing.
You definitively should send your MCU to sleep and wake up on events or use the watchdog timer to wake up after a predefined period of time.

The delay function doesn't do anything special. It basically just counts down milliseconds inside a while loop and times it with micros().
void delay(unsigned long ms)
{
    uint32_t start = micros();

    while (ms > 0) {
        yield();
        while ( ms > 0 && (micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

Calling yield() is somewhat special, but yeah it's still a busy wait that spends most of the time running instructions.

@PeterCordes Calling yield() is nothing special.  That is just a (weakly defined) function that does nothing. It's there to allow other libraries or code to override it and implement some kind of cooperative threads, but the default code doesn't, so it does nothing. It's not like calling yield() in something like VB where it releases the program flow back to the OS...

@Majenko: Thanks, I assumed that yield implied a multi-tasking OS, not just a stub in case there was multi-tasking.  (And yeah, I was thinking it literally was POSIX sched_yield(2), and that this implied Arduino ran a full OS like Linux.  Hard to keep track of which dev boards (RPi / Arduino / whatever) run what when I don't use any of them myself. >.<)

No, a short delay (up to 100 millis) is usually inserted in a void loop() when you are attached to an external sensor, in order to stabilize the readings. But it has nothing to do with power consumption. As an example, here are lines 49-52 from the example sketch "AnalogInSerialOut":
      // wait 2 milliseconds before the next loop
      // for the analog-to-digital converter to settle
      // after the last reading:
      delay(2);

The answers above are wrong, at least for NodeMCU 0.9 (ESP-12 board) ESP8266 and I also tested with Firebeetle ESP8266 board. Since I have a USB tester I can check that if the loop method is empty, the boards consume about 70mA-80mA but during delay(ms) they consume about 20mA-30mA.
This is the delay function for the boards commented:
void __delay(unsigned long ms) {
    if(ms) {
        os_timer_setfn(&delay_timer, (os_timer_func_t*) &delay_end, 0);
        os_timer_arm(&delay_timer, ms, ONCE);
    } else {
        esp_schedule();
    }
    esp_yield();
    if(ms) {
        os_timer_disarm(&delay_timer);
    }
}

I have not investigate further why delay function saves so much power consumption.

could it be possible that adding a delay(10) saves some cycles and thus power?

No, the delay() function just pauses the code for the time specified. It's stil running and consuming energy for counting the time and waiting it to finish.
If you need to conserve power, you could adjust your circuit components in a fashion that will save energy, or if you want to save energy on your Arduino, you could use a breadboard setup(Instructions here and here) or make use of the internal watchdog timer to sleep and wake at certain time intervals. More tutorial about watchdog timer is explained here.
Cheers!

I suspect the answer depends on the kind of Arduino you're using.
The ESP8266 is ARM based, and I believe ARM chips include power management circuits, where subsystems are automatically put in low power state when they are not being used. An ARM-based Arduino will likely use a lot less power while executing a delay than while doing other things.
I don't think AVR chips have any sort of power management, so they have all their silicon "lit up" at all times. That said, CMOS logic circuits do use more power when switching states than when idle, so even an AVR-based Arduino will probably use slightly less power while in a delay() function that it will when it's running instructions that use the arithmetic unit, UARTs, and other subsystems of the chip.
You'll get much better power savings by putting your Arduino into sleep mode.

On AVR delay() uses the ALU.

Yeah, I guess it would use the ALU to see if enough time had passed. I meant that more as an example of the different subsystems of the chip than an accurate list, but point taken.

As stated in previous answers, at least on the AVR version of the
Arduino core, delay() is a busy wait that keeps the CPU running. In
his answer, Duncan C correctly states that “CMOS logic circuits do use
more power when switching states than when idle”. It is then expected
that instructions that switch a large number of gates or flip-flops
consume more power than instructions that only switch a few ones.
Out of curiosity, I disassembled a call to delay() to see what kind of
instructions it executes. I found that the “hot path” is a loop that
executes 44 instructions per iteration:

23 of them do arithmetic or logic (add, subtract, compare, XOR)
13 move data around (register load, register copy, I/O, read RAM)
7 alter the program flow (function call, return, jump, conditional
branches, conditional skip)
1 alters a bit in a status register

I do not know how this compares with “typical” code, but the large
proportion of instructions that do arithmetic and logic computations
suggests that delay() should be way more energy hungry than, say, a
long sequence of nop instructions. In the end, the only way to
know for sure whether delay() changes anything to the power
consumption of a specific program would be to measure it.
As a side note, an easy way to save some power on AVR boards is to
#include <avr/sleep.h> and insert a call to sleep_mode() at the end
of loop(). The sleep with not last for long though, as the Arduino
core sets Timer 0 to interrupt the CPU every 1024 µs.

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


text:
Arduino Pro Micro Analog Pinouts
I have the Arduino Pro Micro and I would like to use all the analog pins that I can on it.
It currently looks like it has a total of 9 Analog pins that can be used.

A0, A1, A2, A3, A6, A7, A8, A9 and A10.
However, I am unsure how to call these pins since all of those are also digital pins.
Would A0-A3 be defined as:
#define analog1 A0;
#define analog2 A1;
#define analog3 A2;
#define analog4 A3;

While the other pins would be this?:
#define analog5 4;
#define analog6 6;
#define analog7 8;
#define analog8 9;
#define analog9 10;

Then just call:
analogRead(analog1);
analogRead(analog2);
.....
analogRead(analog8);
analogRead(analog10);

Would that be the correct way of defining the 9 analog pins?

Assuming you have the Pro Micro core, they are called A0, A1, A2, A3, A6, A7, A8, A9 and A10. There is no need to "special case" the others, since the pins are known as both.

So you're saying its = A0, = A1, = A2, etc... or are you saying its just = 0, = 1, = 2, etc?

Analog pins in the Arduino libraries are prefixed with "A".

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


text:
Unable to connect Ethernet shield W5100 to localhost
I have an Arduino Uno and a W5100 Ethernet Shield. I am trying to post some data from the Arduino board to the WAMP server running on my computer. I do not have a router so I have directly connected my Ethernet shield stacked onto the Arduino Uno to the laptop's Ethernet port via an Ethernet cable. I have also assigned the Ethernet connection a static IP address 192.168.0.1 and my localhost page opens when I put this address in my browser.
In my Arduino sketch I have assigned the Arduino shield an IP address 192.168.0.4, i.e. on the same IP segment. When I try to do client.connect to the server (192.168.0.1), i.e. localhost, I get "Connection failed".
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0x6F, 0xED };
IPAddress ip(192,168,0,4);
byte server[]={192,168,0,1};

int value=9;
EthernetClient client;

void setup() {
  // Serial.begin starts the serial connection between computer and Arduino
  Serial.begin(9600);
  // start the Ethernet connection
  Ethernet.begin(mac,ip);
}

void loop() {
  // Connect to the server (your computer or web page)
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");
    client.print("GET /Ethernet/getData.php?"); // This
    client.print("value="); // This
    client.print(value); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.println(" HTTP/1.1"); // Part of the GET request
    client.println("Host: 192.168.0.1");
    client.println("Connection: close");
    client.println(); // Empty line
    client.println(); // Empty line
    client.stop();    // Closing connection to server
  }

  else {
    // If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }
  delay(10000);
}

Now when I upload the sketch onto the board and run the serial monitor, I get this output:

My Ethernet connection detail screenshot is as follows:

Please tell me any changes that I must make and also are there any WAMP settings which I should change to allow the connection to get established?
Please consider the fact that I don't have a router anywhere in this connection - just my laptop and Ethernet shield connection.

What state are the LEDs in on the ethernet board? Do they show a proper ethernet connection has been negotiated? If neither end is able to auto-negotiate uplink mode you may well need a special cross-over cable.

Are you running a firewall?
Have you checked if your server is actually listening on that interface?

@Majenko all the LEDs i.e. the full duplex ,LINK, 100M,COLL are blinking.

@IOBToolkitTeam yes my mcAfee runs a firewall. How to check if my server is listening on that interface. when i enter 192.168.0.1 in browser i am able to view the WAMP server page. if that's what you mean

With everything flashing like that it does sound like a cable problem. Most likely you need a cross-over cable. That's one where at one end of the cable the orange and green wires are swapped with each other.

@Majenko Is everything else fine.?? I mean my IP assignment and the code?

If you're running firewall, it probably blocks your Arduino. Since I'm not using windows since 1999, I can't help you with that. :)

@IOB Toolkit Team I tried turning off my firewall and then running the code again but without any success

@Majenko the LINK, FULLD, 100M,COLL LEDs are constant, they are not blinking, but yes in High state.  The TX and Rx LED blink occasionally and with that the LINK LED also flickers

Your program is fine. I have just run it and see GET requests on my Apache server: 192.168.1.4 - - [26/Jan/2016:21:34:50 +0000] "GET /Ethernet/getData.php?value=9 HTTP/1.1" 404 475 "-" "-" so it is either your cable or your PC.

@Majenko, I will try with a cross over Cable then

After uploading the sketch from your laptop you should disconnect your Arduino and Ethernet shield setup from your laptop and then use a switch.
Connect the same setup to the switch at one end and the other end of the switch must be connected to your laptop then you can try to access your web page using IP address you specified in Ethernet sketch.

Welcome to Arduino SE! As we here try to keep the quality of answers and questions high could you please fix any grammatical or spelling errors in your answer?

Well, the problem has been solved. The Ethernet shield was not properly stacked onto the Arduino board which caused connection to fail.

Could you edit and expand your answer on how it was not properly stacked...? Were some of the pins bent, or badly soldered, or was the shield just not seated correctly? Also, could you mark your answer as the accepted answer, in order to remove it from the Unanswered Questions list? Thx.


text:
Interrupt triggering using DHT-11
I am new at arduino.
I want to write a sketch that would print the message if the temperature grows greater than 30 C.
Here is my sketch can you please tell me what's wrong with it
#include "DHT.h"
#define DHTTYPE DHT11
#define dht_dpin D3

DHT dht(dht_dpin, DHTTYPE);

void setup()
{
 Serial.begin(9600);
 }
void loop()
{
 float t = dht.readTemperature();
 Serial.print("temp=");
 Serial.println(t);
 attachInterrupt(dht_dpin, IntCallback, CHANGE);
}
void IntCallback()
{
  float t = dht.readTemperature();
  if(t>30)
  {
    Serial.print("Alert");
  }
}

remove lines starting from the line with attachIterrupt until the line before if (t > 30)

You can't use an interrupt the way you are attempting to. Attaching an interrupt to a pin like that will cause the interrupt to trigger any time the digital pin's value changes. The DHT11 uses serial communication to send temp values to the Arduino. Serial communication uses lots and lots of on/off pulses on the signal line to send characters of data. Your interrupt will fire every time the DHT11 toggles the signal line.
You need to read the temp from the DHT11 in your loop, and then add an if statement that does what you want when the temp exceeds your threshold. (It looks like you just need to get rid of the attachInterrupt() call, and instead call IntCallback() every couple of seconds.

Hi.Thanks for helping but i am a noob in this. I don't know much about Interrupt and callback. So if you don't mind can you please modify the sketch for me. That would a great help.

You don't even need an interrupt.Modification:
#include "DHT.h"
#define DHTTYPE DHT11
#define dht_dpin D3

DHT dht(dht_dpin, DHTTYPE);

void setup()
{
 Serial.begin(9600);
 }
void loop()
{
 float t = dht.readTemperature();
 Serial.print("temp=");
 if(t>30)
  {
    Serial.print("Alert");
  }
}

Let me explain my whole situation. My project is to make a gps tracking system plus using dht11 to give an alert through GSM if the temperature grows above 30 C. But the problem is after 1st or 2nd output, the dht11 is not giving any reading it shows "Nan" in serial monitor. It taking 28 to 30 seconds to give another reading. So I thought may be using Interrupt will work. Any suggestions for this??

try using other library for DHT11 then.


text:
Blink doesn't work on pin D3,D4 and D0 but works on D7
I am facing a strange issue. I am trying to blink an external LED using Wemos D1 mini V2 board. But it is not working. My sketch is as below.
int LED = D3;
void setup()
{
  pinMode(LED, OUTPUT);
}
void loop() {
  digitalWrite(LED, LOW);   // LED off
  delay(1000);              // Wait 1 second
  digitalWrite(LED, HIGH);  // LED on
  delay(1000);              // Wait 1 second
}

The same problem happens on D0, D3, and D4 pins. I am getting 0 volts constantly on pin D0 and 3.3v constantly on pins D3 and D4.
However, The same sketch works for the D7 pin.
Does anyone know how to fix this?

This code should just work. If you're setting LED to D4 it should blink the internal LED. What happens if you do that? How are you measuring the voltage? Also, please make a habit of properly indenting your code, even with such a small program.

Make sure all your SW and FW is up to date.  Trying to get so many different processor to work like the original Atmel processor on the original Arduino UNO is no easy task.  Even the well known Adafruit.com got the this wrong in the beginning.


text:
My computer dose not recognise my Arduino Uno
I had never used Arduino before. When I tried to interface my new Arduino Uno board to my computer, the computer failed to recognize the board.
Why isn't the board interfaced successfully? How should I troubleshoot that problem?

Did you install the drivers? Is it a genuine Arduino? Are you using a fully wired USB cable?

Majenko is probably right.  If it is a clone Arduino board you will need to install some CH340 drivers.  If it's an authentic board I would return it as it should work out of the box with the Arduino IDE.

Also if you are on a Windows PC be careful because FTDI drivers have been known to kill these boards.  I've also encountered something with Windows 10 when the updated driver causes the CH340 to quit responding.  If you have access to a machine running Ubuntu these drivers come preloaded and work out of the box.


text:
What are the other IDEs for Arduino?
The basic Arduino IDE lacks a lot of the sophistication present in other IDEs such as code completion, code collapsing, folder organisation, etc. Are there other IDEs that allow programming in C or C++ and improve on these aspects?

Suggestion: Can this question be extended for different languages (not just different IDEs)?

What do you mean @anorton

@anorton That would make for a different question entirely.

anorton probably meant that one could be interested in knowing also what programming languages, other than C++, can be used to program an Arduino. Right, @anorton?

@Ricardo That is correct.   But, I agree that this question should be kept strictly different IDEs.  :)

@anorton I agree. The language one is a separate question.

The Arduino IDE does include code-folding. It is not enabled by default though. Edit "preferences.txt" at the line: editor.code_folding=false and make it true. That's not meant to detract from the question though.

There is an Arduino Eclipse plugin named sloeber! And Eclipse is an awesome cross-platform open-source IDE!
Stino is good. It requires Sublime Text 2 which has an indefinite free trial.
Visual Micro provides a full build system with debugger for Arduino in Microsoft Visual Studio. For advanced users it also allows the underlying Arduino source code to be viewed or modified, enabled projects and/or libraries to be edited from any location and shared in multiple projects alongside true cross-platform intellisense.
For more go to The Official Arduino Site
For development on Windows, there is a special edition from Arduino official IDE called arduino-erw, This edition much better the last one because it fixed a lot of lagging and stability issues!

And NetBeans too!

@Jean-ChristopheDuperron Thanks! I will definitely use the NetBeans plugin. Thanks Hardik Thaker I don't like using Eclipse but if the NetBeans one fails I will use the Eclipse plugin

How is Stino? I love Sublime and was wondering if Stino is any better than the Arduino IDE (especially in terms on connection and serial overflow errors/crashes).

@FakeName I appreciate your enthusiasm, but you will want to tweak your language down just a tad ;-)

I use the Arduino Eclipse plugin and I'm happy with it. But I'll take a look at the other proposals which I was not aware of!

@ChrisO - Why? I have yet to ever hear a convincing argument for censorship.

@FakeName, Just installed it. Hopefully everything goes well tomorrow while working on some mouse tracking for our robot

@FakeName I'm not going to argue for/against censorship (whatever that is).  StackExchange is about professionalism, but in practical terms, it's the community that decides:  if no one flags your post/comment as offensive, then it's alright as is, eh?

@ChrisO - I think this XKCD adequately sums up my opinion on the topic.

@FakeName Hahaha, brilliant thanks for the link, going to the printer, right now ;-)  Wow, instantaneous workplace morale improvement...

Do Eclipse or Visual Studio have features like method tracing (e.g. CTRL-Click leads to the other unit being called by a users method) and context help for C++? (sorry if that's a real newbie question)

@Hamish_Fernsby, yes, Eclipse does this incredibly well. See my setup documentation here: https://arduino.stackexchange.com/a/75491/7727. It makes navigating the code sooo much easier, enabling one to really dig into the core and libraries.

First link (to Eclipse) goes to a spam website.

Expanding on Fake Name's answer, there is also Visual Micro's Arduino plugin for Atmel Studio (built off Visual Studio). It shares the tools, sources and libraries with the Arduino IDE but provides all the code completion and other features of Visual Studio.
The Visual Micro plugin also works in all versions of Visual Studio. Provides
Arduino usb debugging and an Arduino IDE compatible Board Manager.

AtmelStudio is ponderous and a bit quirky -- as many Microsoft creations -- but powerful and ultimately very useful.  I've completed three projects for the Due and find it very facile.  Recommend the J-Link emulator by Segger.

vim can be used for Arduino development, but it will take some configuration (as is the way of vim). You'll need the syntax file and this plugin that enables you to compile and deploy from vim.
Grant Lucas produced a great write-up on getting your environment situation squared away:

Using Vim for Arduino development
Here's a quick post on setting up Vim for Arduino development instead
  of using the Arduino IDE. If you're a heavy Vim user, it can be a bit
  of a shock to go into a different editor. Thankfully the setup is
  pretty easy to get this all working with Vim. This post is assuming
  you are comfortable with how Vim is setup and ideally already have an
  environment that works for you.
Install the Arduino IDE
Wait. What?!? I hear you say. I know, I know. We're not actually using the Arduino IDE but we need it for some configuration and the
  files it installs. The Vim plugin we'll be using ties into what the
  IDE installs and configures so it's needed. You can download the IDE
  from the Arduino site.
Install vim-arduino plugin
To get the main goodness of compiling, monitoring and deploying to an
  Arduino, grab the latest version of vim-arduino. Install it in
  your .vim folder using what ever method you use to manage your Vim
  plugins. Hint: I'd recommend Pathogen as it makes installing
  as simple as dropping the plugin folder into a bundle folder.
Vim syntax file
Next up is to get the syntax file so we can have nice colour coding
  for .pde and .ino files. Download the latest arduino.vim and
  install it in your Vim syntax folder. To get the syntax to apply to
  the correct file types add the following to your vimrc file
au BufRead,BufNewFile *.pde set filetype=arduino
au BufRead,BufNewFile *.ino set filetype=arduino

Configuring the Arduino IDE
Before trying to compile and deploy with Vim, get it all working with
  the Arduino IDE first as the Vim plugin just calls from the settings
  saved by the IDE. If it's working in the IDE, it should work in Vim.
  Make sure you select the right tty.usbmodem* serial port from Tools >
  Serial Port in the IDE. Note: This will only show when the Arduino
  is plugged in.
Working from Vim
Once you can communicate with your Arduino from the IDE you should be
  fully good to go with Vim. You shouldn't have to open the IDE unless
  you want some example code. Open up your sketch file in Vim and use
  <Leader>ac to compile a sketch, <Leader>ad to compile and then
  deploy to the connected Arduino and <Leader>as to open a new window
  with screen to monitor the serial output from the Arduino.

I was wondering when a Vim post was going to come up considering Emacs was already present ;-)

@Asheesh gotta represent!

I've just discovered that setting the Arduino IDE preference 'use external editor' puts the IDE into a kind of 'listening' mode that detects changes to the file when editing in Vim (or other editor). You have to have file open in both editors.

You can use AVR Studio to write programs for Arduinos.
There is a plugin that lets you link against and use the arduino libraries from within Atmel Studio.
If you've used Microsoft Visual Studio, Atmel Studio is basically a reskin of Visual studio with different compiler backends that target the ATmega series of devices, so you'll feel right at home.

There is a half way solution as well since the Arduino IDE has support for external a editor, then the Arduio IDE just compiles and uploads.

Now you can use whatever IDE/editor you like to edit the code,
and then you switch back to the Arduino IDE to press the compile and upload button when you are done.

One rather good IDE extension is the Arduino Mode for Emacs. It allows using a highly versatile and extensible IDE such as Emacs for writing, compiling and uploading code to the Arduino.
The documentation and instructions can be found here.

UPDATE->  Codebender is being shut down.
There is a brilliant open source, web based IDE called Codebender
It is like Github for Arduino and has a great community working from it with thousands of examples and the dev team are exceptional.
With codebender, you can:

program an existing sketch to your device
clone an existing sketch
modfy it to your needs
share your work with the world
embed code in your website, blog, or tutorials

Cross-platform
Works on Windows, Mac & Linux, Firefox & Chrome
Codebender supports Windows (from Windows XP up to Windows 8.1, yes, even Vista :P), Mac OS X 10.6-10.9, and Linux and works within all major browsers

How does it manage libraries (and libraries versions) that you would get from variuous locations (e.g. on GitHub)? I ask in relation to these questions: http://arduino.stackexchange.com/questions/362/where-can-i-find-a-central-repository-of-all-available-arduino-libraries and http://arduino.stackexchange.com/questions/348/how-to-organize-my-arduino-projects-structure-for-easy-source-control

A note provided by Sean808080: UPDATE->  Codebender is being shut down.

Majenko created and maintains UECIDE. His contributions are pretty epic; I've seen first hand his coding prowess as we worked together to get the Adafruit 1.8" TFT Joystick shield working on the chipKIT platform.

There is one from Brazil called MariaMole: http://dalpix.com/mariamole
According to the author, like the original Arduino environment, the MariaMole facilitates the creation of software for the Arduino. However, while the original Arduino IDE has limitations to make life easier for beginners, MariaMole brings features that more advanced users are accustomed to find in professional IDEs, such as:

Runs over Arduino install
Workspace support multiple projects at the same time
Multiple serial port consoles at the same time
Files use open-formats
Building process configurable
Imports Arduino examples and sketches
Easily import Arduino libraries
Color-themes

Thanks for your answer Daniel. I hope you don't mind though that I removed the image you included of the candy called "Maria Mole". It's not really relevant to the discussion, and it actually made your post look like spam at first glance.

It would be best if some description of the IDE could be added here. At the moment, the answer contains only a link, and if the link were to go down, the answer would become useless.

@AsheeshR, I've put more info as you suggest. Thank you

I have to ask the same question I already asked for another answer: How does it manage libraries (and libraries versions) that you would get from variuous locations (e.g. on GitHub)? I ask in relation to these questions: http://arduino.stackexchange.com/questions/362/where-can-i-find-a-central-repository-of-all-available-arduino-libraries and http://arduino.stackexchange.com/questions/348/how-to-organize-my-arduino-projects-structure-for-easy-source-control

In addition to the mentioned IDEs you can use Xcode with embedXcode if you use a mac. The IDE has a great file structure and support for a lot of boards. For big and complex projects it is really good. I like to use vim or the arduino IDE for simpler and less complex sketches/projects.

PlatformIO
I use GitHub's Atom text editor with the PlatformIO package.
I like both of them:

Atom has various useful built-in features and over 6,000 packages (which can be easily downloaded and installed from the settings pane) allowing the user to add essentially any feature he needs.
PlatformIO is a powerful IDE for microcontroller programming. It has all the features of the Arduino IDE (like the ability to upload code to an Arduino board with one single click, a serial monitor, ...) plus many others (like all those listed by the OP) and perfectly supports Arduino. Besides "it supports more than 200 development boards along with more than 15 development platforms and 10 frameworks". It can be natively installed either on GitHub's Atom either on Microsoft's VSCode code editors.

Edit
I still use PlatformIO on Atom on a regular basis, but I just saw on their website and forum that they are discouraging users from using their Atom package while proposing PlatformIO in VSCode as a better alternative.
The Atom version still works well, but if you are changing your editor and want to try PlatformIO I would suggest to follow their advice and install it in VSCode.

I have always wanted to use Eclipse, since that is our standard (for Java) at work. But I never managed to get the debugger working with my AVR Dragon board - just too many layers between the source code and the chip.
So I am back to using Atmel Studio. You can set the keyboard mapping to emulate various other IDEs (including Eclipse and Netbeans). I can accept the Microsft quirkiness in return for a stable debugging environment, multi-file support and professional source control features.

I have done debugging with the Arduino eclipse plugin (recently renamed to sloeber sloeber.io ) and the zero. I do not own a avrdragon but I know other people got it to work.

Clion + PlatformIO
I personally use Clion which is a cross-platform IDE along with PlatformIO which is a cross platform build system for arduino and alike.
Clion because I love the jet brains IDEs. As a student or teacher you can get a free licence. And I have been told by suspicious people on the internet that there are other ways of obtaining a license (not that I would advice on doing anything like that).
PlatformIO is quite powerful and integrates well into almost any IDE. It's easy to declare dependencies to other libraries which are automatically downloaded.
I am also using the Clion serial port monitor plugin to communicate over Serial.print().
With this setup you can completely ditch the old Arduino IDE which I found to be quite satisfying!

I use Xcode, set up as an external editor. I write everything in libraries, and the sketch simply call the libraries.

Fritzing

This is the new “Code View”! It lets you write your code directly inside Fritzing, and even upload it from there to your microcontroller. It even has a serial monitor. :)

Normally known as a schematic builder, Fritzing has a built in IDE.
See here for more.

Notepad++

set Notepad++: view->folder as work space
and Language->C->C++ sets syntax highlighting
set arduino Ide file->preferences "Use external editor"

and everything runs smoothly, without the bulk of eclipse.

My go-to choice (pun, that's only a pun, folks!) is Sloeber - Eclipse with Jantje's EclipseArduino plugin. Having decades of emacs muscle-memory-training, I use MulgaSoft's Emacs+ plugin with it, switching to real GNU emacs for the heavy lifting - as developing a project and new libraries for it in parallel, f/ex, and use Sloeber to catch my typos & brain-f*ts.

A good alternative to the Arduino IDE is Visual Studio Code in combination with the Microsoft extension for Arduino https://github.com/Microsoft/vscode-arduino
It gives all the features of the Arduino IDE such as
Verify and upload your sketches in Visual Studio Code

Built-in board and library manager
Built-in example list
Built-in serial monitor

but additionally to offers some attractive features:

IntelliSense and syntax highlighting for Arduino sketches
Snippets for sketches
Automatic Arduino project scaffolding

Haven't seen anyone mention it yet, but I use VisualMicro for Microsoft Visual Studio (not Atmel), and I like it just fine. It gives you everything you'd normally have in Visual Studio, like intellisense typing. The trial version is the full program, and the license is pretty cheap- like 30 bucks or something. I got my work to pay for a commercial license key. Do recommend!

I use Eclipse and Sublime Text for editing Arduino code, and I build in the Arduino IDE with it set to "external editor" mode, or using the Arduino Command Line tools. Eclipse has a fantastic indexer and makes understanding the Arduino core much easier. I've written a detailed PDF about using and setting up Eclipse for professional software development, incl for Arduino, here: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/eclipse/Eclipse%20setup%20instructions%20on%20a%20new%20Linux%20(or%20other%20OS)%20computer.pdf.
Note that I'm using regular Eclipse for C/C++, with no Arduino plugins. I don't find them that useful since they can never seem to keep up with the latest Arduino build tools anyway.
See my document for full setup information in general.
Related:

C++ vs. The Arduino Language?

after some experience
any editor (atom or vscode) are excellent with platformIO
offering:

syntax highlighting
debugger
easy project (s) manager
(which i like most) collapsible blocks

In late 2019 we have the Deviot Sublime Text 3 plugin that runs on top of PlatformIO.


text:
AnalogRead from voltage divider ladder
I'm building a MIDI guitar, using an Arduino, sound synthesising and wood.
To properly know which note I'm pressing, I built a voltage divider with 12 equal resistors (10K). One side is connected at +5V and the other end at GND, so each of the 6 strings connects the right tap to the ADC.
I had just calculated the expected value w/ a bit of math considering I also needed a pullDown resistor(1M) and capacitor for every analog channel to keep the readings stable when no key is pressed.

When measuring with my multimeter the readings are stable, and there are variations of less than 0.02V, and since the difference from tap to tap is about 0.4V that's quite good.
The problem is when reading the 6 channels together: channels supposed to be pulled down to gnd read voltages caused by nearby channels, readings are shaky and similar errors.
This mess disappears on one channel when I connect the multimeter to that one.
Instead of buying 6 multimeters, I figured I could ask you if someone has an idea on why this happens, my guess is on the pulldown resistor, but I'm not sure about Arduino's ADC; I'm also worried about having 6 wires half of a meter each so close, so any other idea on finding the keys is welcome.
EDIT
@EdgarBonet was right, I used 12x220ohm resistors, and at first the results were absolute garbage, then I made it so the code would read each channel about 10 times, discard the readings, wait a millisecond and finally read and store the value. Now it is perfect.
Thanks again.

Circuit link doesn't work.

Excuse my naiveté but... why 12 taps for 6 strings? And why can't you wire those switches the usual way into digital inputs?

@EdgarBonet each string makes 12(+1 open) notes, and there are 6 strings; this means 72 inputs. That's too many switches

Oh, I see. Your circuit now makes perfect sense to me. You could simply reduce the resistances, e.g. R1 = ... = R12 = 1 kΩ and R_PD = 10 kΩ.

The datasheet of the ATmega328P (the main chip of the Uno) states:

The ADC is optimized for analog signals with an output impedance of
  approximately 10 kΩ or less.

The Thevenin equivalent output impedance of most taps of
your voltage ladder is higher than 10 kΩ. You 1 MΩ pulldown is
way beyond that limit. Cross talk from previously read channels is
exactly the symptom you expect from excess output impedance.
Taking each reading multiple times, until the value stabilizes, should
help. A buffer (e.g. an OP-amp set as a unit gain amplifier) is the
usual solution to this kind of impedance problems.

Actually, the whole works perfectly with R as 220 and pull downs as
  10K. The problem comes when connecting more than 3 strings at the same
  time, on any tap, as the pull down resistors become part of the
  ladder (i belive).

The pull down resistors will indeed have an effect on the potentials of
the voltage ladder, especially if you connect several strings. This
could be minimized by having the pull-downs be a lot more resistive
than the resistors along the ladder, but then you would need very low
resistances along the ladder, which is not desirable because of current
consumption and heating.
Here is an idea for an alternative solution: If you can spare 6 digital
pins, you could build for each analog input a pull-down circuit that is
switchable between a “strong pull” mode and a “weak pull” mode. Assuming
D0 is the “pull strength control” pin for A0, it would look like this:
A0 ---+--- 1 kΩ --- D0
      |
     1 MΩ
      |
     GND

Whenever you want to read A0, you:

set D0 to OUTPUT LOW, which creates a strong pull-down to ground
take a couple of analogRead()s
set D0 as INPUT, which leaves only the weak 1 MΩ pull down
take a couple of analogRead()s, keep the last one.

If A0 is not connected to the ladder, then the first reads will
discharge the internal sampling capacitor of the ADC. The final read is
done with only a weak pull-down, but this should be OK since the
capacitor has already been discharged.
The potentials along the voltage ladder will be disturbed by any string
connecting a tap to its strong pull-down, but this disturbance will
disappear when you switch to weak pull-down, so it will not affect the
readings.

I'm well open to changes in the circuit, and I used the first resistors I had.

Actually, the whole works perfectly with R as 220 and pull downs as 10K.
The problem comes when connecting more than 3 strings at the same time, on any tap, as the pull down resistors become part of the ladder(i belive). Would raising R from 220 to 1k ohm solve anything?

@sassoPera: Connecting several pull-downs to any tap will indeed affect the potentials along the ladder. Raising R can only make this worse. See the amended answer.


text:
Detect and stream if a chair is occupied
I am planning to build a device able to detect and tell a server via Wi-Fi if a chair is occupied. How would you do it? And how cheap do you think the device could be?

For those who voted to close this question as too broad: I think it's pretty specific. With a few reasonable assumptions about the chair being rigged with the device, I would hazard a guess that one would need an Arduino board, an Wi-Fi shield and a suitable pressure sensor. Can anyone more knowledgeable than me layout a more detailed answer along those lines?

Do you have an Arduino board yet? Are you planning on using a specific one?

I'm just thinking at how this could be done ;-) My idea is to build something like a internet-based service to map where there are free spots in cafes

@gre-gor was changing the capitalization pattern of a single term nearly 4 years after the fact really worth bumping the question to the top of the page?

Oh wow, so many ways you could do this.  To start, get an arduino with a wifi shield to transmit and read data.  Familiarize yourself with how the arduino works with the shield, and how to read it on the other end.  Then it's time to look at sensors you could use.  Here's a couple ideas, I would recommend using more than one and cross-checking:

Force sensor on base of chair: Can tell you how much weight is on a chair (Sparkfun SEN-09376)
IR or sonic sensor on back of chair to detect distance (example)
Vibration/shock sensor to detect if someone has sit down (example)
Load sensor: literally a scale in a sensor. (Sparkfun SEN-10245)

The optimal solution if you had the cash would be to put all of them on the chair and use the arduino to compute all of the sensor values into one boolean.  However, if you only could have one sensor I would recommend the load sensor which would definitely be the most reliable of all the examples I gave.

What's the difference between 1 and 4? Also, I don't know how well the vibration sensor would work, as if someone were to reposition themselves or if they were laughing really hard.

Yeah, the vibration sensor would only be useful as an additional check combined with at least one other sensor.  As for the force sensor vs the load sensor, the load sensor works more mechanically and can measure a greater weight.

For a soft seat you could sense occupancy with an LED and photo-sensor at opposite ends of a short somewhat flexible tube that gets flexed when the cushion compresses, interrupting the light. That or a microswitch would have to be the cheapest means of sensing.
Getting from there to the server depends a little on how much work you're willing to do, from rolling your own micro-controller+WiFi PCB to purchasing off the shelf parts, which may in turn, depend on whether you need to monitor one chair or a whole auditorium.

I'm not going to answer this directly, because then you wouldn't learn anything! However, here are a few suggestions:

Use a pressure sensor on the seat of the chair or
Put a distance sensor (IR or ultrasonic) pointing at the chair.
Use the official Arduino WiFi shield.

That's what I meant in my comment to the OP: if there's not enough information on the original post, just point the poster to the right direction. No need to close a perfectly decent question. Good answer! +1

@Ricardo Yeah, I guess I'm too used to Stack Overflow. If a question like this were asked on Stack Overflow, it would be closed within ten minutes.

Right! It would have been closed quickly on EE.SE, too. With good reasons, I guess. But we are not them, right? We can make our site the way we like it. Arduino questions are always welcome here. That's my motto!

Actually, the OP didn't even mention Arduino anywhere in his or her question. But that's implied :D

You could use the awesome CapSense-Library. Additionally to the Library you only need a thin piece of conducting material e.g. aluminium foil and two pins on your arduino. The only thing you have to do is experiment with different resistors to reliably distinguish between someone sitting on the chair or not. Advantages of this method are:

virtually no costs at all
easy to implement
not subject to wear and    tear
should work with any kind of chair independent of material e.g.
hard or soft surface
consumes next to no power (I assume the whole device runs on battery since it's attached to a movable chair)
could even sense a person in the process of seating her-/himself and enable you to start the music faster (my stereo for example takes a second or so to start up)

You could use Electric Field Sensing, it allows you to detect the presence and position of conductive objects even if the sensor is covered by an opaque object. The technology is used in cars to detect if someone is sitting in a seat so the car can beep at you to put your seat-belt on. However, if all you want to do is detect presence then this is no better than using CapSense.
http://web.media.mit.edu/~jrs/efs.html
https://en.wikipedia.org/wiki/Electric_field_proximity_sensing
To communicate with a server over WiFi you could use the Arduino WiFi shield, the Arduino Yun (which has on-board WiFi) or buy a ethernet WiFi adapter and use it with an Arduino board which has ethernet.
http://arduino.cc/en/Main/ArduinoWiFiShield
http://arduino.cc/en/Main/ArduinoBoardYun
(Arduino board with on-board WiFi)
http://arduino.cc/en/Main/ArduinoBoardEthernet

conductive foam as sensor. it chg resistance when compressed.
or use image from camera to determine if seat is occupied. only one source for all data.


text:
How to control Arduino using mBlock and Bluetooth?
Is it possible to control an Arduino using mBlock and Bluetooth?
Assuming yes, I tried various things, but was not able to come to a conclusion.
I am trying to get this combination working using a HC-05 Bluetooth module. I am not sure if my Bluetooh setup is the problem or is mBlock is not able to recognize the COM port provided by Bluetooth.
I can see the COM device (in fact two?) when I pair HC-05 with PC. I have the following questions based on whatever I have tried so far:

When I connect HC-05, should I connect TX to TX OR reverse them?
There are varying articles describing both ways of connection.
How much baud rate do I need to set on the Bluetooth device?
Do I need to use the voltage divider for RX? Again there are varying tutorials.
Is mBlock default Arduino firmware sufficient for such setup?

I got it working. Following are steps.

Set the Bluetooth baud rate to 115200. The mBlock firmware uses
this baud rate for serial communication.
Connect Bluetooth to Rx and Tx of Arduino.
Upload default Arduino firmware (orion firmware) to
Arduino using mBlock.
Use mBlock to interact with Arduino using Bluetooth.

Please note that Bluetooth cannot be used to upload
the sketches to Arduino for offline mode.

Connecting Bluetooth COM device to PC in AT mode to set baud rate.

Upload empty (default) sketch to Arduino using USB cable.
Connect 5V of BT shield to 3.3V of Arduino.
Connect EN or BT to 5V.
Connect Tx to Tx and Rx to Rx.
Use USB cable to power on Arduino.
Before turning the power ON, keep pressing the EN
button on BT shield. The LED should blink with almost
a second delay. That is the indication that it is AT mode.
Start Arduino IDE, and connect to the COM port of Arduino
and NOT that of the BT.
Start serial monitor.
Set the baud to 38400 and terminate character settings to
"Both NL $ CR".
In the command input field of Serial Monitor type at twice. First time response will be error, second time it should be ok.
Now use the at commands to set baud rate using "at +uart=115200,0,0" e.g.
Use "at +uart?" to see what is the baud rate set on the device.

Connect Bluetooth device to Rx and Tx of Arduino.
Arduino  <-> HC-05
   =======      =======
   5V            Vcc
   GND           GND
   Rx            Tx
   Tx            Rx (Via Voltage divider)
Some of the articles talk about connecting 3.3V of Arduino to the
Vcc of HC-05 and not using the voltage divider at all. However this
combination fails as once increases the baud rate.
Check out more details about voltage divider here. https://electronics.stackexchange.com/questions/280500/why-do-you-have-to-use-a-voltage-divider-with-hc-05-bluetooth-module-arduino
What is the story of two COM devices for Bluetooth?

https://electronics.stackexchange.com/questions/13741/bluetooth-module

When I connect HC-05, should I connect Tx to Tx OR reverse them?

There are varying articles describing both ways of connection.

Yes, swap them. TX on the HC-05 to RX on the Arduino. However you could struggle to use pins 0/1 since they are the USB connection. SoftwareSerial (which is nasty) is what most people use instead.

How much baud rate do I need to set on the bluetooth device?

Whatever rate you want to communicate at. It's up to you. However all baud rates must match throughout the system - the baud rate on the Arduino, the baud rate of the HC-05, the baud rate of the SPP port on your PC, etc.

Do I need to use the voltage divider for Rx? Again there are varying tutorials.

Which RX? Arduino TX to HC-05 RX yes. HX-05 TX to Arduino RX no.

Is mblock default arduino firmware sufficient for such a setup?

What is mblock?

thanks for the comments. mblock is the visual programmer tool which has arduino eco system integrated. http://www.mblock.cc.

Majenko Could you please explain why using 0/1 is not good idea? I think the default firmware that I use for mblock may be expecting the serial communication to happen over 0/1 pin of arduino.

0/1 is used for communication with the PC and uploading new sketches. You can't do that whilst at the same time communicate with an external module such as bluetooth.


text:
How to send AT command to sim800l with SoftwareSerial
I have SIM800l module connected to Arduino and I'm trying to initialize it in my setup function with this code:
#include <SoftwareSerial.h>

//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 6
//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup()
{
  Serial.begin(38400);
  while(!Serial);
  serialSIM800.begin(38400);
  Serial.println("wait for .... it");
  delay(10000);

  // comments added just for example, both commands return junk
  //serialSIM800.write("AT\r\n");
  //serialSIM800.write("AT+SAPBR=3,1,\"Contype\",\"GPRS\"\r\n");

  Serial.println("command sent");
  delay(2500);

  Serial.write(serialSIM800.read());
}

But Serial.write returns junk.
When I use this code in loop:
  //Read SIM800 output (if available) and print it in Arduino IDE Serial Monitor
  if(serialSIM800.available()){
    Serial.write(serialSIM800.read());
  }
  //Read Arduino IDE Serial Monitor inputs (if available) and send them to SIM800
  if(Serial.available()){
    serialSIM800.write(Serial.read());
  }

and send AT+SAPBR=3,1,"Contype","GPRS" or just AT command with serial monitor, everything works fine.
Can someone help with this?

Can you place your schematic? Are you using the 4V regulation and transistor on RST pin? Maybe this library might help

What sort of junk? Copy and paste please. Also writing the output from a read, without testing for available is likely to return "junk" or at least ÿ.

You're reading only a byte like others have noted. Also, you seem to be sending 2 commands, one immediately after the other. This could result in gibberish. Though it would be nice to see exactly what your 'junk' results are.

I'm a bit surprised you have put a bounty of +100 rep on this question, but are not answering queries like the comments above, that might help resolve it.

You can try to use serialSIM800.println("AT") instead of write. Here some examples https://github.com/stanleyhuangyc/Freematics/issues/17

Somewhere you said that ...but Serial.write return's junk....
Make sure that serial print is Both NL & CR

IIRC, SIM800 modems are very 1990s, they default to 9600 baud. You will get garbage at 38400.
I successfully used a SIM800 at 9600.

You are getting junk because of baud rate, set as 9600.
Serial.begin(9600);
  while(!Serial);
  serialSIM800.begin(9600);
  Serial.println("wait for .... it");
  delay(10000);

NeoSWSerial would be better for this.  It can read and write at the same time, unlike SoftwareSerial, and it doesn't disable interrupts for the entire character receive time (~1ms!).  AltSoftSerial would be even better, but you can only use it on pins 8 & 9 (on an UNO, different pins on other Arduinos).

My SIM808 returns a bit of junk right from the get-go, so that might be influencing things.
Also, it's conceivable you are retrieving a -1 from your initial serialSIM800.read() call - it's a nonblocking call and returns -1 when no data is available.  That would almost definitely appear as junk.

Sim800 series free Atcommander software.
http://bayanbox.ir/info/3493267131357723232/ATcenter


text:
the use of the Arduino's EEPROM
I want to know the purpose of using the EEPROM because I can't get it,
I mean I know that it can store values for a long time, but I just can't get the goal here
#include<EEPROM.h>
void setup()
{
  Serial.begin(9600);
  EEPROM.write(0,4);
  int s=EEPROM.read(0);
  int f=10;
  Serial.print(s);
  Serial.print(" ");
  Serial.print(10);
}

void loop()  {}

For example, I'm using EEPROM to see the difference if I print a value inside variable s to the serial moniter using EEPROM and a normal value inside the variable f.
But I couldn't find the difference between both because when unplugging the power and turn it on again, both of them are printed.
Hope you got the idea and I hope to see some feedback.
Thank you..
the LED program
then I made this program that will compare the EEPROM value to num.4 and compares the F variable to num.4
known that both F and the EEPROM values are 4.
and then I changed both of the values to 3.
shouldn't the GREEN LED of the EEPROM still on because it has already stored num.4??
#include<EEPROM.h>
void setup()
{
  pinMode(12,OUTPUT);
  pinMode(11,OUTPUT);
}

void loop()
{

  EEPROM.write(0,4);                 //GREEN LED
  int f=4;                           //RED LED

  if(EEPROM.read(0)==4) digitalWrite(12,HIGH);
  if(f==4) digitalWrite(11,HIGH);
}

from where is this code? Swap the lines with read and write. The run the code. Then change the 4 to 42 and upload again.

In your sketch, the leds will never be off because you write to eeprom and read back its value immediately. It's quite trivial that they are the same. Also, you will kill the eeprom rather soon if you write to it that frequently. Eeproms are typically rated for around 100k write operations, so your sketch might brick the eeprom within a few minutes.

now even if I write it inside the void setup, the GREEN LED will not turn on when I change the value to 3. I mean it should save number 4 inside so that the value will simply stay inside right?

What did you move to the setup()? The entire code that is in loop()? Do you understand what Tom_C wrote in his answer? ONE sketch is not enough to really demonstrate the purpose of an eeprom. Instead you should upload and run a sketch1 which writes a value to eeprom in setup(), then upload and run a sketch2 which reads the eeprom and uses the respective value

I edited my answer

In short:
Once you shutdown an Arduino, every variables on it, which have been calculated by the sketch, are lost. That is because they are stored in RAM, which is not able to store things without power. That is not the problem of EEPROM: values stored there will be available on reboot, and won't need to be calculated again.
This can prove useful is your device is allowing a user to store presets: so a configuration of the program. If this configuration, which can be for instance variables affecting the program behavior, is stored in RAM, it will be lost on next reboot. On the other hand, a value stored in EEPROM during the first execution (entered by user for instance) will still be available on next reboot, if you took the time to write it (on the first run) and to read it (on the second run). Just like saving and then recalling a preset.
Beware that EEPROM does not like to be written too many times and wear out, so you should keep that to a minimum (values that really need to be restored on reboot, and cannot be calculated at this time).

thanks @Tom_C   I've edited my post and added THE LED program and asked why the LED of the EEPROM is not ON, hope that you can give me feedback there as well

@klay just like before, your new example does not ANY advantage of EEPROM. Did you read my answer? Here your write and read eeprom in a row, which is a bit like: "I put a cheese in my fridge, what is in my fridge now? Oooh, a cheese!"

@klay  Furthermore, as said in answer, EEPROM do NOT like to be written often. Your EEPROM.write(0,4); in the loop will kill it in a very (very) short time

I just want to apply the concept of it, you know when you store a value to it, and then use it similar to the smart house for example that works on particular orders, so the idea here is to only change it once to show the principle of EEPROM. even when I write it in the SETUP, the LED will not work as well. so consider writing this sketch inside the void setup, how can I still make it work for only once?

I'm sorry, I do not understand what you want or do not understand. Maybe @Sim Son is closer to what you are looking for. In any case, if you do not see the point of writing in EEPROM, then you probably do not need it ;). Also, if you ran the sketch in your answer now, beware that the first EEPROM memory block is likely to be dead.

"It can store values for a long time" - that's not exactly what an eeprom does, the major property is that the information in the eeprom persists during power cycles and chip resets. In contrast, a RAM looses all information when you unpower the chip.
To get a feeling for eeproms, I suggest you follow the below routine:
1. Upload this sketch:
#include "EEPROM.h"

void setup() {
  EEPROM.write(0,4);
}

void loop(){}

2. Once this sketch has been executed, upload and run the below sketch (you could even unplug the arduino before this step):
#include "EEPROM.h"

void setup() {
  pinMode(12,OUTPUT);
  if(EEPROM.read(0)==4) digitalWrite(12,HIGH);
  EEPROM.write(0,3);
}

void loop(){}

3. Now, the green led will light up.
4. Reset the atmega and now the green led will remain off.
By just using a variable int f which is in RAM, you can not "transfer" a value between those sketches/runtimes.


text:
multiple button switch case how to add counter
I want to add counter in multiple-buttons-to-control-relays:
int relay1 = 23;
int relay2 = 25;
int relay3 = 27;
int relay4 = 29;
int relay5 = 31;
int relay6 = 33;
int relay7 = 35;
int relay8 = 37;
////////////int mode =  41;      // select mode AUTO/MANUAL if HIGH=AUTO else LOW=MANUAL
//////////int start = 43;      // select START/STOP auto mode
//////////int tool =  13;       // tool Sw
int sw1 = 2;
int sw2 = 4;
int sw3 = 6;
int sw4 = 8;

int sw5 = 3;  //additional
int sw6 = 5;
int sw7 = 7;
int sw8 = 9;
 ////////int modeState =  1;  //modelState for //start stop and tool
/////////int startState = 1; //start1State
/////////int toolState =  1;
int sw1Status, sw2Status, sw3Status, sw4Status,sw5Status, sw6Status, sw7Status, sw8Status;
int order = 1; // default is to set all relays off.
/// for counter//////////////////////////////////////////////////
int val = 0; // variable for reading the pin status
int counter = 0;
int currentState = 0;
int previousState = 0;
//// for counter ////////////////////////////////////////////////
void setup() {
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  pinMode(relay5, OUTPUT);
  pinMode(relay6, OUTPUT);
  pinMode(relay7, OUTPUT);
  pinMode(relay8, OUTPUT);

  // input pull-up, so default state of buttons is HIGH.
  pinMode(sw1, INPUT_PULLUP);
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  pinMode(sw4, INPUT_PULLUP);
  pinMode(sw5, INPUT_PULLUP);  ///additional
  pinMode(sw6, INPUT_PULLUP);
  pinMode(sw7, INPUT_PULLUP);
  pinMode(sw8, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  // read the buttons status
  sw1Status = digitalRead(sw1);
  sw2Status = digitalRead(sw2);
  sw3Status = digitalRead(sw3);
  sw4Status = digitalRead(sw4);
  sw5Status = digitalRead(sw5);
  sw6Status = digitalRead(sw6);
  sw7Status = digitalRead(sw7);
  sw8Status = digitalRead(sw8);
  ///// tool state example
  ////if (sw1Status == LOW && sw2Status == LOW && sw3Status == LOW && sw4Status == LOW && toolState == HIGH) { //

  if (sw1Status == LOW && sw2Status == LOW && sw3Status == LOW && sw4Status == LOW) { // if button 1 pressed
    order = 2; // go to case 2 start up state
    Serial.println("all switch off follow order 2");
  }
  if (sw1Status == HIGH && sw2Status == LOW && sw3Status == LOW && sw4Status == LOW) { // if button 2 pressed
    order = 3;// go to case 3
     Serial.println("order 3 sw 1 relay 1 on");
  }
  if (sw1Status == HIGH && sw2Status == LOW && sw3Status == LOW && sw4Status == HIGH) { // if button 3 pressed
     //// possible if (order != 5) { // if order is not equal 5 turn on relay 1 & 4
    order = 4;// go to case 4
    Serial.println(" order 4 sw 1,4 relay 1,7,8 on");

  }
  if (sw1Status == HIGH && sw2Status == LOW && sw3Status == HIGH && sw4Status == LOW) { // if button 3 pressed
    order = 5;// go to case 5
    Serial.println(" order 5 sw 2 3 on relay 1on now right down");
  }
  if (sw1Status == LOW && sw2Status == HIGH && sw3Status == HIGH && sw4Status == LOW) { // if button 3 pressed
    order = 6;// go to case 6
    Serial.println(" order 6 sw 3 and 2 on");
  }
  if (sw1Status == LOW && sw2Status == HIGH && sw3Status == LOW && sw4Status == HIGH) { // if button 2 pressed
    order = 7;// go to case
     Serial.println(" order 7 ");
  }
  if (sw1Status == LOW && sw2Status == HIGH && sw3Status == HIGH && sw4Status == LOW && sw7Status == LOW) { //
    order = 8;// go to case
    Serial.println("orde 8 left side ");
  }
  if (sw1Status == LOW && sw2Status == LOW && sw3Status == LOW && sw8Status == HIGH && sw8Status == LOW) { //
    order = 9;// go to case
    Serial.println(" spare order 9 sw 4 high");
  }

  if (sw1Status == LOW && sw2Status == LOW && sw3Status == LOW && sw4Status == LOW) { // button 4 toggle
    if (order != 10) { // if order is not equal
      Serial.println("  spare order 10 all off ");

      order = 10;
    }
    else { // else go to case 1, which will turns off all relays
      order = 1;
    }
  }

  switch (order) {
    case 1: // if order equals 1
    delay(200);
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, HIGH);
      digitalWrite(relay5, HIGH);
      digitalWrite(relay6, HIGH);
      digitalWrite(relay7, HIGH);
      digitalWrite(relay8, HIGH);
      Serial.println("default start up ");

      break;

    case 2: // if order equals 2
    delay(1000);
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, HIGH);
      digitalWrite(relay5, HIGH);
      digitalWrite(relay6, HIGH);
      digitalWrite(relay7, HIGH);
      digitalWrite(relay8, HIGH);
      Serial.println("move up case 2");

      break;

    case 3: // if order equals 3
      delay(1000);
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, HIGH);
      digitalWrite(relay5, HIGH);
      digitalWrite(relay6, HIGH);
      digitalWrite(relay7, HIGH);
      digitalWrite(relay8, HIGH);
      Serial.println("move right case 3");

      break;{

    case 4: // if order equals 4
      delay(1000);
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      digitalWrite(relay5, HIGH);
      digitalWrite(relay6, HIGH);
      digitalWrite(relay7, LOW);
      digitalWrite(relay8, LOW);
      Serial.println("move down case 4");
      break;}

    case 5: // if order equals 5
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, HIGH);
      digitalWrite(relay5, HIGH);
      digitalWrite(relay6, HIGH);
      digitalWrite(relay7, LOW);
      digitalWrite(relay8, LOW);
      Serial.println("move down  case 5");
      break;
      case 6: // if order equals 6
      delay(1000);
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, HIGH);
      digitalWrite(relay5, HIGH);
      digitalWrite(relay6, HIGH);
      digitalWrite(relay7, HIGH);
      digitalWrite(relay8, HIGH);
      Serial.println("move up case 6");
      break;
          case 7: // if order equals
          delay(1000);
          val = digitalRead(sw2Status); // read input value
          if (val == HIGH)  // check if the input is HIGH (button released)
            currentState = 1;
            if(currentState != previousState)
            if(currentState == 1)
              counter = counter + 1;
              else
              case 10: // if order equals
            Serial.println(counter);

      digitalWrite(relay1, LOW);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, HIGH);
      digitalWrite(relay5, HIGH);
      digitalWrite(relay6, HIGH);
      digitalWrite(relay7, HIGH);
      digitalWrite(relay8, HIGH);

      Serial.println("move up rly 1");
      break;

    case 8: // if order equals
    delay(1000);
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, HIGH);
      digitalWrite(relay5, HIGH);
      digitalWrite(relay6, HIGH);
      digitalWrite(relay7, HIGH);
      digitalWrite(relay8, HIGH);
      Serial.println("new left side");
      break;
      case 9: // if order
      delay(1000);
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      digitalWrite(relay5, LOW);
      digitalWrite(relay6, LOW);
      digitalWrite(relay7, HIGH);
      digitalWrite(relay8, HIGH);
      Serial.println(" on right side");
      break;

    default: // if none of above cases is valid go to case 1
      order = 1;
      break;
  }
}

multiple button switch case for multiple relays

Align your code by selecting it and press ctrl-k  You added the counter already in your code. So I guess the counter does not count what you want, and we cannot guess. Describe what you expect counter to count, and what you see now.

I'm confused. Your buttons are set up using INPUT_PULLUP, so reading a low from a button should indicate that it's pressed. You have code like this: if (sw1Status == LOW && sw2Status == LOW && sw3Status == LOW && sw4Status == LOW) with a comment of "if button 1 pressed". I read that code to say "if switches 1, 2, 3, and 4 are all pressed...". Why do you interrogate the state of all your buttons to determine which case to execute in your switch statement? Is it valid for the user to press multiple buttons at the same time to get to different relay states?


text:
Slice byte-stream into bit pieces
I receive byte data from a RS-232 device with Serial.read();. Now I need to slice this down in bit-pieces:

value1: 15bits
value2: 7bits
value3: 9bits
value4: 12bits
and so on

Data from the stream (switch them around for better understanding):

Byte 1: 00101100 => 00110100 (least significant byte first)
Byte 2: 10011011 => 11011001
Byte 3: 00110011 => 11001100
Byte 4: 11101000 => 00010111
Byte 5: 01001100 => 00110010
Byte 6: 01100111 => 11100110

Now the least significant is first.

value1: 00110100.1101100[1] => 6956
Need to cut of the last bit of the second byte
value2: 1.110011[00] => 103
Add the last bit of the second byte and cut off the last two bits of the third byte
value3: 00.0001011[1] => 416
Add the last two bits of the third byte and cut off the last bit of the fourth byte
value4: 1.00110010.111[00110] => 3737
Add the last bit of the fourth byte and cut off the last 5 bits of the fifth byte

Now the question: How do I realize this from programming side. I'm lost.

If the records are byte aligned you could use a struct with bit-fields and let the compiler do the work. http://www.tutorialspoint.com/cprogramming/c_bit_fields.htm

Another alternative is to define a BitStream class that operates on a Stream (Serial). Typical member function would be uint16_t read(uint8_t bits). The class would have to buffer any remaining bits for the next read, etc. http://www.drdobbs.com/bitstream-parsing-in-c/184402014

@LookAlterno But this one has an answer. It is/was edited into the question. I have now put that as an answer.

Note: This is an answer that OP originally edited into his question.

I gather the data into an array of bytes data[125].
Then I gather the relevant bytes per value and stack them together:
long var = (data[4]<<8) + (data[3]);

I shift them so the relevant bytes start first
var=var>>3;

Afterwards I mask them with the RIGHT mask
var=var & 0xFF;

For the example in my question:
long var = (data[1]<<8) + (data[0]); // I need two bytes
var=var>>1; // shift them to the right one bit
var=var & 0x7FFF; // mask it with "0111 1111 1111 1111"

Good work gre_gor!


text:
I would like to know the ATMEGA wiring to Arduino

I would like to know which pins are connected to the output of the Arduino.
For example:

PC6 is digital 12
PB5 is analog 13
etc...

Image searching for the term "arduino uno pinout" reveals a better pinout diagram.

I prefer this image, as it combines the arduino pin numbers and PWM capabilities, with the names and functions from the datasheet.

I usually preferred this image. It very useful for me every time.

Or you could simply look at the Arduino Uno schematic, which has everything you should ever need to know.

I think this is the diagram you are seeking.

thanks for your help everyone
just another question
is there another program to implement the code to the arduino
other than the official arduino  program
i need a program where i can debug and put break points like mplab
thanks for your help

Start a new question...

Updated: Pins PB6 & PB7 while available as I/O pins (D6 & D7) are committed to the external crystal on this board and not brought out to the connectors.

That is not true: you cannot find a connector for XTAL for instance.


text:
I want to change my "serial monitor" command to push button command for IR cloning project
void loop() {
  char data[6];
  int index = 0;

  delay(1000);  //Serial input seems to need some kind of short delay or the data gets screwed up.

  while (Serial.available() > 0) {            //Loop if there data on the serial line
    if (index < 5) {                          //Make sure we don't overflow
      data[index] = Serial.read();            //Load a character into the string
      index++;                                //Increment the index to get the next character
    }
  }

  data[5]='\0';  //Null terminate the string

  if (strcmp(data, "POWER") == 0){                //If the Arduino receives the POWER signal...
    Serial.println("SENDING SIGNAL!");
    for (int i = 0; i < NumIRsignals; i+=2) {         //Loop through all of the IR timings
      pulseIR(IRsignal[i]*10);              //Flash IR LED at 38khz for the right amount of time
      delayMicroseconds(IRsignal[i+1]*10);  //Then turn it off for the right amount of time
    }
  }                                         //Otherwise do nothing!
}

// This function allows us to PWM the IR LED at about 38khz for the sensor
// Borrowed from Adafruit!
void pulseIR(long microsecs) {
  // we'll count down from the number of microseconds we are told to wait

  cli();  // this turns off any background interrupts

  while (microsecs > 0) {
    // 38 kHz is about 13 microseconds high and 13 microseconds low
   digitalWrite(IRledPin, HIGH);  // this takes about 3 microseconds to happen
   delayMicroseconds(10);         // hang out for 10 microseconds, you can also change this to 9 if its not working
   digitalWrite(IRledPin, LOW);   // this also takes about 3 microseconds
   delayMicroseconds(10);         // hang out for 10 microseconds, you can also change this to 9 if its not working

   // so 26 microseconds altogether
   microsecs -= 26;
  }

  sei();  // this turns them back on

And what exactly is the problem? We aren't a code writing service.

Purav Vashisht, please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.  Also note that your question is going to be closed pretty soon unless you edit it to include a clearly stated question.  Or at least a question.

//Serial input seems to need some kind of short delay or the data gets screwed up. - Wrong, wrong, wrong! Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Please specify your question.

Please read How do I ask a good question?. Your "question" just seems to be some code. The subject title doesn't really clarify what the question is.

Identify the code which collects the characters from the serial port.  Then remove it.
Also remove the line of code which check to see if the correct character sequence was received.
Replace the above check with code that tests if a button has been press.

Note:

Mechanical buttons bounce!
And software is fast enough to see this as multiple button presses.

Avoid problems by going here and learning how to connect buttons to an Arduino and de-bounce buttons in software.