text:
SoftwareSerial Write to return Read in Serial Monitor?
Hoping someone can help me out in my conundrum here...
I currently am testing the SoftwareSerial library out to understand how I may use it in my project.
I have a wire running from pin 6 to pin 9, so that the TX talks straight to the RX.
I have written the following:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(6,9); //RX = 6 TX = 9

void setup() {

  Serial.begin(1200);
  mySerial.begin(1200);
}

void loop() {

  mySerial.write('F');
  delay(100); // attempting to allow time between write and read commands

  while (mySerial.available()>0) {
  Serial.println(mySerial.read());
  }
}

The whole point is just to see 'F' return in the Serial Monitor.
The output, unfortunately, is absolutely nothing! If I omit the while(mySerial.available>0) I just get -1 's down the lines of the Serial Monitor.
Thank you in advance!

SoftwareSerial cannot talk to itself. Since it is implemented in software and not hardware it can either send or receive at one time, but not both.
Look at the code for write in SoftwareSerial:
size_t SoftwareSerial::write(uint8_t b)
{

...

  cli();  // turn off interrupts for a clean txmit

...

  // Write each of the 8 bits
  for (uint8_t i = 8; i > 0; --i)
  {
    if (b & 1) // choose bit
      *reg |= reg_mask; // send 1
    else
      *reg &= inv_mask; // send 0

    tunedDelay(delay);
    b >>= 1;
  }

...

  SREG = oldSREG; // turn interrupts back on

...

}

Since it turns interrupts off, and interrupts are needed for it to detect incoming data, therefore it cannot detect incoming data while it is sending.

You're the best. Thank you.
Hypothetically, if I make a big delay between the TX and RX, shouldn't that solve the problem? Say,1 full second?

It would in hardware but not software. For SoftwareSerial the code actually goes into a timed loop (to receive) similar to the timed loop to send. It can't be doing both loops at once. If you connect SoftwareSerial to a HardwareSerial port it should work (the hardware works in the background).

Exactly what I needed. Thanks! You're the best!


text:
Why use an int variable for a pin when const int, enum or #define makes much more sense
Why do people use a variable to specify a pin number when the pin is unlikely to change throughout the execution of the code?
Many times I see an int being used for a pin definition,
int led = 13;

when the use of a const int
const int led = 13;

or enum, or #define
#define LED 13

makes much more sense.
It is even in tutorials on the Arduino site, for example, the first tutorial that most people run, Blink.
I read somewhere that const int is preferred over #define. Why isn't this encouraged right from the beginning, rather than allowing people to develop bad habits, from the outset? I noticed it a while back, but recently it has started to irritate me, hence the question.
Memory/processing/computing wise is a const int, enum, or for that matter #define, better than a plain int, i.e. occupies less memory, stored in different memory (Flash, EEPROM, SRAM), faster execution, quicker to compile?

This may appear to be a duplicate of Is it better to use #define or const int for constants?, but I am addressing the question of why people use variables, and how does the performance improve when they don't, rather than which type of constant is better.

Because terrible begets terrible. Most hobbyists aren't seasoned programmers and so teach other hobbyists bad habits.

With pins in particular, the simplistic form of the basic arduino API functions like digitalWrite don't encourage proper embedded design, i.e. using masks and a single memory address for the entire port

const int led = 13;

That is the correct method. Or even:
const byte led = 13;

How many pins do you have?
Some of the tutorials did not quite go through as much quality control as they might have.
Performance will be better using const byte, compare to int however the compiler may be smart enough to realize what you are doing.
What you can do is gently encourage people to use more efficient techniques by using them in your own code.

Responses to comments

A commenter has suggested that byte is not standard C. This is correct, however this is an Arduino StackExchange site, and I believe using standard types supplied by the Arduino IDE is acceptable.
In Arduino.h there is this line:
typedef uint8_t byte;

Note that this is not exactly the same as unsigned char. See uint8_t vs unsigned char and When is uint8_t ≠ unsigned char?.
Another commenter has suggested that using byte will not necessarily improve performance, because numbers smaller than int will be promoted to int (see Integer Promotion Rules if you want more on this).
However in the context of a const identifier, the compiler will generate efficient code in any case. For example, disassembling "blink" gives this in the original form:
00000086 <loop>:
  86:   8d e0           ldi r24, 0x0D   ; 13
  88:   61 e0           ldi r22, 0x01   ; 1
  8a:   1b d1           rcall   .+566       ; 0x2c2 <digitalWrite>

In fact it generates the same code whether the 13:

Is a literal
Is a #define
Is a const int
Is a const byte

The compiler know when it can fit a number into one register and when it can't. However it is good practice to use coding that indicates your intent. Making it const makes it clear that the number won't change, and making it byte (or uint8_t) makes it clear that you are expecting a small number.

Confusing error messages
Another major reason to avoid #define is the error messages you get if you make a mistake. Consider this "blink" sketch which has an error:
#define LED = 13;

void setup() {
  pinMode(LED, OUTPUT);      // <---- line with error
}

void loop() {
  digitalWrite(LED, HIGH);   // <---- line with error
  delay(1000);
  digitalWrite(LED, LOW);    // <---- line with error
  delay(1000);
}

On the surface it looks OK, but it generates these error messages:
Blink.ino: In function ‘void setup()’:
Blink:4: error: expected primary-expression before ‘=’ token
Blink:4: error: expected primary-expression before ‘,’ token
Blink:4: error: expected `;' before ‘)’ token
Blink.ino: In function ‘void loop()’:
Blink:8: error: expected primary-expression before ‘=’ token
Blink:8: error: expected primary-expression before ‘,’ token
Blink:8: error: expected `;' before ‘)’ token
Blink:10: error: expected primary-expression before ‘=’ token
Blink:10: error: expected primary-expression before ‘,’ token
Blink:10: error: expected `;' before ‘)’ token

You look at the first highlighted line (line 4) and don't even see a "=" symbol. Plus, the line looks fine. Now it's fairly obvious what the problem is here (= 13 is being substituted for LED), but when the line is 400 lines further down in the code, it isn't obvious the problem is with the way LED is defined.
I've seen people fall for this many times (including myself).

How many pins do you have? is a very good point Nick, as most boards have only in the range of the tens, not hundreds (i.e. greater than 255), so an int is overkill... that is, until Arduino finally come out with the Tera board... :-)

C doesn't have a byte type.  You mean unsigned char.

Performance won't necessarily be better with byte instead of int, since in most contexts, integer value with types smaller than int are promoted to int.

C doesn't have a byte type. You mean unsigned char. - My answer was in the Arduino context, which has this typedef uint8_t byte;. So for an Arduino, using byte is OK.

Performance won't necessarily be better with byte instead of int - see amended post.

As Ignacio has rightly states, it's basically because they don't know better.  And they don't know better because the people who taught them (or the resources they used when learning) didn't know better.
Much of the Arduino code and tutorials are written by people who have never had any training in programming and are very much "self taught" from resources by people who themselves are very much self taught with no proper training in programming.
Many of the snippets of tutorial code I see around the place (and especially those that are only available within YouTube videos --- urgh) would be a fail mark if I were marking them in an exam.
Yes, a const is preferred over a non-const, and even over a #define, because:

A const (like a #define, unlike a non-const) does not allocate any RAM
A const (like a non-const, but unlike a #define) gives the value an explicit type

The second point there is of particular interest.  Unless specifically told otherwise with embedded type-casting ((long)3) or a type suffix (3L) or the presence of a decimal point (3.0), a #define of a number will always be an integer and all mathematics performed on that value will be as if it were an integer.  Most of the time that's not a problem, but you can run into interesting scenarios when you try to #define a value that is larger than an integer can store, such as #define COUNT 70000 and then perform a mathematical operation with other int values on it.  By using a const you get to tell the compiler "This value is to be treated as this variable type" - so you would instead use: const long count = 70000; and all would work as expected.
It also has the knock-on effect that it checks the type when passing the value around the place.  Try passing a const long to a function that expects an int and it would complain about narrowing the variable range (or even completely fail to compile depending on the scenario).  Do that with a #define and it would just silently carry on giving you the wrong results and leave you scratching your head for hours.

It's worth noting that a const variable may require RAM, depending on the context, e.g. if it's initialised using the return value from a non-constexpr function.

Similarly, const int foo = 13; bar(&foo); will definitely require the compiler to allocate actual memory for foo.

If you define a macro that expands to a value that won't fit in an int the compiler treats the value as having the smallest type in which it will fit (modulo rules about signed vs. unsigned). If you're on a system where int is 16 bits, #define count 70000 will result in count looking like a long, just as if it had been defined as const long count = 70000;. Further, if you pass either of those versions of count to a function expecting int, any sane compiler will treat them the same.

I agree with @PeteBecker - a construct like #define COUNT 70000 does not truncate into an int, but the compiler treats it as a type large enough to hold that number. It is true that it might not be obvious when you use COUNT that it isn't an int, but you could say the same thing about a const long anyway.

"a #define will always be an integer" That is not true. You are taking the rules of integer literals and applying them to preprocessor macros. It's like comparing apples and pop music. The expression COUNT in your example is replaced before compilation with the expression 70000, which has a type defined by the rules of literals, just like 2 or 13L or 4.0 are defined by the rules of literals. The fact that you use #define to alias those expressions is irrelevant. You can use #define to alias arbitrary chunks of C code, if you like.

As a consequence your final paragraph is wrong too. It seems like you fundamentally misunderstand the preprocessor. A shame because the rest of the answer was great!

I don't understand what you're on about there. I am not applying anything to macros. I am applying literal rules to the results of the macro expansion - that is why I talk about explicit casting and type suffixes within the macros.

As a 2-week newbie to Arduino I'd pick up on the general idea of Arduino being occupied by non-programmers. Most sketches I have examined, including those on the Arduino site, show a total lack of order,  with sketches that do not work & barely a coherent comment in sight. Flow charts are non-existent, and the "Libraries" are an un-moderated jumble.

My answer is... they do it because it works. I'm having a hard time not asking a question in my answer such as "why does it have to be 'wrong'?"

One hallmark of a good programmer is that the code always reflects their intentions.

We're still talking about Arduinos, right? ;)

Arduino already has a bad rep in the larger EE community because of the mediocre-to-terrible hardware designs put out by the community. Shouldn't we try to give a sh*t about something?

I guess I've come to appreciate the 'just enough' approaches that are common in the Arduino make community. Most projects aren't going to involve risk of life or finances so what difference does it make if Blink.ino uses an int or a const int? Those who stick with it and gain experience will learn when it matters and when it doesn't.

"Most projects aren't going to involve risk of life or finances..." No surprise there. Who would want to involve Arduino where there's any chance of risk after looking at the community at large.

It's 'wrong' not because it doesn't work in one particular situation but because, compared to doing it 'right,' there are more situations in which it doesn't work. This makes the code fragile; changes to the code can cause mysterious failures that eat up debugging time. The compiler's type checking and error messages are there to help you catch those sorts of errors earlier, rather than later.

source: Stack Exchange

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

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

sort: votes


text:
Arduino LCD Simple Problem
Hi my lcd doesnt display that i was expected. Can anyone help me???
RS-->22
RW-->GROUND
E-->23
D4-->24
D5-->25
D6-->26
D7-->27
    #include <LiquidCrystal.h>

LiquidCrystal lcd(22, 23, 24, 25, 26, 27);
void setup() {

lcd.begin(16,2);

lcd.setCursor(0,1);
lcd.print("Hello!");
delay(1000);
}
void loop() {
lcd.setCursor(0,1);
lcd.print(millis()/1000);
}

Have you tried turning the trim pot? It could be a contrast issue

yes. i add lcd clear commant and shakes the cables and the problem is solved!

I Had a similar problem with a different display, It looks like you are printing the value without clearing the display so all the numbers print on top of each other creating those squares. try adding lcd.clear() in the loop to clear the display before it prints another value.

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


text:
How to develop or edit an Arduino library?
I'm not sure if I should split this question in two.
I had to edit some libraries and I plan to make some myself but didn't try yet.
Editing a library seems very laborious comared to editing a sketch.
I have to use an external editor and then compile on the Arduino IDE with the help of a test sketch.
I wish to use the Arduino IDE to edit the libraries but it seems it is not easy, maybe in future reales it is supported.
The libraries used to be on %home%/Arduino/libraries/etc. but now I have to edit some located at %appdata%\Arduino15\packages\esp8266\hardware\esp8266\1.6.5-947-g39819f0\libraries and it seems these packages might get updated so maybe it is not a good idea to edit them there but I am not sure.
What about GitHub and conflicts? I clone the library and edit it but then I have two versions and you can't choose one of them. So I have to delete the original from the arduino instalation or wherever it is to avoid the conflict.
I also wish to post the progress to GitHub and maybe receive collaboration there. Do you have any hint about the clone process or something to avoid any trouble with it?
And what about the .h/.o? Arduino precompile the headers on startup so if I edit a .h I have to find and delete the .o or restart the IDE.
How do you do all of this? Is there any trick that helps?
Thank you.

I know this http://playground.arduino.cc/Main/CustomizeArduinoIDE (very raw information, just a specification) and this http://forum.arduino.cc/index.php?topic=37294.0 (old).

I'm not accepting any answer because they are only focused on versioning/git/github fork->edit->share and I am very interested on all the things that I have to do to make the development. Any good editor if Arduino IDE is not an option? Why is not an option? Where should I place the git clone to override any other version of the library? or should I delete them? That kind of things. Thank you.

There is one component of your question that remains unanswered:

I wish to use the Arduino IDE to edit the libraries but it seems it is not easy, maybe in future reales it is supported.
Any good editor if Arduino IDE is not an option? Why is not an option?

The rest of your questions already have good answers so I'll limit myself to explaining how the Arduino IDE 1.6.5-r4 and newer can be used to edit libraries:
Copy the library you want to modify to {sketchbook folder}/libraries or create a new folder at that location if you're writing a library from scratch. You can find the location of {sketchbook folder} at File > Preferences > Sketchbook location.
Create a file that matches the folder name that contains the source files with the .ino extension. For example:
{sketchbook folder}
|_libraries
  |_FooBar
    |_FooBar.ino
    |_FooBar.h
    |_FooBar.cpp

or:
{sketchbook folder}
|_libraries
  |_FooBar
    |_library.properties
    |_src
      |_src.ino
      |_FooBar.h
      |_FooBar.cpp

This dummy .ino file is necessary in order to open the library source files in the Arduino IDE but will not actually be used as part of the library. You can leave it blank. I like to use this file as a "to-do" list for my development work. I add this filename to .git/info/exclude so that it will not be tracked as part of the repository. It's also possible to use this file as a sketch to test the library with. Just remember to use the local file include style:

#include "FooBar.h"

Note that you will only be able to edit the files that are in the same folder as the .ino file via the Arduino IDE. Luckily most Arduino libraries place all their source files in a single folder so this is not much of a limitation. If you wanted to edit a library that has source files in multiple folders you could always put a dummy .ino file in each folder and open them in separate IDE windows.
Add a file named .development to the library root folder. This is necessary because normally the Arduino IDE does not allow saving to the library folders or the examples folder to prevent accidental modification of the example sketches. Using Windows Explorer (and possibly others), you will find that you are not allowed to create files that start with a dot. You can create the .development file using a text editor or the command line. The contents of the file don't matter, only the presence of the file. Note that you should not publish the .development file to repositories that will be included in the Arduino IDE Library Manager as the file will cause the library to be skipped by the job that fetches releases. I also add this filename to .git/info/exclude.
If the library does not already contain one, add a library.properties file to the library root folder. You can find the correct format of this file in the Arduino Library Specification:
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#libraryproperties-file-format
Now the structure of the example libraries above would look like this:
{sketchbook folder}
|_libraries
  |_FooBar
    |_.development
    |_FooBar.ino
    |_FooBar.h
    |_FooBar.cpp
    |_library.properties

or:
{sketchbook folder}
|_libraries
  |_FooBar
    |_.development
    |_library.properties
    |_src
      |_src.ino
      |_FooBar.h
      |_FooBar.cpp

Restart the Arduino IDE if it's running.
After doing this, when you open any of the source files of the library with the Arduino IDE, all source files in the folder will be opened and you can edit and save them as you would a sketch.

I'm not accepting any answer because they are only focused on versioning/git/github fork->edit->share and I am very interested on all the things that I have to do to make the development.

I will run through the basics of making a library. It's really quite simple, and they persist through upgrades to the IDE.
Let's imagine I have a useful function (or lots of functions) that I want to use in lots of sketches. For example, something that blinks an LED:
void blinkLED (const byte which, const int times)
  {
  for (int i = 0; i < times; i++)
    {
    digitalWrite (which, HIGH);
    delay (500);
    digitalWrite (which, LOW);
    delay (500);
    }  // end of for loop
  } // end of blinkLED

And some test code:
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (13, OUTPUT);
  blinkLED (13, 5);
  }  // end of setup

void loop ()
  {
  }  // end of loop

Make a library
To turn that into a library we need three steps:

Make a folder for the library. This should be placed inside the libraries folder in your sketchbook folder. This folder:

In my case: /home/nick/sketchbook/libraries. It does not go into anywhere associated with the IDE download.

but now I have to edit some located at %appdata%\Arduino15\packages\esp8266\hardware\esp8266\1.6.5-947-g39819f0\libraries

No, not there.
I will call my library blinkLED. So I make that folder, which is now: /home/nick/sketchbook/libraries/blinkLED

Make a function prototype for any functions your library is going to "expose" to the end-user, and put that into a .h file, like this:
blinkLED.h
#include <Arduino.h>

void blinkLED (const byte which, const int times);

Important: You must include <Arduino.h> as in the example, or you will get compile errors.

Put the C++ code into a .cpp file, like this:
blinkLED.cpp
#include <blinkLED.h>

void blinkLED (const byte which, const int times)
  {
  for (int i = 0; i < times; i++)
    {
    digitalWrite (which, HIGH);
    delay (500);
    digitalWrite (which, LOW);
    delay (500);
    }  // end of for loop
  } // end of blinkLED

Important: You must include the .h file created in step 2, as in the example, or you will get compile errors.

That's it! Restart the IDE now so it notices the new folder with the library in it.
Now our test sketch can just use the new library.
#include <blinkLED.h>

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (13, OUTPUT);
  blinkLED (13, 5);
  }  // end of setup

void loop ()
  {
  }  // end of loop

Testing
For testing I just keep the library files open in a separate text editor (I am using Geany these days, but whatever your favourite editor is).
You can make changes to the library source and save them. You do not need to restart the IDE if you do this. It will always pick up the latest version.
In the IDE you alter your calling code, upload and test. It is really quite fast and simple.

Git
Once you have put a bit of work into your library you probably want to put it under source control. Using a terminal/command window, navigate to the library folder and put it into a Git repository:
git init
git add *.cpp
git add *.h
git commit -m "Initial commit"

I am going to split my answer into 2 parts
1. Editing an Arduino library:
It doesn't matter how you edit your library, you can do it in notepad for all I care. It just doesn't matter.
2. Version Control:
Git is a version control software used to track software/code changes and ensure that people don't screw up the files by adding code that's not tested.
If you want to contribute to a certain library here is what you need to do
Step 1: create a github.com account since most people host it there
Step 2: fork the required library, this basically creates a clone of the library in your account.
Step 3: clone the forked repo from your account to your computer. So now you have the files on your computer to mess around
Step 4: create a branch a branch is your personal workspace to mess around as you wish. The advantage of have a branch is that if you screw up.  You could always go to the main branch (master) and start over :)
Step 5: once you are done editing and testing and are sure the file is perfect, you commit your changes and then you create **pull request ** with the original author so  that he can review your work and if he is happy will accept your change and merge it to master.
Note: read about adding remote to your git repo and fetching from remote repo, once you understand these basics you will understand the power of git :)

This is the common process for all open source projects, not just arduino (example using github svn)
1. Fork a project
When you fork a project, you create a separate "project" of your own from the original project on the SVN.
2. Clone your project
Clone your fork down to your local directory so you can make changes and use it.
git clone https://github.com/<your-repo>/<project>

3. Push changes up
Push your changes up to your repo regularly. At this point your changes are not affecting the original project in any way.
git push -u origin <branch>

4. Pull updates from the original project
The original author(s) can make changes and improve his/her code. You can make sure your fork is up-to-date by pulling/merging those updates into your fork.
git pull https://github.com/<original-author>/<repo> <branch>

Some time there will be conflicts, which are normal since your changes and the author's may collide. You'll be prompted to fix the conflicts before committing your changes.
<<<<<<< HEAD
    # this portion is your code at the current HEAD
=======
    # this portion is the one from the original branch master
>>>>>>> master

You'll have to fix the conflict manually by either accepting your change and deleting the master's or deleting your change, and get rid of the marks before committing to your svn.
4. Creat a pull request
After using your supercharged version of the project for a while, you think it might be useful for others. To contribute, you create a pull request to the original author. It works similar to you pulling in his changes, just he will review your changes then merge in.
All the while, others can do all these with your project too!
To edit the project/make changes, you can use any editor to open your local project, code away, save it and commit. It is not ideal to use Arduino IDE since it is an environment to run the code (but otherwise possible).


text:
MCP23S17: Programming IODIRx-Register works in loop(), but not in setup()

I use a single MCP23S17 connected to an Arduino Uno. I use its port B for output and port A for input. When I first started to use this device I noticed, I could read pins, but using them as output failed. After a lot of debugging and trial and error I found out, that the IODIRx Register was never programmed. I then copied the respective code from the setup() routine — where it belongs IMHO — to the loop() routine.
And miraculously the IODIRx Register was written correctly. The code below contains the IODIRx programming snippet in the setup() as well as in loop(). But only in loop() it yields an effect. This means: The output will work only after the first traversal of loop() in my example.
The rest of the setup() routine obviously works, which means it is called at least. SPI is initialised correctly there.
This drives me nuts. What the hell is a setup routine for, if you can't setup things there. And why on earth doesn't it work then? I don't do strange things there.
#include <Arduino.h>
#include <Wire.h>
#include <inttypes.h>
#include <SPI.h>
#include "flanschcontrol.h"
#define DEBUGOUTPUT
#define PROTOV2
typedef int elem_type;
#define ADDRESS (0)
#define    OPCODEW       (0b01000000)  // Opcode for MCP23S17 with LSB (bit0) set to write (0), address OR'd in later, bits 1-3
#define    OPCODER       (0b01000001)  // Opcode for MCP23S17 with LSB (bit0) set to read (1), address OR'd in later, bits 1-3
#define    ADDR_ENABLE   (0b00001000)  // Configuration register for MCP23S17, the only thing we change is enabling hardware addressing
uint8_t PexSSPin=7;

void setup() {
   Serial.begin(9600);
    pinMode(PexSSPin, OUTPUT);
    SPI.begin();
    SPI.setClockDivider(2);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);

    delay(1000);
    PORTD &= 0b01111111;    // Slaveselect low

    SPI.transfer(OPCODEW | (ADDRESS << 1));
    SPI.transfer(IODIRB);
    SPI.transfer(0b10101010);
    PORTD |= 0b10000000;    // Slaveselect high
    delay(1000);
}

void loop()
{
    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
    SPI.transfer(GPIOB);
    SPI.transfer(0b00000000);
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.println("0");
    delay(1000);

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
    SPI.transfer(GPIOB);
    SPI.transfer(0b11111111);
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.println("ff");
    delay(1000);

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
    SPI.transfer(GPIOB);
    SPI.transfer(0b00001111);
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.println("0f");
    delay(1000);

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
    SPI.transfer(GPIOB);
    SPI.transfer(0b11110000);
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.println("f0");
    delay(1000);

    int value;

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODER | (ADDRESS << 1));  // Send the MCP23S17 opcode, chip address, and read bit
    SPI.transfer(GPIOA);                      // Send the register we want to read
    value = SPI.transfer(0x00);               // Send any byte, the function will return the read value (register address pointer will auto-increment after write)
    value |= (SPI.transfer(0x00) << 8);       // Read in the "high byte" (portB) and shift it up to the high location and merge with the "low byte"
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.print("pindata: ");
    Serial.println(value);
    delay(1000);

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));
    SPI.transfer(IODIRB);
    SPI.transfer(0b10101010);
    PORTD |= 0b10000000;    // Slaveselect high
}

Definitions of some preprocessor thingies:
#define    IODIRA    (0x00)      // MCP23x17 I/O Direction Register
#define    IODIRB    (0x01)      // 1 = Input (default), 0 = Output
#define    GPIOA     (0x12)      // MCP23x17 GPIO Port Register
#define    GPIOB     (0x13)      // Value on the Port - Writing Sets Bits in the Output Latch

Please show the declarations for IODIRB, GPIOA, GPIOB.

@NickGammon: I added the defines.

I have one question. Once you set the PinMode of an expander then can you change the mode without giving a reset? I mean, I have to use 3 expanders for controlling an SRAM: on one MCP I have the data lines, on the second one I have the control signals and on the last one I have the address lines. Firstly, I do a SRAM_WRITE, so I need the pins of the first expander to be OUTPUTs,then I do a READ_SRAM so a need the pins of the first expander to be INPUTs. Can I change the mode from output to input? Then I am trying to check the signals with an oscilloscope. When a do a pinMode OUTPUT of the expa

@Gabriele: Why should you have to do a reset to change pin behaviour? But please don't use the comment section to ask new questions.

You've fallen for the old "slave select pin is already low" trick!
Let me show you. First we add a line to bring pin 2 high before starting the sequence (for logic analyzer triggering):
pinMode (2, OUTPUT);     // <--- pin 2 output
delay(1000);
PORTD |= bit (2);        // <--- pin 2 HIGH
PORTD &= 0b01111111;     // Slaveselect low
SPI.transfer(OPCODEW | (ADDRESS << 1));
SPI.transfer(IODIRB);
SPI.transfer(0b10101010);
PORTD |= 0b10000000;    // Slaveselect high
delay(1000);

This is the logic analyzer output of running your sketch:

Notice how SS is low all the time, and thus the chip does not respond to the command?

Now we add a line before the SPI.begin
PORTD |= 0b10000000;    // Slaveselect high
SPI.begin();
SPI.setClockDivider(2);
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);

Now look at the results:

This time you get the transition of SS from high to low, the chip notices it, and we have a valid SPI transaction.
So without bringing SS high, the first thing you sent was always going to fail.

It was nothing to do with it being in setup - it couldn't be. After all the logic is basically this:
init ();
setup ();
while (true)
  loop ();

Personally I wouldn't hard code all those bit patterns throughout the code. What if you change the slave select pin one day?
How about:
digitalWrite (PexSSPin, LOW);
/// write to chip
digitalWrite (PexSSPin, HIGH);

Isn't that much more readable? And easier to change later?

Hahahaaa, that's good. Works flawlessly now. My code looks so awful due to all the debugging steps I took. In the beginning it was a nice class with everything in it's place. Finally I unrolled all crucial parts into the main loop and used constants everywhere to rule out all other programming failures. Thanks for riddling this for me.


text:
Sending Data between two boards using SoftwareSerial
I'm attempting to connect two Arduino boards to eachother using SotwareSerial as the title suggests!
The two boards are 1) Arduino UNO and 2)MultiWii Controller (MWC) FLIP 1.5 (Uses ATMega328 chip).
The idea, is to get Serial TX on the "MWC" FLIP 1.5 to Serial RX on the UNO.
These are my connections thus far:
MWC Pin ------->UNO Pin
Digital 3 (TX)--->Digital 6 (RX)
Digital 9 (RX)--->Digital 9 (TX)
This is the code on the MWC Chip -- the TX chip. (NOTE: These functions are called to run in a header file)
#include "attout.h"
#include "SoftwareSerial.h"

SoftwareSerial altSerial(9,3); // RX=9 TX=3

void startaltserial(){

  altSerial.begin(9600);

}

void attout(){

pinMode(3,HIGH);
pinMode(9,HIGH);

  altSerial.print('1');

}

NOTE: I also tried altSerial.write('1'). Same result (or lack of one).
Then, the RX Code on the UNO Board:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(6,9); // RX=6 TX=9

void setup()
{
  // Open serial communications:
  Serial.begin(9600);

  // Set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

}

void loop()
{
  while (mySerial.available()>0) {
    Serial.println(mySerial.read());
  }
}

When I open Serial Monitor for the UNO board, I get nothing but zeroes streaming down. Curiously, if I disconnect the TX OUT wire from MWC, the Serial stream stops!
This means, as far as I can tell, that the UNO is doing its job of receiving, and the MWC is doing it's job of transmitting, but something is wrong with the formatting inbetween, so that I end up with zeroes.
Additionally, if I change the baud rate, the Serial Monitor output changes. When I go to 1200 baud, I get nothing but '4' followed quickly by '1' and then carriage return, so it looks like '41'.
Hope we can find a solution to these quandaries. My next course of action is trying I2C, but I'm not sure about it yet...

Do you have a common ground connection? Also please edit the connections in your question you have mentioned TX for both the MWC pins

What's pinMode(3,HIGH); doing? Pinmode accepts INPUT or OUTPUT, not HIGH. Also this line isn't needed.

They are sharing a common ground.. Both plugged in via USB to my laptop. And also, when they're both powered by a battery and the UNO is connected to my laptop, I still get Serial Monitor reading zip. OP edited.
pinMode(3,HIGH); was my attempt to make sure that the pin was actually enabled... I wasn't sure if it was super required or not. Thanks!
Any other ideas?

Out of curiosity, why are you not using hardware serial?

Well, I could use hardware serial on the UNO board, but on the MWC board the hardware serial is already being used by a telemetry radio, so I have to compromise.

Your problem here is that you are streaming out serial data non-stop.
See my answer in this thread: What is Serial.begin(9600)?
Without having a pause, the receiver just latches onto somewhere in the middle of the data stream and tries to make sense of it, often unsuccessfully.
If you add one "character time" delay to the sender, the receiver works fine:
  altSerial.print('1');
  delay (2);

It might get the first one wrong, but now the receiver has 2 ms to resynchronize on the data stream. At 9600 baud the delay should be 1/960 (second) at least, I used twice that to be sure.

Thanks for your fantastic reply! I read the answer in the other thread, and learned a lot there. What you say here helps tremendously in my understanding, and I have attempted the 2ms delay in the sender, but regrettably I am still getting a stream of zeroes in the Serial Monitor... Could this perhaps be a clock sync error? I'm not certain if the clocks on both boards have the same rate. If not, any other suggestions? Thanks Mr. Gammon!

I don't know what speed the MWC runs at, but it seems odd that you are getting zeroes. Either you get data or not, it shouldn't turn 1 into 0.

Thanks Nick! This last comment you made led me to go through all of the MWC's other code (pretty time consuming.. phew!). Turns out it was using direct manipulation of the pins, and bit banging PWM on the pin I was trying to TX out of. All my commands were overridden by the 0 PWM signal. Thanks again, and have a great rest of the weekend!


text:
Motion sensor large areas
I'm looking to build a motion sensor which detects if an object is in the monitored area. Doing some researched I found out that I can use PIR motion sensor for this but it seems the area it monitors is pretty small.
I need something that can monitor about 3 feet x 1 feet area. Is there something else that I can use for this?
My goal is to light up some LED lights when an object is detected in that area.
Thanks in advance.

What kind of object? What are its dimensions compared to the area it's in?  Is it an enclosed area or an unbounded area within a larger space?

I wanted to mount on my garage's ceiling and monitor when a car is in the monitored area

I would strongly suggest a ultrasonic ping sensor.  It is low cost (under $3 on E-Bay) and will give you an accurate reading.
Here is an example:
http://www.instructables.com/id/Ultrasonic-Garage-Parking-Assistant-with-Arduino/
I would use an Arduino Nano on e-by if you want to keep total cost under $5.

A standard PIR motion sensor will work fine.  It can monitor motion in a very room.  You just need to make sure the PIR sensor is far enough away.
Here is one article that states it should work up to 10 meters away.
https://www.mobotix.com/eng_US/Support/FAQ/Configuration2/What-is-the-range-of-the-PIR-Passive-Infrared-motion-detector
Note that the device that the PIR sensor is mounted on must be stationary.  It will not work on a robot of anything that is moving.

Also, note that the object sensed by the PIR must be hot, and that object must be moving, not stationary.  The PIR works by sensing changes in infra-red light between two overlapping fields of view. That's why you can sit in a room with a PIR and it's normally off. As soon as you stand up or otherwise move it'll activate.

It sounds like what you want is an ultrasonic distance ("ping") sensor over the area where the car is.
When the car isn't there it will measure the height of the garage (say 3m).  With the car there it will measure the distance from the ceiling to the top of the car (say 1.5m).
Ultrasonic sensors have a limit to their range.  The cheap ones are usually around 2m, so may not work for you, or you may get away with it if it will return "infinite" for anything outside its range, in which case anything that is not "infinite" will be something present under the sensor.

What's the coverage of a ping sensor? can it monitor specified area or it's just one straight line ?

It's roughly a straight line, but a car is a pretty large object - bigger than the 3' by 1' area you mention.  If it's there it'll be filling the area, so even with a 1µm wide laser as the sensor it'll still be present.

What if I wanted to monitor a specified area rather than a straight line ? 3' by 1' was something I specified so that it can be placed in the middle of the garage.

Pressure sensor under the floor? Array of ping sensors? Grid of infra-red beams intersecting the area? For these kind of things it can often be easier to sense an entry or exit to an area rather than the area itself.


text:
Making CS (chip select) work in SPI (for and SD card and OLED)

I'm working on a project that will log data to an SD card and display a user interface on an OLED. The SparkFun OLED breakout was super easy to set up. I was also able to get the SD-Card library working independently, though that was harder.
The trouble is when I combine these examples the SD card only writes during "setup" after that it isn't writing to the SD card as the loop continues. The OLED still works just fine.  I've read up on SPI a bit and tried various things to get "chip select" to work (I suspect this is the problem) I even tried setting the CS pins to LOW or HIGH using digitalWrite, but this had no impact.
My pins are connected as follows:
          SD CARD      OLED
MOSI        A5            A5     same pin
MISO        A4            --     just SD connected
SCK         A3            A3     same pin
CS          A1            A2     different pins

The SD card writes in the main loop if I comment out all of the code that runs the OLED. The OLED works either way.  What could I try next?
Here is the code:

 #include "application.h"
 #include "sd-card-library/sd-card-library.h"
 #include "SparkFunMicroOLED/SparkFunMicroOLED.h"
 #include "math.h"

 //////////////////////////////////
 // MicroOLED Object Declaration //
 //////////////////////////////////
 // Declare a MicroOLED object. If no parameters are supplied,
 // default pins are used, which will work for the Photon Micro
 // OLED Shield (RST=D7, DC=D6, CS=A2)
 // Since I use A1 as the chip select pin for the SD card these
 // defaults seem fine.

    MicroOLED oled;

 // Declare a file object?

    File myFile;

 // These are the pins for the SD card. A5, A4, and A3 are all
 // shared by the OLED.

    const uint8_t chipSelectSD = A1;
    const uint8_t mosiPin = A5;
    const uint8_t misoPin = A4;
    const uint8_t clockPin = A3;

 ////////////
 // setup //
 ////////////
 void setup() {
  delay(500);

  SD.begin(mosiPin, misoPin, clockPin, chipSelectSD);
  File dataFile = SD.open("data.txt", FILE_WRITE);
  dataFile.println("this text was printed to the SD card during setup");
  dataFile.close();

  oled.begin();  // Initialize the OLED
  oled.clear(ALL); // Clear the display's internal memory
  delay(1000);  // Delay 1000 ms
  oled.clear(PAGE); // Clear the buffer.
  randomSeed(analogRead(A0) + analogRead(A7)); //seed to make test pattern random.

               }//end setup

//////////////////
// main loop //
//////////////////
void loop()  {

  SD.begin(mosiPin, misoPin, clockPin, chipSelectSD);
  File dataFile = SD.open("data.txt", FILE_WRITE);
  dataFile.println("The text was added during the loop.");
  dataFile.close();

//test the display with text and pixels.
  printTitle("Pixels", 1);
  for (int i=0; i<512; i++)
  { oled.pixel(random(oled.getLCDWidth()),  random(oled.getLCDHeight()));
  oled.display(); }
   delay(9000);

               } //end loop

//-------------------------//
// function to print titles //
//-------------------------//
  void printTitle(String title, int font) {
  int middleX = oled.getLCDWidth() / 2;
  int middleY = oled.getLCDHeight() / 2;
  oled.clear(PAGE);
  oled.setFontType(font);
  // Try to set the cursor in the middle of the screen
  oled.setCursor(middleX - (oled.getFontWidth() * (title.length()/2)),
  middleY - (oled.getFontWidth() / 2));
  // Print the title:
  oled.print(title);
  oled.display();
  delay(1500);
  oled.clear(PAGE);
                                           } //end title function

This is how the SD card is hooked up.
  oled.begin();  // Initialize the OLED

Any attempt to use the SD card after this line will not work. I've looked for something like "oled.end()" but have not found a way to reset to the state where the SD card works.
I have tried commenting out all of the OLED code and then the SD card writes fine in the main loop. So, I started adding the OLED code back in. This line of code breaks the SD card writing in the main loop:

Try interfacing with the OLED using I2C. That might avoid the contention with the SD card.

Try explicitly setting the CS pin used by MicroOLED oled(rst, dc, cs)

I2C is notoriously buggy on this micro. I'll see if anyone has it working.
I added  "MicroOLED oled(MODE_SPI,D7, D6, A2);"  it still has the same error.

There are devices that "break" the bus by not being able to work on systems that have more than one SPI slave. In that case you can do nothing to fix it but use devices that don't have this behaviour.

I wanted to write to 2 SD cards simultaniously with one Arduino Mega. Used all the relevant pins including CS on 53 for the first SD card and 13 for the second SD card.  Can be any digital pin I think but this one makes the LED blink too).  Before the SD.begin(13) of the second SD card I do a digitalWrite(53,HIGH).  That de-selects the first SD card. and digitalWrite(13,HIGH) when switching back to SD.begin(53) I do a digitalWrite(13,HIGH).  This works real fine.
Now I tried to impelment this on a D1-Mini.  Cannot get it to work.
SD.begin(D8) starts the first SD fine.  By doing a digitalWrite(D8,HIGH) I tried to de-select SD1 and with SD.begin(D4) opened the second card. Strangely enough it still opens the first SD card again regardless of the pinnumber-parameter.
Maybe the SD library for ESP8266 remembers the first setting of the CS and later settings og the parameter with fifferent pinnembers are ignored???

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


text:
Which board/shield to generate (non-PWM) analog outputs?
I am currently building a project involving a laser scanner (two galvanometers with mirrors that deflect a laser beam) that I want to control. The galvos need +-10V differential signals (and I'd like to have a least 12Bit) that I want create with some small board.
Most Arduinos I know use PWM to create an analog output which is not usable for this project. I found the Teensy3.1 which has at least one 12Bit DAC so that also doesn't work. An alternative would be a DAC breakout board like "MCP4725" but it would be nicer to just have a single board with no additional parts.
The best thing would be a small board with already two 12Bit DACs. (even If I had to upscale the voltage +-10v)
Is there a board I haven't found so far? Or have I missed a completely different approach?

Why is filtering the PWM not an option?

Would it be a solution? I'm not that deep into electronics, so it could possibly be a solution for me. How does it work?

Adding a capacitor to smooth out the PWM?

For 12-bit dual DAC you want the MCP4822 which has two channels of 0-4.095V in 1mV steps.
The output of that you would then need to pass through a suitable amplifier arrangement with an op-amp giving a gain of 5 and adding an offset of -10V.  The gain would change the 0-4.095V to 0-20.475V, and the -10V offset would change that to -10V to +10.475V.  If you want to get more precise you could use an offset of -10.2375V (it's not easy to make an offset voltage that precise) then you would get -10.2375V to 10.2375V in 12-bit resolution.
It's doubtful you'll find a board already made up with that specific arrangement (it's fairly specialised) but it's not something that's hard to make - all the components are available as DIP or other through hole components, and the circuit for the amplification stage is pretty simple (check for non-inverting op-amp circuits online, there's millions), so building it up on strip board or matrix board would be easy enough.

Thanks! Did you already know this component or how did you search for it? I only found SMD-parts (like the MAX5322) when searching and I don't have the equipment for them.

It's a component I know well. I have a number of them in my bits box, they're very useful.

If you already used it, could you maybe check if I understand the chip correctly: To communicate, I send two-byte messages as described on page 22 and select the output via bit 15, set Bit 13 to 1 to get the 4.095-Range, SHDN(12) to 1 to enable the output and fill 11-0 with my data. To synchronize the outputs, I set the LDAC-Pin(5) to high (VDD, Pin1), write messages for both outputs, set it back to VSS (Pin7) and then the output-voltage is updated.

From what I recall that sounds right, Yes.

I just found thist library: http://hacking.majenko.co.uk/MCPDAC :) I think that's an easier way to use the chip

You might find thats out of date. Check github for the latest version

https://github.com/MajenkoLibraries/MCPDAC


text:
How do pins on an arduino mega 2560 work?
I got a copy of Arduino from a local retailer here (it's a local copy and I'm pretty confused with how the pins actually work).
I know basic electronics so far, there should be two pins for every node one acting as the negative terminal and other as the positive terminal. If I were to connect an LED with my Arduino board which pins would I be utilizing?
Here let me tell you how pins are arranged on mine:
IOREF                                                                         GND

                                         13
RESET                                                                         12
3.3V     //this left group marked power                                        .
5V                                  //right group marked PWM                   2
GND            //right groupmarked communication                          TX0 -1
GND                                                                       RX0- 0

V1N                                                                       TX3-14
                                                                         RX2 -15
A0                                                                         ..
A1                                                                      SCL -21
..   //THIS left GROUP MARKED ANALOG IN
A7

A8
A9 //I believe it is part of the above group
..
A14
A15

     //the pins below marked DIGITAL
     52-50-`48-46...........................................................22`

there should be two pins for every node one acting as the negative terminal and other as the positive terminal.

No, there is one pin per node, and a common "Ground" pin which is the negative terminal. On your Mega2560 are 5 ground pins (effectively equivalent because they are connected). They are circled on the photo below, and marked GND on the board.

As Majenko says in his answer you must use a resistor in series with any LED you connect, or you will damage both the LED and the processor.
You may find a "breadboard" handy for making connections, most prototyping boards have a long connected strip for sharing the Ground wire between different places, like this:

The continuous blue lines indicate pins which are connected together (for Ground) and the continuous red lines are connected together for +5 V (usually).

Btw can you tell me why there are two pins on the bottom horizontal row?

Just for convenience. You often want an extra ground pin, for example if you are trying to connect up two LEDs.

Secondly, yes each pin can be set as input or output but is there any specific difference in the type of pins?

Some of the pins can optionally be used for extra hardware-supported features.

PWM: Pulse-width-modulated output
COMMUNICATION: Serial input/output (4 serial ports)
ANALOG IN: Analog-to-digital converter (ADC) input
DIGITAL: Digital (not analog) input/output
SDA/SCL: I2C communications
Pins 50-53: SPI communications (not marked on the board)

However all pins, as you noted, can - if you wish - be used for digital input or output.

Great. Thank you. Btw can you tell me why there are two pins on the bottom horizontal row? I mean the grounds on left and right are singled pin but on the horizontal row they are double pinned?
Secondly, yes each pin can be set as input or output but is there any specific difference in the type of pins? If yes, what? If not, why are they categorized as PWM, COMMUNICATION,ANALOGI IN,and DIGITAL?

This is another example of a lengthy answer, which doesn't get a single upvote, nor an accepted answer vote. So it is recycled by "Community" as unanswered. IMHO it was answered.

One good turn deserves another.

Any IO pin can be set to either be an input, where it reports to your program if the voltage present on that pin (relative to ground) is above or below a certain threshold (HIGH or LOW voltage), or it can be an output, where it can either be set to be a HIGH output (pin is connected internally to +5V) or a LOW output (pin is connected internally to GND).
To drive an LED you would connect one side of a small resistor (say 470Ω) to any IO pin you choose.  The other side of the resistor would connect to the anode of the LED.  The cathode of the LED would then connect to ground.  When you set the IO pin to HIGH it will provide 5V to the LED through the resistor (which is needed to limit the current as the LED is a non-linear, current driven, component) and the circuit is completed by the return path through ground.

Note that you must not exceed 40mA going into or out of any IO pin, and you should not exceed 25mA going into or out of any IO pin.  The total current going into or out of all IO pins must not exceed 200mA.

Understood. Thanks, for the part where you said a resistor must be used with an LED can you tell me which formula do you use to calculate the required resistance?
I=V/R
R=V/I
R=RequiredVoltage/RequiredCurrent Is this it?

I'm upvoting this answer to stop this question staying as unanswered. Even though I posted my own answer. :)

@NickGammon I have noticed the Arduino community is much less inclined to upvote or accept answers than other communities. Just looking at the question list you see much lower numbers in general here than in for example the Photography community.

I've noticed that too. My fairly minor contributions to other SE sites (eg. English) get quite a few votes, even for a short post, but a lengthy one here, complete with schematics, photos, code, etc. can get completely ignored. It is a little off-putting.

"The total current going into or out of all IO pins must not exceed 200mA."  For a '2560, the total is actually 800mA.  200mA per VCC/Gnd pin, the Mega has 4 of each. This was confirmed with Atmel tech support some number of years ago and posted at Arduino.cc


text:
Need assistance with program for POV Project
I've created a very basic POV project.
It has a 12V DC motor with a piece of wood on it.
The wood has 6 LEDs on it as well as a copper ring.
The power is delivered to the LEDs from brushes connecting to the copper ring and from the shaft of the motor (the ground is attached to the base of the motor.) I'm using a TCRT5000L Sensor to count the RPM and have attached the LEDs to pin 13 and ground of the Arduino. (I've attached white tape to one side of the wood so that the sensor only counts one rev.)
I need help (please) with the program.
This is the code that I am using:
int pin = 13;
volatile  int tcnt = 0;
volatile  int lastcount = 0;
volatile int state = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(pin, OUTPUT);
  attachInterrupt(1, blink, RISING);
}

void loop() {
  Serial.println(tcnt);
  if (tcnt != lastcount)
  {
     digitalWrite(pin, HIGH);
     delay(10);
     digitalWrite(pin, LOW);
     delay(10);
     lastcount = tcnt;
  }

   delay(10);

}

void blink() {
  tcnt = tcnt + 1;
  state = !state;
}

My first issue is that the when I use the code above, the lights don't seem to switch on / off on the exact same area. They are within 30 degrees but certainly not precise.
The second issue (and the biggest) is that I'm sure that this code is not the best way to do what I need. For example, if I wanted to use this as an analog clock, so that the lights would only show on the current hour / minute, how would I do this?
Any help is greatly appreciated.

If you rotate the arm by hand and observe the position sensor signal does it come up rapidly and cleanly almost independent of speed of arm motion? The sensor may be near its limit and take a finite time to transition when reflection is detected. If so,more LED current or lower separation may help. | Without trying to follow exactly what happens in your cide, are the loop delays (several 10 mS ones, affecting response time? If you change them does response time alter?

Only the first delay is needed. Try removing the other two.

Your third delay is the issue. It means you have up to 10 ms before you notice the need to turn on the light. Try this:
const byte pin = 13;
volatile bool detected;

void setup() {
  pinMode(pin, OUTPUT);
  attachInterrupt(1, blink, RISING);
}

void loop() {
  if (detected)
    {
    delay(10);
    digitalWrite(pin, LOW);
    detected = false;
    }

}

void blink() {
  digitalWrite(pin, HIGH);
  detected = true;
}

Now that immediately turns on the LED, so it will always happen at the same time. Then in the main loop you notice it is on, wait 10 ms, and then turn it off.


text:
I'm looking for a real small but decent Arduino, that can fit in a watch but power a servo and a gyroscope
I've been scouring the internet looking for a small Arduino that can power two sensors and a servo. Is there a way of getting a custom one? Does anyone know if theres software out there for creating custom Arduinos and having them made?

You might look into building a circuit, on a breadboard, from basic components. Think Atmel, AtMega instead of Arduino. Depending on your experience and willingness to read datasheets, this might be easier than you imagine. After you have a large-scale working prototype, find miniature surface-mount versions of all of the components. Designing an actual circuit board to connect these things might be the real trick, but if you can get it done then you can have the board made. I believe, am uncertain about this, that there are software tools available that help turn schematics into circuit board designs. This part might be expensive. Getting to the point of having a large-scale working prototype, on the other hand, would be inexpensive and fun. Once you have a board designed you'll have to get it made. Testing this prototype might be difficult and perhaps expensive as well. (Engineers are paid well because they tend to know before construction if a design will work.) If you come up with something that works then selling the extras might pay for having it made.

Look at the ATtiny85 MCU. It's a small 8pin device, and pretty easy to get up and running using Arduino code. You could also use the ATtiny84 which has more pins and still very small.
Start here: https://code.google.com/p/arduino-tiny/
Also, there are plenty of tutorials on setting up and programming them.
Regarding a custom board, your least expensive route would be to design your own. Otherwise you would need to outsource the design.

No, there is no software specifically for designing custom Arduinos.  However, the Arduino is open source, so you can design your own if you have the skills.
You can download the schematics for your chosen base design from the Arduino website, then use any PCB design software you like to design your own PCB.
You can then send that PCB design off to China (for example) to have it fabricated, and when you get them back you can solder the components on and hope it works.
Of course, designing and building very small circuits well is a talent that few possess. Hand building circuits with the very tiny components you will need to make it fit into a watch is very difficult and normally requires specialist equipment.  That is unless you want your watch to be the size of a dinner plate, like most of the watch kits you can buy.

If you do not want to send the design to china and live in the US https://oshpark.com/  has some great rates and are hobbyist friendly.


text:
How to wirelessly communicate with I2C infrared thermometer
I've been getting involved with arduino recently as a means of improving a heating device which is quite small, a box about 15x10x5cm which I would like to rig with an MLX90614 infrared sensor.
The box is already "wired" with many small flexible tubes, so I would like to set up the sensor so that I can read from it wirelessly, to keep it from getting anymore complicated than it needs to be.
What would be the most compact way to set up a transceiver capable of I2C (ideally with arduino uno coding compatibility) and to then communicate with another arduino? (I already have an Uno to act as the base station)
The reason I mention that the device should be codable with Arduino is that the MLX90614 uses a communication protocol that is beyond my skill level and which I can only operate with open source code libraries for arduino.
I've been doing some research and the best thing I've found so far is the PanStamp, but I have never soldered before, and they are not in business at the moment.
Another limitation is size. I would prefer not to use another entire arduino Uno, with shield.
And of course low cost is a plus :)
So if any of you have worked on something like this before and you have a recommendation, it would be greatly appreciated.
-Ryan

I should also add that distance is not an issue. My datalogger/control unit will be only a few feet away

Why I2C in particular? The NRF24L01 gadgets which you can get for a dollar or so on eBay work well over short range, and there is a good library for it. It uses SPI, so you just need your SPI pins spare (basically pins 9 to 13 as it needs one more pin for chip enable).

I2C is needed to read temperature from the sensor, which would then be transmitted to another microcontroller which controls the heater at the AC mains. I was hoping there was a simple MCU with integrated RF that could handle I2C, but it does not look like this is the case, based on the severe lack of responses in here... I also think the nRF24l01 might be the best solution, but it just seems like a waste to buy an entire arduino uno or similar to act as the intermediary between the sensor and the RF module. Have you implemented these before? If so, did you have any problems with it?

So if any of you have worked on something like this before and you have a recommendation, it would be greatly appreciated.

See Solar powered Arduino - I used a standalone Atmega328P on a prototyping board for that. That used the NRF24L01 to send information (the current voltage in this case) to another Arduino.
For small and simple you could get an Arduino Nano or Arduino Pro Mini. The Pro Mini is around $US10, and is quite small.
They have the same processor (Atmega328P) so you can connect your I2C sensor to it, and the NRF24L01 as well.

I have never soldered before ...

I think you will have to do a little soldering, to connect up the sensor, and the transmitter, but soldering on connecting wires isn't too onerous.

That is a nicely implemented project. I see that the setup for the nRF24l01 is fairly simple. I may take up soldering for this project, but I am reluctant because I fear I am deviating from what I am paid to do, which is biology, and I have no workspace to solder. Perhaps I can find someone willing to help me. I recently found out about the ESP8266 has GPIO capabilities and could potentially handle the IR sensor, but again, this involves investing a lot more time, so i'll probably get a Pro Mini.

You can always take it home to do a bit of soldering. You can get a cheap soldering iron for $25 or so, and a small packet of solder. Spread newspapers over a table and hop to it. :)

haha ok sounds good. thanks for your help. I would give you some points but i can't yet.


text:
Having issues with sending output to WiFi Shield
I am doing simple proof of concept trying to send C++ program output to Adafruit CC3000 WiFi Shield (using Visual Studio 2013 Desktop Edition on Windows 8.1).
In my design laptop is connected to UNO via USB, UNO is connected to WiFi Shield, and WiFi Shield is connected to D-Link router running Adafruit example sketch ("EchoServer"). These connections are working fine.
Next, I am using TCP client sample code from Microsoft for WiFi connectivity with client code running on the laptop to connect to WiFi Shield. Tested this code with sample TCP server code from Microsoft, and client was able to communicate with server code but for some reason this client is not able to find WiFi Shield TCP Server. I get "Unable to connect to server" error with CC3000 continue to show it is listening for connections but never finds one
I am sure it is due to my lack of understanding TCP/networking world. Below is the client code I am running on laptop using Visual Studio:
#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include<iostream>

// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")

#define DEFAULT_BUFLEN 512          //Default buffer length of port
#define DEFAULT_PORT "7"        //Change this to change port

int main()//int argc, char **argv
{
    WSADATA wsaData;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
        *ptr = NULL,
        hints;
    char *sendbuf = "100";
    char recvbuf[DEFAULT_BUFLEN];
    int iResult;
    int recvbuflen = DEFAULT_BUFLEN;
    /*
    // Validate the parameters - not necessary for use
    if (argc != 2) {
        printf("usage: %s server-name\n", argv[0]);
        system("pause"); return 1;
    }
    */

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        system("pause"); return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if (iResult != 0) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        system("pause"); return 1;
    }

    // Attempt to connect to an address until one succeeds
    for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {

        // Create a SOCKET for connecting to server
        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
            ptr->ai_protocol);
        if (ConnectSocket == INVALID_SOCKET) {
            printf("socket failed with error: %ld\n", WSAGetLastError());
            WSACleanup();
            system("pause"); return 1;
        }

        // Connect to server.
        iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (iResult == SOCKET_ERROR)
        {
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);

    if (ConnectSocket == INVALID_SOCKET) //If failed to get a socket, end program
    {
        printf("Unable to connect to server!\n");
        WSACleanup();
        system("pause"); return 1;
    }

    // Send an initial buffer
    iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
    if (iResult == SOCKET_ERROR) {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        system("pause"); return 1;
    }

    printf("Bytes Sent: %ld\n", iResult);

    // Receive until the peer closes the connection
    do {

        iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
        if (iResult > 0)
        {
            printf("Bytes received: %d\n", iResult);
            std::cout << recvbuf << std::endl;
        }
        else if (iResult == 0)
            printf("Connection closed\n");
        else
            printf("recv failed with error: %d\n", WSAGetLastError());

    } while (iResult > 0);
    // shutdown the connection since no more data will be sent
    iResult = shutdown(ConnectSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        system("pause"); return 1;
    }
    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();
    return 0;
}

At no point in your program are you telling it where to connect to.  You are requesting service "7", which of course is resolved to port number 7, but you aren't giving it an IP address or host name to connect to.  Ergo, it is trying to connect to port 7 of the same computer that the program is running on - which will fail.
You need to specify the IP address of the WiFi shield as the first parameter to getaddrinfo() (currently NULL):

int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res);
node specifies either a numerical network address (for IPv4, numbers-and-dots notation as supported by inet_aton(3); for IPv6, hexadecimal  string format  as  supported  by  inet_pton(3)),  or  a network hostname, whose network addresses are looked up and resolved.  If hints.ai_flags contains the AI_NUMERICHOST flag, then node must be a numerical network address.  The  AI_NUMERICHOST  flag suppresses any potentially lengthy network host address lookups.
If the AI_PASSIVE flag is not set in hints.ai_flags, then the returned socket addresses will be suitable for use with connect(2), sendto(2), or sendmsg(2).  If node is NULL, then the network address  will  be  set  to  the  loopback  interface address  (INADDR_LOOPBACK  for  IPv4 addresses, IN6ADDR_LOOPBACK_INIT for IPv6 address); this is used by applications that intend to communicate with peers running on the same host.
-- Extract from the getaddrinfo(3) manual page


text:
Disabling a push button after being under pressure for some time?
Disabling a push button after being under pressure for some time?
I need to disable a button where the user is pressing for a time it is disabled.
Code:
int ledPin = 13;

int inPin = 7;

int val = 0;

void setup() {

pinMode(ledPin, OUTPUT);

pinMode(inPin, INPUT);

}

void loop(){

val = digitalRead(inPin);

if (val == HIGH) {

digitalWrite(ledPin, LOW);

} else {

digitalWrite(ledPin, HIGH);

}

}

You want to what?  I don't understand what you're asking.

Okay, sorry if the question was misdirected, English is not my main language. What I mean is how to disable a push button after it is pressed for a certain time.

That's pretty much what you said before.  I don't understand what you want when you talk about "disable a push button". Do you want to have it physically disconnected from your Arduino, or only have the Arduino ignore any state changes from the button?

int ledPin = 13;
int inPin = 7;
int val = 0;
int oldVal = 0;

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

void loop(){
  val = digitalRead(inPin);
  if (val == HIGH && oldVal == LOW) {
    digitalWrite(ledPin, LOW);
    oldVal = HIGH;
  } else if (val == LOW && oldVal == HIGH) {
    digitalWrite(ledPin, HIGH);
    oldVal = LOW;
  }
}

Can you please edit your post to include exactly how this code works and how it's different than the original code? Thanks!

I think the question is about activating something on a switch push, but only for x seconds. For example, you press a button to sound an alarm, but it stops after 5 seconds.

This should do it:
const byte ledPin = 13;
const byte inPin = 7;

const unsigned long MAX_PUSH_TIME = 2000;  // ms
const unsigned long DEBOUNCE_TIME = 20;    // ms
unsigned long whenPushed;

bool switchState;
bool awaitingRelease;

void setup()
  {
  pinMode(ledPin, OUTPUT);
  pinMode(inPin, INPUT_PULLUP);
  }  // end of setup

void switchPushed ()
  {
  // we want them to let go now, ignore it
  if (awaitingRelease)
    return;

  // is LED already on?
  if (digitalRead (ledPin) == HIGH)
    {
    // held for too long? turn off LED, remember it
    if (millis () - whenPushed >= MAX_PUSH_TIME)
      {
      awaitingRelease = true;
      digitalWrite(ledPin, LOW);
      }
    return;  // all done
    }

  // turn LED on, remember when
  digitalWrite(ledPin, HIGH);
  whenPushed = millis ();
  delay (DEBOUNCE_TIME);
  }  // end of switchPushed

void switchReleased ()
  {
  digitalWrite(ledPin, LOW);
  awaitingRelease = false;  // they released it!
  delay (DEBOUNCE_TIME);
  }  // end of switchReleased

void loop()
  {
  switchState = digitalRead(inPin);
  if (switchState == LOW)
    switchPushed ();
  else
    switchReleased ();
  }  // end of loop

Note: I used an input pull-up resistor on the switch to avoid having to use extra components. Thus the switch is wired between pin 7 and ground. That is why the test for the switch being pressed is for it to be LOW.

Reference

Switches tutorial


text:
arduino boards manager configuration
I installed the Arduino IDE 1.6.4, and used the "boards manager" to install the package for Arduino Due.
I am using c++11 in my project so i need to add the compiler.cpp.extra_flags=-std=gnu++11 like i did in the /Applications/Arduino.app/Contents/Java/hardware/arduino/platform.txt file (i am on MacOSX).
It seems that arduino is ignoring that file and using a configuration coming from somewhere else.
Where is the downloaded package installed? Can it be configured?

Did you try looking under where the preferences file is stored?

@IgnacioVazquez-Abrams you are right, there it is, in the packages folder. Write it as an answer and you will get the accept points!

Ok, as @IgnacioVazquez-Abrams suggested: the configuration files for the plugins can be found in the Arduino ide preferences directory. Click the menu Arduino->Preferences (under macosx) at the bottom of the window there is the clickable path of the preferences.txt file. In the same folder as that file you will find a packages folder, where the plugins are downloaded.


text:
ISP - Wrong direction frying ATmega
I tried to flash my ATmega328P-PU not over the Arduino but over a self-made programming board and an USBasp. The problem is, I made the board a while ago and didn't mark which direction the 10-pin connector has to go.
My question is, can I fry the ATmega if I connect the 10-pin connector the wrong way around? Also, can this harm the USBasp in any way?
Connecting it the wrong way around would give me the following connections:
USBasp  ---  ATmega

MOSI    -|
NC      -|-  GND
RST     -|
SCK     -|

MISO    ---  Vcc
Vcc     ---  MISO

         |-  MOSI
GND     -|-  NC
         |-  RST
         |-  SCK

As long as there isn't anything connected to the arduino that uses power you'll probably be fine. The clamping diode on the MISO pin will pass VCC from the usbASP to the arduino's vcc. I've done something similar a few time myself, and the chips are still fine. Just don't leave it connected the wrong way for too long. But I'd suggest just getting the multimeter and check that way, before connecting.

No, connecting it backwards shouldn't do any damage, it just won't work.  The clue is in these two connections:
NC      -|-  GND
GND     -|-  NC

With it backwards the ground connection doesn't go anywhere.  Without that ground connection there's no circuit.  With no circuit, no current flows.
The only possible danger is to the protection diodes in the IO pins when you try and operate the programmer.  The lack of a ground connection could cause some current to flow the wrong way through the circuit (in through the ATMega's MISO pin and out through the MCU's Vcc pin) through the ESD protection diode.  That could cause damage to that diode and maybe the rest of the MISO pin's logic, but it's not that likely since the currents involved would be somewhat limited by the route the power then takes through the MISO pin of the programmer.

Thanks for the answer! Is there any danger for the programmer?

I'm not sure what the design of the programmer is, but a sensible one would include resistors in all the IO lines to protect against overcurrent, so it's highly unlikely that it would cause any problems.

Ok, sounds good. Thanks a lot for your help!


text:
Arduino Mega 2560 R3 with Shield Model Wireless SD R3 not working
Recently I've bought an Arduino Mega 2560 R3 and a Shield Model Wireless SD R3 from http://www.amazon.de/Arduino-A000065-Netzwerkkarte-Wireless-SD-Shield/dp/B00L1FO860. I try to run the example from https://www.arduino.cc/en/Tutorial/ConnectWithWPA
Before running the sketch I turn the DIP switch to the position USB.
It seems like the WIfi Shield is correct connected to the Arduino since the LEDs TX and RX are blinking during upload the Sketch.
Sadly as output I got only:
    WiFi shield not present
Currently I'm not sure if the hardware itself provide Wifi functionality. Does somebody know if it should work with this hardware?

You see that double row of 10 pin headers?  That's an XBee connector.
https://www.sparkfun.com/pages/xbee_guide
You use it to connect your XBee module of choice (there's a few to choose from) to communicate wirelessly between Arduinos using the special XBee system.
Note that XBee is not WiFi, it's Wireless.  The two are very different things (Wireless refers to any wire-free communication system, WiFi is one specific protocol on one specific set of frequencies using a specific set of encodings, etc).  XBee cannot talk WiFi in the same way that I can't talk Chinese.
For WiFi you need a WiFi shield.
https://www.arduino.cc/en/Main/ArduinoWiFiShield


text:
Usage of SPI inside an ISR
I learned, that SPI-code uses interrupts. So is it true then, that I can't use SPI related code inside an ISR?
Background: I want to capture one or more revolution speeds with an MCP23S17. I rewired the interrupt lines to INT1 and INT2 accordingly to get the interrupts at the Arduino.
I thought it was good to fetch the port registers from the MCP23S17 inside the ISR, but this apparently doesn't work.
Is the only thing I can do in my ISR set a flag for another test in the main loop? And let a routine called from lood() then poll the registers from the port expander? This opposes the idea to fetch the relevant data which issued the interrupt ASAP.

This is why you don't use port expanders for timing-sensitive applications.

And instead of port expanders i shall use what?

Real IO pins on the microcontroller.

@Majenko: Which I have to poll. :(

No you don't - there's such a thing as Pin Change Interrupt which is (IIRC) available on every IO pin.

Reads interesting. Is the only difference between those Pin Change Interrupts and INT0/1 the fact that the latter can additionally trigger on high and low?

Please post your code. Majenko is perfectly correct. SPI does not use interrupts, at least during SPI.transfer(). I learned, that SPI-code uses interrupts. - where did you learn that?

apparently doesn't work. - I hate that expression. What happened? What did you expect to happen? In what way did they differ?

As a sidenote. You can use interrupts inside an ISR. Just call sei(); at the beginning of the ISR. There are however some side effect that you have to know about. It's therefor generally advised not to do this, unless you know what you are doing.

@NichGammon: The ISR is never called. To control the behaviour of the ISR I let it increase a global counter. But the counter stays at 0, while the INTCAP register of the port expander shows evidence for activity. But considering the answers here, the error must be elsewhere.

SPI doesn't use interrupts.  It references the interrupt flag to know if a transfer has been completed, but it doesn't actually have interrupts enabled:
SPDR = data;
asm volatile("nop");
while (!(SPSR & _BV(SPIF))) ; // wait
return SPDR;

It should be perfectly possible to use SPI within the interrupt - indeed there is portions of the SPI API that deal specifically with this - see https://www.arduino.cc/en/Reference/SPIusingInterrupt for instance.

Ok, I missed that. Then there must be another thing I apparently have botched...


text:
How can an Arduino Mega 2560+Wifi Shield 2.0 (SeeedStudio) receive data from database in a XAMPP server on my PC?
I'm trying to connect my Arduino Mega via Wifi to my XAMPP server. My main objective is get a value from my database and store it on a variable in Arduino code. With this new variable I'll be able to control the rest of the program... So I need your help. Can someone give me advice?
I already tried every thing that I found on the internet but it just doesn't work.
I think that the simple way is to send a GET request to the server and read its response... But for some reason I can't send a GET request through...
I tested it on the browser directly and the value shows up, so I think that the server side is all right.
Here is my Arduino code:
#include <Arduino.h>
#include <SoftwareSerial.h>
#include "WiFly.h"
#include "HTTPClient.h"

#define SSID      "mySSID"
#define KEY       "myKEY"
#define AUTH      WIFLY_AUTH_WPA2_PSK
#define HTTP_GET_URL "http://192.168.1.80/xampp/training/send_data_db.php/?temp=0"

// Pins' connection
// Arduino       WiFly
//  2    <---->    TX
//  3    <---->    RX
SoftwareSerial uart(10, 11);
WiFly wifly(uart);
HTTPClient http;
char get;

void setup() {
  Serial.begin(9600);
  Serial.println("------- WIFLY HTTP --------");
  uart.begin(9600); // WiFly UART Baud Rate: 9600
  // Wait WiFly to init
  //  delay(3000);

  // check if WiFly is associated with AP(SSID)
  if (!wifly.isAssociated(SSID)) {
    while (!wifly.join(SSID, KEY, AUTH)) {
      Serial.println("Failed to join " SSID);
      Serial.println("Wait 0.1 second and try again...");
      delay(100);
    }
    wifly.save(); // save configuration,
  }
  Serial.println("\r\nTry to get url - " HTTP_GET_URL);
  Serial.println("------------------------------");
  while (http.get(HTTP_GET_URL, 10000) < 0) {
  }
  while (wifly.receive((uint8_t *)&get, 1, 1000) == 1) {
    Serial.print(get);
  }
  if (wifly.commandMode()) {
    Serial.println("\r\n\r\nEnter command mode. Send \"exit\"(with \\r) to exit command mode");
  }
}

void loop() {
  int c;
  while (wifly.available()) {
    c = wifly.read();
    if (c > 0) {
      Serial.write((char)c);
    }
  }
  while (Serial.available()) {
    c = Serial.read();
    if (c >= 0) {
      wifly.write((char)c);
    }
  }
}

And here is my PHP code:
<? php
include("./connection/database_connect.php");
include("./top_table.php");

if ((isset($_SESSION["ID"])) AND (isset($_GET["temp"]))) {
  $id = $_SESSION["ID"];
  $sql = "SELECT temp FROM perfil, client WHERE perfil.ID ='$id'";
  $consult = mysqli_query($connect, $sql);
  $result = mysqli_num_rows($consult);
  if (($result == 1)) {
    $person_data = mysqli_fetch_array($consult, MYSQLI_ASSOC);
    $temp = $person_data["temp"];
    header("HTTP/1.1" . " " . 200 . "OK");
    header("Content-Type: text/html; charset=UTF-8");
    header("Content-Length: 1112");
    header("Connection: close");
    header("/r/n");
    echo $temp;
  } else {
    //se user dosen't exist on data base
    header("Location: http://192.168.1.80/xampp/training/login.php");
    exit;
  }
} else {
  header("Location: http://192.168.1.80/xampp/training/login.php");
  exit;
}
?>

Step 1: confirm if the request is reaching the Apache server.

Sorry the delay but I just saw it now...
Yes the request is reaching the server. I tried with a simpler code just to be sure and the server sends a response, but not what I want.
It seems that the $_GET['temp'] is not set...

php/?temp - That looks "iffy" to me.  Should that / be in there?

I think so, just a while ago I spoted an error in that line I had "php/?$temp"  in there and solved part of my problem. It seems like the problem is that the $_SESSION can't be reached. And besides that my web page on the browser dosen't react

$_SESSION either needs cookies or a PHPSESSID=.... parameter, neither of which you will likely have.

hum... that might be an issue, I'm only logging in an user in my browser and start the session in "include('./top_table.php'), maybe it isn't enough.
I thought that with the user logged in I could user his $_SESSION but it seems not...
Does PHPSESSID changes ever new session? if yes i don't think i can use it in Arduino code as a variable.
what should i do? register arduino along with the info of the person/house? With that i might be able to acess the person ID and reach out "temp"

The PHPSESSID is a unique key that identifies the session.  It is allocated by PHP when the session is opened and must be provided back to PHP with every request to be able to access the session.  What you could do is perform a 2-stage login action, where you first go to a "login" page which returns your session ID, and then you make your normal (and all subsequent) request(s) including the session ID.

Filipe I need your help. Can you help me out from this! I need to store voltage sensor data from arduino mega using shield in local server. Please contact me at sjisylhet.partha@outlook.com
thanks for your time.

You should forget about the $_SESSION["ID"]; on PHP side, because you are working stateless without any session!
You should give a parameter for identifying your variable from arduino to php script - is this the temp=0? If so you need to exchange
$sql="SELECT temp FROM perfil, client WHERE perfil.ID ='$id'";

with
$sql="SELECT temp FROM perfil, client WHERE perfil.ID =" . $_GET["temp"];

assuming that perfil.id is only an integer - if it is a string, then add "'".

Yes you are right!
Meanwhile i finished this project.
The problem was with the Wi-Fi shield that I was using. The Http request wasn't in a right format.


text:
Tried to fix ports on Mac OS X Yosemite. Now nothing works
I was having an issue very similar to this one:
Arduino compatible's serial port not showing Mac OSX
Basically I have a clone (VISduino) and it's made with a different USB chip so it needed a driver. Installing the driver didn't help.
http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html
Running:
 sudo nvram boot-args="kext-dev-mode=1"

didn't help. So I decided to delete Arduino and reinstall. Then I went through all of the steps again.
Well.... now nothing works. Before doing this I could use:

Adafruit metro
An uno clone
My genuine uno
lightBlue Bean
adafruit trinket and trinket pro
adafruit trinket pro via USB
digikey

I've reinstalled the drivers for these but NOTHING is working now. They were all working before. It just says Arduino Uno on COM1, or digikey on COM1 etc.

And of course my clone (vis duino) isn't working either.
How can I fix this?

The com ports just are not there.

That's clever - you've got your Mac to give you Windows device names...?!

what do you mean?

COM1 is what windows calls it.  I'd expect something like /dev/cu.modem-4d82f3a

well my mac is calling it com1 I posted a photo.

It's saying COM1 because you haven't (yet) selected a serial port to use.  This has nothing to do with the Arduino IDE - it's 100% to do with dodgy drivers.

Serial is greyed out. I tried deleting all Arduino files (except for my sketches which I put in another folder.) reinstalling and just trying to load blink on my  genuine uno.... same error.

Have you reviewed the questions shown as Linked or Related, in the right sidebar?  Eg,  “Arduino compatible's serial port not showing Mac OSX”, “No valid serial ports for Arduino UNO on Mac”, “Arduino compatible's serial port not showing Mac OSX”, “Arduino Nano no serial port for MacBook Air 2013”, and “Mac won't detect Serial Port for Leonardo”

Restarted for the 6th time and now it works WTF seriously.

Oh I did read all of those. It's working now but I have no idea why. Ugh.

I solved this issue by deleting all of the Arduino files and the Arduino app. I put my sketched folder aside but deleted all libraries.
Restarted the computer.
Installed Arduino fresh.
Restarted the computer.
Installed the drivers.
Ran the command.
Restarted the computer.
Restarted the computer.
Restarted the computer.
Then it worked.


text:
Can I use micros() to analyze TX23 anemometer signal?
I'm very new to Arduino, and I'm trying to read data from a LaCrosse TX23 V02(X) anemometer. It's supposed to behave like this https://www.john.geek.nz/2012/08/la-crosse-tx23u-anemometer-communication-protocol/, but it's not...
I don't have an oscilloscope, so I made this code, using micros() to try to trace the output from the TX23:
void loop() {
  collectData();
}

int collectData(void){
   if (bitLength < 0){
      bitLength = 1200;// length of bit is equal to approx 1230 micro seconds;
   }
  // init sequence
  pinMode(dataPin, OUTPUT);
  Serial.print("Send LOW\n");
  digitalWrite(dataPin, LOW );
  Serial.print("Send HIGH\n");
  digitalWrite(dataPin, HIGH);
  delay(100);
  Serial.print("Send LOW\n");
  digitalWrite(dataPin, LOW );
  delay(500);

  Serial.print("Begin input mode\n");
  pinMode(dataPin, INPUT);

  int state = 0;
  int oldstate = 0;
  unsigned long oldmicros = micros();
  for (int i = 1; i<5250 ; i++) {
    state = (digitalRead(dataPin) == LOW)? 0:1;
    if (i%10 != 0) {
      Serial.print("-");
    } else {
      Serial.print("+");
    }

    delayMicroseconds(10);
    if (state != oldstate) {
      oldstate = state;
      i = 1;
      Serial.print(oldstate);
      Serial.print(" @");
      Serial.print(micros() - oldmicros);
      oldmicros = micros();
      Serial.print("\n");
    }
  }
  Serial.print(state);
  Serial.println(micros()-oldmicros);
}

Does it have a chance to provide a quite accurate monitoring of the TX23 output? (eg is using micros() or delayMicroseconds(10) accurate ?)

You should really make use of pulseIn() to work out the bit rate of the signal.  The first HIGH pulse in the header is there for timing so you know how often to poll the input.
Step one, after sending your outgoing initiation pulse, should be to wait for that first pulse (you might need a slight delay first before it starts transmitting - wait for the line to be low first):
while (digitalRead(dataPin) == HIGH); // Wait for TX start
uint32_t pulseWidth = pulseIn(dataPin, HIGH); // Get first pulse

That gives you the width of the first pulse in microseconds.
Now you can read 45 times at that period.  If you first delay by half that amount before your first sample you will be roughly in the middle of the bit so you can cope with a slight amount of drift.
// Wait for the middle of the first bit
delayMicroseconds(pulseWidth / 2);

uint32_t highBlock = 0;
uint32_t lowBlock = 0;
for (int i = 0; i < 45; i++) {
    // Shift the high 32-bits left one bit
    highBlock <<= 1;
    // Place in the highest bit of the low block as the lowest
    // bit of the high block
    highBlock |= (lowBlock & 0x80000000UL ? 1 : 0);
    // Shift the low 32-bits left one bit
    lowBlock <<= 1;
    // Add in the value of the bit from the data pin
    lowBlock |= digitalRead(dataPin);
    // Wait for the next bit
    delayMicroseconds(pulseWidth);
}

You should now have two 32-bit words which, when put together, form the entire datagram.  You can now use bitwise operators to pull out the parts you are interested in.
A better, though more complex, method of doing it would be to employ a timer with an overflow period equal to the pulse width. That will afford you much more accurate timing than a simple loop with delays.

Thanks a lot for the input. It does not exactly answer my initial question, but it certainly helps me solve my problem reading the TX23 output ! It works, but I don't understand the first 'while (digitalRead(dataPin) == HIGH);' and the data I get with pulseIn() are the first two bits of the header, not an initial pulse...

Marking this as right answer as it helped me resolve my real problem, but other two contributions were really helpful as well. Thanks to
jwpat7 and Nick Grammon.

Majenko showed a method for digitally recording the waveform, after measuring pulseWidth at the outset, and mentioned use of a timer for delays.   I'll address the part of your question about using micros() while tracing TX23 output:  “Does it have a chance to provide a quite accurate monitoring of the TX23 output?”
Some of the serial output that your method produces as it goes along will affect evenness of timing.  For example, the Serial.print() of + after every tenth reading introduces a small timing irregularity (the two branches of the if may differ a few cycles in execution time).
More seriously, your double-read of micros() (after you print oldstate, you print micros() - oldmicros and then read micros() again) introduces a few cycles of timing error.  It probably amounts to a few microseconds total over the course of recording the pulse train.  Instead of reading micros() twice, say something like newmicros = micros() directly after detecting a state change, before doing any serial printing, then use newmicros in place of other micros() calls.  Having serial prints before oldmicros = micros(); causes an offset error, which will be microseconds or milliseconds depending on the data rate you set in setup().  It mostly affects the reported length only of the first pulse.
What I would do for debug monitoring of the pulse train is along the following lines:
enum { timelen=44, maxpause=50000 };
unsigned long int times[timelen];

int collectData() {
  byte ntimes = 0, state=LOW;
  unsigned long int prevtime;
  pinMode(dataPin, OUTPUT);
  digitalWrite(dataPin, LOW ); // Pull DTR low to trigger conversion
  delay(500);
  pinMode(dataPin, INPUT_PULLUP); // Release DTR and set pullup
  delay(1);           // Let TX23U pull DTR low
  prevtime = micros();
  while (micros() - prevtime < maxpause && ntimes < timelen) {
    if (digitalRead(dataPin) != state) {
      times[ntimes++] = prevtime = micros();
      state = 1-state;
    }
  }
  return ntimes;
}

This code is intended to record times at which state changes occur.  After loop() calls collectData(), it can call a reportData() routine that will print out pulse lengths by subtracting adjacent entries of times[].  Even-indexed array entries are times of rising edges in the pulse train; odd-indexed entries are times of falling edges.  Because the if (digitalRead(dataPin) != state) {...} statement isn't executed atomically, the data pin can change after being tested but before being recorded a couple of lines later.  Using state = 1-state; instead of state = digitalRead(dataPin); guarantees that even indexes are for rising edges, but does not guarantee that adjacent entries correspond to the same pulse edge.  That is, a noisy signal can produce misleading results.

I'm going to present a third way of working on this. :)
First, since I don't have a TX23 I wrote a TX23-simulator:
const byte TESTPIN = 2;

const byte test [6] = {
    0b00000011,
    0b01111011,
    0b01010100,
    0b00010100,
    0b01001010,
    0b10111111 };

void setup ()
  {
  pinMode (TESTPIN, INPUT);
  delay (100);
  }  // end of setup

void loop ()
  {
  // wait for host to pull pin low
  while (digitalRead (TESTPIN) == HIGH)
    { }
  // wait for host to release it
  while (digitalRead (TESTPIN) == LOW)
    { }
  digitalWrite (TESTPIN, HIGH);
  pinMode (TESTPIN, OUTPUT);
  for (byte i = 0; i < 6; i++)
    for (byte j = 0; j < 8; j++)
      {
      delayMicroseconds (1100);
      digitalWrite (TESTPIN, test [i] & bit (7 - j));
      }
  pinMode (TESTPIN, INPUT);
  }  // end of loop

Based on your linked page about the TX23 it outputs a series of low/high pulses corresponding to the example on that page, like this:

Note that you need a 10 k pull-up resistor for this to work properly.

Now the reading code uses interrupts to detect state changes:
const byte READ_PIN = 2;
const byte NUMBER_OF_CHANGES = 48;

volatile unsigned long bitTime [NUMBER_OF_CHANGES];
volatile byte state [NUMBER_OF_CHANGES];
volatile byte count;

void stateChange ()
  {
  unsigned long now = micros ();
  if (count >= NUMBER_OF_CHANGES)
    return;  // array full
  state [count] = digitalRead (READ_PIN);
  bitTime [count++] = now;
  } // end of stateChange

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  }  // end of setup

void takeReading ()
  {
  count = 0;
  digitalWrite (READ_PIN, LOW);  // start reading
  pinMode (READ_PIN, OUTPUT);
  delay (20);  // pulse width
  pinMode (READ_PIN, INPUT);     // release line
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  attachInterrupt (0, stateChange, CHANGE);
  delay (55);  // let readings fill up array
  detachInterrupt (0);
  }  // end of takeReading

void loop ()
  {
  takeReading ();
  if (count == 0)
    return;  // nothing!

  delay (500);
  for (byte i = 0; i < count; i++)
    {
    Serial.print ("count: ");
    Serial.print ((int) i);
    Serial.print (" = ");
    Serial.print (bitTime [i]);
    Serial.print (", state = ");
    Serial.print (state [i]);
    if (i > 0)
      {
      Serial.print (", width = ");
      unsigned long width = bitTime [i] - bitTime [i - 1];
      Serial.print (width);
      Serial.print (" (");
      int bits = width / 1000;
      for (byte k = 0; k < bits; k++)
       Serial.print (state [i - 1]);
      Serial.print (")");
      }
    Serial.println ();
    }
    Serial.println ();
  }  // end of loop

Results were:
count: 0 = 10952804, state = 1
count: 1 = 10953928, state = 0, width = 1124 (1)
count: 2 = 10960616, state = 1, width = 6688 (000000)
count: 3 = 10962844, state = 0, width = 2228 (11)
count: 4 = 10963960, state = 1, width = 1116 (0)
count: 5 = 10968412, state = 0, width = 4452 (1111)
count: 6 = 10969524, state = 1, width = 1112 (0)
count: 7 = 10971752, state = 0, width = 2228 (11)
count: 8 = 10972876, state = 1, width = 1124 (0)
count: 9 = 10973988, state = 0, width = 1112 (1)
count: 10 = 10975104, state = 1, width = 1116 (0)
count: 11 = 10976216, state = 0, width = 1112 (1)
count: 12 = 10977328, state = 1, width = 1112 (0)
count: 13 = 10978440, state = 0, width = 1112 (1)
count: 14 = 10984012, state = 1, width = 5572 (00000)
count: 15 = 10985124, state = 0, width = 1112 (1)
count: 16 = 10986244, state = 1, width = 1120 (0)
count: 17 = 10987356, state = 0, width = 1112 (1)
count: 18 = 10990700, state = 1, width = 3344 (000)
count: 19 = 10991812, state = 0, width = 1112 (1)
count: 20 = 10994040, state = 1, width = 2228 (00)
count: 21 = 10995156, state = 0, width = 1116 (1)
count: 22 = 10996268, state = 1, width = 1112 (0)
count: 23 = 10997380, state = 0, width = 1112 (1)
count: 24 = 10998500, state = 1, width = 1120 (0)
count: 25 = 10999616, state = 0, width = 1116 (1)
count: 26 = 11000728, state = 1, width = 1112 (0)

This seems to agree with the test data.

Thanks for this, it really helps me progress and opens other possibilities to me.