text:
What are the parameters of the browseUrl() callback in the Ethercard library?
I'm reading a code that uses Arduino as a webclient and when he tries to catch the info from the site, he uses a callback with the following parameters:
static void response_callback (byte status, word off, word len)

Can anyone explain me how does each one of this parameters work exactly?
PS.: The example I got it from:
#include <EtherCard.h>

#define HTTP_HEADER_OFFSET 0
static byte mymac[] = {0x12,0x34,0x56,0x78,0x90,0xAB};
char website[] PROGMEM = "www.yourwebsite.com";

byte Ethernet::buffer[700];
static uint32_t timer = 0;

static void response_callback (byte status, word off, word len) {
  Serial.print((const char*) Ethernet::buffer + off + HTTP_HEADER_OFFSET);
}

void setup () {
  Serial.begin(57600);

  if (!ether.begin(sizeof Ethernet::buffer, mymac, 10))
  {
    Serial.println("Failed to access Ethernet controller");
    while(1);
  }
  else
    Serial.println("Ethernet controller initialized");
  Serial.println();

  if (!ether.dhcpSetup())
  {
    Serial.println("Failed to get configuration from DHCP");
    while(1);
  }
  else
    Serial.println("DHCP configuration done");

  if (!ether.dnsLookup(website))
  {
    Serial.println("DNS failed");
    while(1);
  }
  else
    Serial.println("DNS resolution done");

  ether.printIp("SRV IP:\t", ether.hisip);
  Serial.println();
}

void loop() {
  ether.packetLoop(ether.packetReceive());

  if (millis() > timer) {
    timer = millis() + 5000;
    ether.browseUrl("/", "yourpage.php", website, response_callback);
  }
}

Where do you get that callback signature?

Just added the example I got it from

The Arduino world indeed often lacks traditionally detailed API documentation.  One fallback is to do a full-text search (with a GUI tool or grep -R ) of the library folders and installation for the function name, and find its actually source code to study.

Apparently, the callback is executed on every packet which arrives by the browseUrl call.
"off" and "len" are pointers to the Ethernet buffer holding the data. "Off" are the initial value (offset) and "len" (length) is the amount of data received.
"byte status", I am not sure what it means, but it's very likely will be some kind of error code. It's not being used in any sample I am seeing, so I am really wondering what it means...
Check this link for a fully working sample
Callback here are called browseUrlCallback1 and browseUrlCallback2.
Can't figure out a link with the detailed documentation. If someone has it, please post it.

Could it be this product: http://jeelabs.org/pub/docs/ethercard/ ?

Yeah, but as all I have found, it lacks specific documentation about callback details. BrowseUrl is well documented as usual, but it just specifies how the callback method has to be defined, not what does each parameter mean.

Thats exactly my problem, I can't find its documentation anywhere!
Btw, thx for the response!

It's all in the source. In the file tcpip.cpp in the ethercard-master.zip you find the function static uint8_t www_client_internal_result_cb. There you see how status is derived from the HTTP status code, like uint8_t f = strncmp("200",(char *)&(gPB[datapos+9]),3) != 0;. Why waste any other space in a docfile nobody likes to write or even read?

They are not actually pointers.  "off" is presumably an offset index while "len" is a count or size.

authors: Дмитрий Семенов


text:
Possible to create IP-to-USB HID (keyboard) device using Arduino?
Is it possible to create an IP-to-USB HID (keyboard) using Arduino?
I'd like to connect an Arduino to my network using Ethernet, and then send it commands using TCP/IP and have those commands translated to USB HID and sent as keystrokes to the connected PC.
I've found a few articles discussing USB HID emulation using the Arduino Uno (see http://mitchtech.net/arduino-usb-hid-keyboard) but it refers to using GPIO pins as buttons.
Am I correct that this might work if I use an Arduino Uno and then purchase an Arduino Shield Ethernet?  (seems a bit expensive, but is this the cheapest option?)
Thanks in advance!

And it's not the cheapest option.
You might want to check Arduino HID first, to see which type of Arduino can handle HID. You could also buy an Arduino Nano and arduino ethernet module on eBay (which should be around $10) but might take a 15-30days shipping.

Yes, it is perfectly possible.
You ideally need an Arduino with a direct USB interface, such as the Leonardo. Then you can just access the Keyboard object to send the keystrokes to the PC.  How your receive the data through Ethernet is entirely up to you. A simple TCP interface may be easiest - open the connection with whatever telnet-like client and whatever you type gets sent through.  The trick will be getting it into character-at-a-time mode.

Thanks for the information!  So I would need a Leonardo and then connect my own USB connector to the I/O pins?  Also, what would be the cheapest way to add the Ethernet connection?

No, with the Leonardo you just plug the USB cable into the on-board USB socket. No need to do anything dodgy with GPIO pins. The cheapest ethernet is probably using WiFi with the ESP8266.

What about the Leonardo ETH version?  (I'm not too found of wireless, usually)

Perfect board. Has everything you need. Just plug in the USB and Ethernet cables and write a sketch. Nothing else needed.

Thank you so much!  Any recommends for a case?

Nope. Never used a case on an Arduino before.

source: Stack Exchange

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

authors: Иван Крафченко

sort: votes


text:
Why is the nRF24L01 not working with Arduino Esplora?
I am working on a remote control car from an Arduino Esplora board and the Mega 2650 Board. My problem lies with the Esplora board as the nRF does not transmit like it is supposed to or does not even transmit at all.
I am using the pingpair_test.ino from the RF24 library to make sure the transceiver is working, and when I try to transmit on the serial monitor, I get the following output:
Configuration = t

STATUS = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0

RX_ADDR_P0-1 = 0x0000000000 0x0000000000

RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00

TX_ADDR = 0x0000000000

RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00

EN_AA = 0x00

EN_RXADDR = 0x00

RF_CH = 0x00

RF_SETUP = 0x00

CONFIG = 0x00

DYNPD/FEATURE = 0x00 0x00

Data Rate = 1MBPS

Model = nRF24L01

CRC Length = Disabled

PA Power = PA_MIN

Now sending length 4...No responses received. Are interrupts connected?

I have no idea what any of this means besides the interrupts part.
Even using interrupts(); the Arduino Esplora still refuses to send data. I am sure my wiring is correct because the status light on the nRF is on and I triple checked all of the SPI pins.
On the Esplora:

CE = 0
CSN = 1

On the Mega:

CE = 51
CSN = 50

I have a fritzing sketch here for those who want to see my wiring.

Bad wiring, check it three times and verify you are using the right pins. Another option is that your module is broken. Currently the library can't even detect the module (at all, like totally 0).

You may not be using the IRQ pin.   Mind posting your code so we can comment/troubleshoot?

@tr4nc3 - I have edited the question, and added a link to the actual pingpair.pde file. However, one thing that strikes me as odd is that the quoted output has a misspelling in recieved. However, the actual code line does not... How is that possible?

Uhh, also update your library it's ancient, either from the IDE of from https://tmrh20.github.io/RF24/.

@Greenonline Yeah I had to manually type the output because copy-paste wasn't working. Idk why.

As for the module being broken it isn't because I tried it on another board. And I repeatedly checked my wiring so I am 99.9% sure it's right.

is there a way you could post a picture of your wiring because i'm having the same problem as you

This is really a comment, not an answer. With a bit more reputation, you will be able to post comments. For the moment I've added the comment for you, and I'm going to delete this answer. Thanks for your understanding and cooperation!

How much voltage are you supplying to the nRF24? It must be 3.3v.

Funny you should ask, I have been playing with nRF24 for a while, and was thinking of trying out my Esplora. There are however a few problems, which have postponed this (read: can't be arsed).

Pins. You need access to the SPI pins + 2 other pins. On the code you linked to, it's 8 and 9. Which won't work on an Esplora: D9 is not broken out, and D8 is CARD_CS. Better leave that alone. Your best bet would be to use the ICSP header and the two orange TinkerKit pins, D11 & D3.

[UPDATE] Also, the RF24 library uses D2 for IRQ, which is going to be slightly inconvenient on an Esplora, as this pin isn't broken out either. TMRh20 doesn't use an IRQ pin. Neither does Mirf.

As you can see, the Esplora is on 5V, which could give the nRF24 module a headache. You'll have to step that down to 3.3. Way too much work for me, but then again I'm lazy.
If you're planning on using the screen, the ICSP header is kind of in an awkward place. I've tried fitting regular cables under the screen, and all I've got for my pains was a big dose of what the heck.
Stand-alone power. If you're planning to use the Esplora as a standalone, you'll need a battery and a voltage stepper. So in the end, you could use the voltage of the battery for the nRF24 module, and the 5V output from the stepper for the Esplora. More work, grrr.

Looking at your output either you have a wrong wiring or, more probably, you need a capacitor between the nRF24 positive and negative pins: anything between 10uF and 100uF will do.

authors: توفيق الخولاني

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


text:
LM335Z temperature sensor gives very varying values
I'm trying to get consistent values from the LM335Z temperature sensor. But it behaves very strange.
I'm using an arduino nano and it's powered via USB from a Raspberry Pi. The circuit also has two little reed relays (SIP-1A05), a button and a potentiometer.
It's connected like this:

Additionally I'm using analogReference(EXTERNAL) in an attempt to get consistent values, so I've connected the Arduinos 5V output to the reference voltage pin.
Here's the code for reading the thermometer:
int getTemperature() {
  int rawvoltage = analogRead(0);
  float millivolts = (rawvoltage / 1024.0) * 5000;
  float kelvin = (millivolts / 10);
  float celsius = kelvin - 273.15;
  return round(celsius);
}

Then it just waits for me to say "get" in the serial monitor and it replies with:
void sendData(){
  String data = (String)getTemperature();
  data += ',';
  data += (String)map(getTablePos(), 0, 1023, 0, 100); //Potentiometer
  data += ',';
  data += (String)getTableActive(); //1 or 0
  Serial.println(data);
}

I also read somewhere that the first couple of readings are unreliable, and that you should read a couple of times in startup, which I do:
for(int i = 0; i < 10; i++){
    analogRead(0);
    delay(1);
  }

Yesterday the termometer reported 37 degrees. Today it started by reporting 49 degrees. After asking for the temperature a couple of times it said 56. Then now, about an hour later it says 52. And if one of they relays is active it says 77 degrees.
My two other (non Arduino) thermometers have ben on a steady 25 all this time.
What should I do to get reliable values from the LM335z?

Edit
Added dots to the intersections of the circuit diagram for better readability.
I've also found a way to get the thermometer to work, kind of. I removed the external analog reference and only have one 1kOhm resistor for the LM335Z.
Then I have this code instead:
const float cal = 4.62; //Voltage between 5V and GND, measured with multimeter

float getTemperature() {
    float input = (float) analogRead(0);
    input = (input*cal)/1024.0;
    return (input/0.01)-273.15;
}

It worked perfectly standalone on an Arduino Uno powered via USB3.0. When I moved it over into my project with the Nano it gave a few degrees off, but that can be combated by just subtracting the difference I guess.
Then I tried switching to a USB2.0-port on my keyboard, and the values started jumping all over the place.
Here's a comparison using Arduinos rather spartan plotter:

Left: USB2.0 via keyboard hub. Right: Front panel USB3.0.
Also, the temperature dubbels when a relay is on.
How do I tackle this? I'd like keep powering it from my Raspberry pi 3, if possible.

You may want to use a more stable reference. You're checking the 5V of the Arduino by taking it's 5V output to the analog-reference input? You could also just use the default in that case. You could use the internal "bandgap reference" which should always be 1.1V, even when the input voltage varies (which might be the case, I don't think it's a steady 5V?).

@Paul doesn't the thermometer and the potentiometer I have connected need to output between 0v and 1.1v if I use internal?

I believe not, you can check it againsts the 1.1V read this article by our user Majenko for more information (https://hackingmajenkoblog.wordpress.com/2016/02/01/making-accurate-adc-readings-on-the-arduino/#more-12)

According to your schematic, one of the LM335Z's leads is floating. The pins are meant to be Vcc, Gnd, and output; the output should go to an Analog input.
You wrote that Aref was tied to +5 but you've drawn it as going to one end of the pot with the other end of the pot grounded. The pot's wiper goes to A1 (assuming the pin hasn't been set to some other function).
In short, check your circuit. Try wiring up the sensor to +5, Gnd, and your DVM. Then replace the DVM with A0. At that point you'll have confirmed the sensor circuit, leaving only the code and the external analog circuitry. While I only skimmed the code I don't see anything that would give flaky results. I think you're seeing analog noise, probably due to one or more of the floating sensor pin, an inconsistent or noisy Aref, and pickup in the analog input from the sensor.
Update:
I based my connections description on this diagram

, from this datasheet. In all of those diagrams, the Resistor-Zener connection is shown as the output and no pins are shown floating. But I did see that pin labeled as adj, for what reason I don't know. That's really why I recommended getting the sensor working by itself first.
I see your +5V to Aref connection now. The usual convention for indicating a connection at such a crossing is to put a dot on the intersection, just as the output pin's connection is shown in the above diagram.

All the tutorials have shown that you only use two pins, and the datasheet says that it has adj + -. And adj is for offsetting if the value if off.
The pot is connected to the same 5V line as Aref, I don't now exactly how you show that lines are connected but I didn't draw a little loop in that intersection.

Thanks for expanding on your reply. I tried that without success. However, I found old code from when I first fiddled with the sensor, and that worked to some extent. I've updated the main post with details.


text:
SD-Card-Module doesnt work with external power supply
Problem description
I am trying to build a datalogger with an Arduino UNO. I have connected a SD card module to the Arduino. I have planned to catch the measurement data from the analog input pins. Everything works fine if connected to the usb port. But if I run the Arduino over an external power supply, the SD.open-method fails (It simply returns false).
The problem occurs even, if I connect the external power supply additional to the USB connection. So the problem can't be a missing serial connection.
Note that the problem only occurs, if SD.open is in WRITE-mode.
(File dataFile = SD.open("datalog.txt", FILE_WRITE);)
What I've already tried:

running the SD-card example code, which is included in the SD card library.
trying different types of file-system formattings (FAT, FAT32, with different cluster-sizes)
powering the sd-card reader with 3.3V instead of 5V

Arduino wiring
Look at the pictures to check if there are some mistakes with the wiring:

Specifications of the power supply
And here are the specifications of the power supply:

Manufacturer: MyVolts
Model: DD282MU
Input: 100-240V (AC) - 50-60 Hz
Output: 9V, 1A (DC)

I hope you can help me with my problem. And of course, I hope there is a solution for the problem at all. Thank you.

Have you tried connecting the SD card module 5V pin directly to the PSU through a 7805 regulator? How do you know SD.open() returns false when you arent connected to the PC over USB?

Thanks for your reply.
I don't have a 7805 regulator - so I didn't try it. I know that SD.open() returns false, because I have connected a LED and let it flashing in this case. Secondly I saw it in the Serial monitor: The error also occurs if both, the usb cable AND the PSU, are connected.

Scratch what I said about the 7805; just remembered theres no need for one since the Arduino 5 V output is from an internal regulator anyways. SD cards draw a lot of current (at least 100mA) when reading or writing. So it could be that with the current drawn by both Arduino and SD card causes the PSU voltage to dip and and cause dropout, Try another PSU if you have one (one with 2 A max draw); a 100uF cap from 5V to GND would help.  Also did you check the return value of SD.begin()?

Okay, thank you all for your efforts.
Finally, after changing the PSU and connecting the Arduino to another usb-port without operating system, I found the solution.
The problem was the SD-Card itself:
I swapped the SD-card with a newer (maybe more expensive(?)) one and it just works now. No matter if you connect the Arduino with the PSU or over an usb connection.
My assumption is, that there could be a different clock speed of the sd-card module on different voltages, which causes the problem. The old sd-card can't handle the fast speed and runs into an error (or just rejects it) on a write attempt...
Anyway, thank you again for your efforts!

I had this problem too, SD card not initiliasing on external power.
Having read this I turned down my external power voltage to 5.1 V
(from 7.5V ish)  and suddenly my SD card initialises on external power.
So a 'solid' 5 V must have the SPI running at a higher speed ( I guess) make sense.  The drawback is TFT is not as bright as should be.
...  better get a more 'expensive' SD card module LOL.
Ps - After some testing I had found that the SD card would work up to 6.4V on the power jack, above that the card would not initialise.   BTW I am not convinced it is a speed issue only because the SPI speed is locked by a divider to the Mega clock, so the Mega clock needs to change first.
Hope this helps


text:
Casting a struct member between uint8_t and char, with regard to serial transfer
Im simply trying to pass my payload to another device that has the same architecture and struct. I'm using UART to transfer, and modeling the protocol from EasyTransfer.
When I call Serial.print((char*)mydata.data); in Transfer it prints Hello World as expected.
Calling that same line in Receive prints a '?' to console. This may be some background behavior with Arduino, or I'm just not casting/handling the pointers correctly. How can I get this print out to function properly?
Transfer Sketch
#include <EasyTransfer.h>

//create object
EasyTransfer TransferObject;

//Struct contents must be idential to struct from other board
#define PAYLOAD_SIZE 255
struct SEND_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t data[PAYLOAD_SIZE];
};

//give a name to the group of data
SEND_DATA_STRUCTURE mydata;

void setup()
{
  Serial.begin(9600);

  //#define details(name) (byte*)&name,sizeof(name)
  TransferObject.begin(details(mydata), &Serial);

  pinMode(13, OUTPUT);

  //initalize not so random number generator
  randomSeed(analogRead(0));

}

void loop()
{
  //mydata.blinks = random(5);
  //mydata.pause = random(5);

  //Create payload to transfer
  char* payload = "Hello World!";

  //Fill array with data
  strncpy((char *)mydata.data, payload, PAYLOAD_SIZE);

  //Print sample
  Serial.print((char*)mydata.data);

  //send the entire struct
  TransferObject.sendData();

  delay(5000);
}

Receive Sketch
    #include <EasyTransfer.h>

//create object
EasyTransfer TransferObject;

//Struct contents must be idential to struct from other board
#define PAYLOAD_SIZE 255
struct RECEIVE_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t data[PAYLOAD_SIZE];
};

//give a name to the group of data
RECEIVE_DATA_STRUCTURE mydata;

void setup(){
  Serial.begin(9600);

  //#define details(name) (byte*)&name,sizeof(name)
  TransferObject.begin(details(mydata), &Serial);

  pinMode(13, OUTPUT);

}

void loop()
{
  //check and see if a data packet has come in.
  if(TransferObject.receiveData())
  {
    Serial.print("active");
    //print data payload
    Serial.print((char*)mydata.data);
    }

  //you should make this delay shorter then your transmit delay or else messages could be lost
  delay(250);

This is an exerpt and variant from this library

You're actually falling into a common problem with pointers in structs.
This structure:
struct SEND_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t *data;
};

contains three values: blinks, pause and a pointer to the data.
uint8_t *data;

That doesn't contain the data. That only contains the address that the data is stored at in memory.  When you transfer the struct it's that address that you are sending - then when the other end tries to print it all it can do is look at the address it's been told about and try and print whatever is in there - and that is complete garbage.
Instead of storing a pointer to the data you need to store the actual data itself. That means that you need to decide upon a maximum size for that data and pre-allocate the memory within the struct:
#define DATA_SIZE 40

struct SEND_DATA_STRUCTURE
{
  int blinks;
  int pause;

  uint8_t data[DATA_SIZE];
};

Now in order to get the data into that struct you need to fill that array with your payload. For strings the simplest way is:
strncpy((char *)mydata.data, payload, DATA_SIZE);

That will copy up to DATA_SIZE characters from payload into mydata.data.
Note that if payload contains more than DATA_SIZE-1 characters the data in mydata.data will not be NULL terminated. You can get round that by forcing NULL termination:
mydata.data[DATA_SIZE-1] = 0;

In your revised code your payload size is too big. The way the EasyTransfer library works is it has a single byte for the size of the payload. Your total payload size is PAYLOAD_SIZE + 2 ints - that is 255 + 2 + 2 = 259 bytes.  Placed into a single byte that gets truncated to 3. That means you are actually transferring one and a half integers and nothing else.
You need to ensure that your entire struct never exceeds 255 bytes. So you can have a maximum size of data, once you have taken your two integers into account (assuming 16-bit integers on an 8-bit Arduino), of 251 bytes.

Thanks Majenko! And how might I read the data post transfer? Serial.print((char*)mydata.data); shows no output on the recieving device

Did you replicate the same struct on the receiving end?

They appear to be the same, yeah. I can update that original post with my new code, if that helps.

Yes. Please do.

Okay, done. :-)

See my note at the end of my now modified answer.

I COMPLETELY overlooked that, thank you so much.


text:
Can I apply a Kalman filter to DHT11 data?
I want to apply a Kalman Filter to the humidity data which I retrieve of the DHT11.
How can I do that?

Learn about the kalman filter and what it does. It requires a certain understanding of what it is, what it is good for and why you would eventually use it. It seems to me, that at the moment this isn't your strongest topic.
Thereafter, figure out which !multiple! sensor values you have, since only with a "model" and an "observation" a filter of this kind makes sense in the first place.
To specifically adress your question: you can apply any filter to any data. The hidden question, if it makes sense in this case is not trivial to answer, since you didn't exactly provide the vast information. My guess is, you only have this one sensor, and it would be (at this state of knowledge) a reasonable idea to use a bandpass filter of sorts instead.

Hi, thanks for your reply. I have some knowledge about Kalman filter in theory. But i didnt yet apply anwhere and  I have some data in my figures. The humidty is acting +-%5 and I want filter this data. As i see on internet, some people use Kalman filter to temperature and humidity data for best results. I can research about applications of Kalman filter. May be someone help me for earn time.

As I said before, you didn't give enough information for anything. Please state a specific question. If you know, what a kalman filter is, you need to think about what your observation is, and what your model is. Then you need to state the covariances of both of these and then you implement the filter.
However, it seems to me, a lowpass is a better fit for a one-sensor problem.

Thanks, may be I should basicaly implement a smoothing filter for DHT data.

That's what I suggested. I think a kalman filter is a very nice tool, but it has it's place and it's nowadays used, where it really has no place at all. Just because it became famous, doesn't mean it does wonders for each problem. But still, all of this is guessing, since you didn't specify, what resources you have, or what your goal is. If you have many sensors and a lot of time, a kalman filter might just be the thing!

Btw: If you calculate a discrete time kalman filter for a linear system with only one measurement, the formulae automatically yield a simple lowpass filter (the steady state KF). This means, in the sense of the least quadratic error, it is best to just use a lowpass.

Hi, I applied a smoothing filter with samples of 100 from DHT data. This filter is already work as recursive and the results are very good for me. Anymore humidity data is coming without noise and peak. This is enough  for now. May be i can try discrete time kalman filter for my filter in the coming days.


text:
Irregularly triggering an ISR using timers
I seek to call an ISR routine after a fixed time of 400us. This action needs to be done every now and then (in the range of 0.8-3.0ms). For that matter, I thought I'd set timer2 to CTC mode, use OCR2A to set some TOP value for 400us and let the timer call the ISR routine after 400us. Within the ISR I would then stop the timer from triggering interrupts, until I need to count to 400us again, where I would activate the timer interrupt again.
This works, as expected, except for the fact, that after activating the interrupt for OCR2A again, it instantly triggers. The code below, produces a 1ms alternating signal, instead of 1ms+400us.
My question is, am I on a good way with this, or should I use the overflow ISR and preload the timer? Or any other method? The problem is, that after the 1ms waiting time in the main loop, I'd expect the counter to count from 0 to 100, meaning 400us. However on an oscilloscope I see the pin toggle each 1ms.
uint32_t timestamp;

void setup() {
  Serial.begin(115200);
  pinMode(9, OUTPUT);
  cli();         // disable global interrupts
  // Timer2 for counting (to release the pin)
  TCCR2A |= (1 << WGM21); // CTC mode, clear timer on compare match
  TCCR2B |= (1 << CS22); // Prescalar 64

  OCR2A = 99; // ticks, before ISR is called
  TIMSK2 |= (1 << OCIE2A); // enable timer compare interrupt
  TCNT2 = 0x00; // set the timer to 0
  // counting time[s] = (OCR+1)/(F_cpu/prescalar)
  // 99 = 400us | 124 = 500us
  sei(); // enable global interrups
  timestamp = micros();
}

void loop() {
  uint32_t now = micros();
  if (now - timestamp > 1000) {
    timestamp = now;
    cli();
    TIMSK2 |= (1 << OCIE2A); // enable timer compare interrupt
    sei();
    TCNT2 = 0x00;
  }
}

ISR(TIMER2_COMPA_vect) {
  // Serial.print(F("Here\n"));
  PORTB ^= 2; // set pin 9 high again
  // TCNT2 = 0x00; // reset timer for testing
  // deactivate the counter
   cli();
   TIMSK2 = 0x00; // unlink the ISR from timer
   sei();
}

However on an oscilloscope I see the pin toggle each 1ms.

That's what you expect. You set up the timer to fire every 1 ms. Since the ISR is called some time after that (and that is what toggles the pin) you will see the pin toggle every 1 ms.
I've reworked your example a bit to make it clearer, and to toggle the pin when we start the timer, and again when the ISR fires:
uint32_t timestamp;

void setup()
  {
  pinMode(9, OUTPUT);
  // Timer2 for counting
  TCCR2A = bit (WGM21); // CTC mode, clear timer on compare match
  OCR2A = 99;           // ticks, before ISR is called

  // counting time[s] = (OCR+1)/(F_cpu/prescalar)
  // 99 = 400us | 124 = 500us
  timestamp = micros();
  }  // end of seupt

void loop()
{
  uint32_t now = micros();
  if (now - timestamp >= 1000)
    {
    timestamp = now;
    TIFR2 = bit (OCF2A);   // clear any pending interrupt
    TCNT2 = 0;             // make sure counter is zero
    TIMSK2 = bit (OCIE2A); // enable timer compare interrupt
    TCCR2B = bit (CS22);   // start timer: Prescalar 64
    PINB = bit (1);        // toggle pin 9
    }  // end of if
}  // end of loop

ISR(TIMER2_COMPA_vect)
{
  PINB = bit (1); // toggle pin 9
  TCCR2B = 0;     // stop timer
}  // end of TIMER2_COMPA_vect

You can see from the scope output that the timer is started every 1 ms (as expected) because Cursor 1 is at -1 ms. The width of the pulse is 400 µs, as expected.

In my example I do not have to set so many settings each time I want to start the timer.

I took out the cli and sei so I saved you two lines. Don't forget to count them!
If you leave the timer running, it may well have reached the counter again (even though not generating an interrupt). Thus this line is important (even more so for you):
TIFR2 = bit (OCF2A);   // clear any pending interrupt

Also, if you leave the timer running, you may have a race condition. Say the timer is just about to tick over and generate the interrupt. You clear the flag (as shown above), but one machine cycle later the timer reaches the counter and sets it again, just before you get a chance to zero it. With the timer running, there could be combinations of when you enable interrupts, zero the flag, and clear the pending interrupt flag, that could occasionally work against you. Having the timer stopped is much safer.
Now if you are worried about the number of lines you need to start it (I wouldn't be) then you can move this line into setup:
TIMSK2 = bit (OCIE2A); // enable timer compare interrupt

Since you stop the timer in the ISR it doesn't matter if the interrupt is still enabled. Now you just have three lines to start the timer:
TIFR2 = bit (OCF2A);  // clear any pending interrupt
TCNT2 = 0;            // make sure timer is zeroed
TCCR2B = bit (CS22);  // start timer: Prescalar 64

I think we've agreed that clearing the compare flag is important, so this isn't any lengthier.

looking at your divisioning of the time axis, and from code, it is clear, that there is a 600us break, not 1ms!

Yes, there's a 600 µs break, because you start the timer every 1 ms, and it runs for 400 µs, thus there will be a 600 µs break.

I seek to call an ISR routine after a fixed time of 400us.

That's exactly what my posted code does. The pin goes high at the time you desire, in loop, and it goes low 400 µs later. That's what you wanted: a 400 µs interval.

As far as I can tell, the only additional thing is TIFR2 = bit (OCF2A);. In your code, you stop the timer alltogether. Isn't it cleaner the way I did, where I just disconnect the timer from the interrupt? In my example I do not have to set so many settings each time I want to start the timer. Or is it even desirable to use the overflow timer instead,... would that result in less hastle when starting the timer?

btw.: looking at your divisioning of the time axis, and from code, it is clear, that there is a 600us break, not 1ms! Since both timers (timer0 running micros() and timer2) run parallel, it is clear, that the break is 1ms-400us = 600us.

See amended answer.

Thanks for the additional explanation. I was originally worried about the flag, that was set on compare match, but now I totally agree, that stopping the timer is what I was looking for!


text:
How do I set my sampling rate?
I want to monitor the vibration from a motor running at 9.5Hz at 565rpm. I am using Arduino Uno and the ADXL345 as my condition monitoring equipment. How do I set the sampling frequency? I want to sample at at least 5x more than the operating frequency which is 50Hz, which will give a interval of 0.02 sec. However, to collect 2500 readings, I would need to take around 300 sec which is 0.12sec per reading different from the preset value at 0.02 sec.
Is my code wrong somewhere? Or what can I do to speed up the process?
#include <Wire.h>
#define DEVICE (0x53)    //ADXL345 device address
#define TO_READ (6)        //num of bytes we are going to read each time    (two bytes for each axis)
#define THRESH_ACT  (0x24)
#define THRESH_INACT  (0x25)
#include <SPI.h>
#include <SD.h>
File myFile;

// Declare Variable
byte runComplete; //setting the number of iteration
int i; //delare i for count
byte buff[TO_READ];//6 bytes buffer for saving data read from the device
float x, y, z; //Acceleration variable
float x1, y1, z1; //Acceleration variable

void writeTo(int device, byte address, byte val) {
  Wire.beginTransmission(device); //start transmission to device
  Wire.write(address);        // send register address
  Wire.write(val);        // send value to write
  Wire.endTransmission(); //end transmission
}

void readFrom(int device, byte address, int num, byte buff[]) { //reads num bytes starting from address register on device in to buff array
  Wire.beginTransmission(device); //start transmission to device
  Wire.write(address);        //sends address to read from
  Wire.endTransmission(); //end transmission
  int n = Wire.requestFrom(device, num);    // request 6 bytes from device
  if( n == num)
  {
      Wire.readBytes(buff, n);
  }
    }
void regAddress()
{
    int regAddress = 0x32;    //first axis-acceleration-data register on the ADXL345
    readFrom(DEVICE, regAddress, TO_READ, buff); //read the acceleration data from the ADXL345

     //each axis reading comes in 10 bit resolution, ie 2 bytes.  Least Significat Byte first!!
     //thus we are converting both bytes in to one int
    x = (((int)buff[1]) << 8) | buff[0];
    y = (((int)buff[3])<< 8) | buff[2];
    z = (((int)buff[5]) << 8) | buff[4];

    x1 = (x/256);
    y1 = (y/256);
    z1 = (z/256);

 Serial.println(" ");
    Serial.print("X: ");Serial.print(x1); Serial.println(" mm/s2");
    Serial.print("Y: ");Serial.print(y1); Serial.println(" mm/s2");
    Serial.print("Z: ");Serial.print(z1); Serial.println(" mm/s2");
    Serial.println(" ");

    myFile = SD.open("x30.txt", FILE_WRITE); // if the file opened okay, write to it:
    if (myFile) {
      Serial.print("Writing to X.txt...");
      myFile.println(x1);
      myFile.close();// close the file:
      Serial.println("done.");
    } else {
      Serial.println(F("error opening x.txt")) ;// if the file didn't open, print an error:
    }

    myFile = SD.open("y30.txt", FILE_WRITE); // if the file opened okay, write to it:
    if (myFile) {
      Serial.print("Writing to Y.txt...");
      myFile.println(y1);
      myFile.close();// close the file:
      Serial.println("done.");
    } else {
      Serial.println(F("error opening Y.txt")) ; // if the file didn't open, print an error:
    }
      myFile = SD.open("z30.txt", FILE_WRITE);// if the file opened okay, write to it:
    if (myFile) {
      Serial.print("Writing to Z.txt...");
      myFile.println(z1);
      myFile.close();// close the file:
      Serial.println("done.");
      Serial.println("");
    } else {
      Serial.println(F("error opening Z.txt")); // if the file didn't open, print an error:
      Serial.println("");
    }
       }

void setup()
{
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
  writeTo(DEVICE, 0x2D, 0);   //Turning on the ADXL345
  writeTo(DEVICE, 0x2D, 16);  //Turning on the ADXL345
  writeTo(DEVICE, 0x2D, 8);   //Turning on the ADXL345
  writeTo(DEVICE, 0x31, 8);
  Serial.println("Initializing Accelerometer...");
  Serial.print("Initializing SD card...");
  Serial.println("");
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    Serial.println("");
    return;
  }
  delay(2000);
}

 void loop() {
   if (runComplete == 0){
  for (i=0; i<2501; i=i+1){
 Serial.print("Number of iteration(seconds) = "); Serial.print(i);
 Serial.println("");
 regAddress();
     delay(200);
   }
  runComplete = 1;
  }
}

Hint: Try measuring the time to perform regAddress(). Looks like that is in the range of 0.1 second??

Hint: Improve regAddress() by first removing all the Serial.print() statements.

Hint: Use a single data log file. Write all three values to this file. Keep it open during the data collect.

After speeding up regAddress(), instead of delay(), use an if (millis() -previousMillis >20){previousMillis=millis();... } to control the rate.

Record the raw data, then after the sampling is done, re-read the data and report or recode the data in whatever format you need.

0.02 seconds means 20 ms, not 200. Your delay time is too long. Try using millis or micros instead of delay for average deviation. Using delay will accumulate lags caused by process time.
Try to sacrifice memory to log the data first (using for()  & data array), and then write to serial later.


text:
Error: "invalid use of incomplete type" and "forward declaration"
I have the following errors trying to use a TFT library function inside my library. My library uses the pointer to an instance of the TFT library in the constructor, as well described there:
Basic C++ programming, how to pass constructor argument into class?
The errors are:
error: invalid use of incomplete type 'class TFT'
_TFTscreen->background(0, 0, 0);

error: forward declaration of 'class TFT'
class TFT;

MESmenu.h:
#ifndef _MESMENU_H_
#define _MESMENU_H_

#include <SPI.h>
#include <SD.h>

class TFT;

class MESmenu{
public:
  MESmenu(TFT* pTFT) : _TFTscreen(pTFT) {};
  void start();
  void execute();
private:
  TFT* _TFTscreen;
};

#endif

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

void MESmenu::start(){
  _TFTscreen->background(0, 0, 0);
  _TFTscreen->text("starting menu...", 0, 0);
  //...
}

void MESmenu::execute(){
   //some code...
}

The Arduino sketch is:
#include <SPI.h>
#include <SD.h>
#include <TFT.h>  // Arduino LCD library
#include <MESmenu.h>  // my library

// --------- TFT LCD ---------
// pin definition for the due
#define sd_cs  7
#define lcd_cs 10
#define dc     9
#define rst    8
TFT TFTscreen = TFT(lcd_cs, dc, rst);

// MES menu class
MESmenu *mainMenu = new MESmenu(&TFTscreen);

void setup() {
  // initialize TFT
  TFTscreen.begin();
  TFTscreen.background(0, 0, 0);
  // set the stroke color to white
  TFTscreen.stroke(255,255,255);
  TFTscreen.fill(255,255,255);
  TFTscreen.setTextSize(2);
  TFTscreen.text("TEST", 0, 0);

  // Start menu
  mainMenu->start();
}

void loop () {
  mainMenu->execute();
}

The problem is related to the function:
_TFTscreen->background(0, 0, 0);

inside the MESmenu::start() in the .cpp file.
UPDATE:
As suggested by frarugi87 I've updated the question with the details of .h and .cpp files.
Those file are in the Arduino\libraries\MESmenu folder.
I try to change
class TFT;

with
#include <TFT.h>

and removed the #include  from the main arduino sketch.
This leads to the following errors:
libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)'
sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: first defined here

libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `PImage::read16(SDLib::File)'
sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/PImage.h:17: first defined here

libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `PImage::read32(SDLib::File)'
sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/PImage.h:17: first defined here

libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `PImage::loadImage(char const*)'
sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/PImage.h:17: first defined here

Please add the actual source code that gives the problem. It looks like you have forgot to include the TFT header file in the menu source file.

The posted code is almoste complete.
I have the MESmenu.cpp file that contais:
#include "Arduino.h"
#include "MESmenu.h"

void MESmenu::execute(){
  _TFTscreen->background(0, 0, 0);
}

And this give me the error.
If I put the code of the function "execute" in the .h file it works.
If the code is in the .cpp file I got the error.
I cannot include the TFT.h library in the .h or .ccp files, becouse it leads to "multiple definition"

Try to change
class TFT;

to
#include <TFT.h>

Then you can remove the #include <TFT.h> from the main arduino sketch.
Moreover you should at least write a piece of code to make the compiler include your library just once; this is the usual way to do it:
#ifndef _MESMENU_H_
#define _MESMENU_H_

#include <SPI.h>

...
the rest of your library
...

  TFT* _TFTscreen;
}

#endif

_MESMENU_H_ is any unique string (usually the filename is used, remembering that you can't put spaces or other punctuation marks except the underscore). And you should put it only in the header file (*.h or .hpp), not in the source (.c or *.cpp or *.ino)
EDIT:
The additional info lead me to analyze the library and.. there are problems with the library. Particularly the file TFT/src/utility/Adafruit_GFX.h has a big problem: it has the code for the functions.
To fix it, you have to modify the library.
Go into the folder TFT/src/utility/ and make a copy of Adafruit_GFX.h, calling it PImage.cpp.
Open Adafruit_GFX.h and delete everything between line 227 and line 370. This means that from
bool useFill;
};

#if defined(__SD_H__)  // Arduino SD library

#define BUFFPIXEL 20

void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) {

...

  return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip);
}

#endif

#endif // _ADAFRUIT_GFX_H

it should become
bool useFill;
};

#endif // _ADAFRUIT_GFX_H

Having done this, open PImage.cpp and delete everything above line 227, then delete the function Adafruit_GFX::image and the last endif and add, at the beginning, #include Adafruit_GFX.h. This means that the file should look like
#include "Adafruit_GFX.h"

#if defined(__SD_H__)  // Arduino SD library

#define BUFFPIXEL 20

// These read 16- and 32-bit types from the SD card file.
// BMP data is stored little-endian, Arduino is little-endian too.
// May need to reverse subscript order if porting elsewhere.

uint16_t PImage::read16(File f) {

...

  return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip);
}

#endif

Then try to compile again the program
BTW: the source I looked at is at this page.

I try with your suggestion, but now I got "multiple definition" releated to Adafruit_GFX.h that is included in the TFT library. Do you think that the problem could be in the TFT library itself?

@DavideTagliafierro multiple definitions of what?

libraries\MESmenu\MESmenu.cpp.o: In function 'Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of 'Adafruit_GFX::image(PImage&, unsigned int, unsigned int)'
sketch\test_MESmenu.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: first defined here

Ok, and where is MESmenu.cpp? Can you post the whole modified files in the question? Or at least the ino, mesmenu.h and mesmenu.cpp

Question updated with more details. I try to move all the functions from the .cpp file to the .h file it works (not tested on the board, but it compiles). I still doesn't understand why.

@DavideTagliafierro Modified the answer; it looks like the library is broken ;)

Thanks a lot for the hint. I tried to modify the library following your indications, but I got even more "multiple definition" than before. I think that the TFT library needs more changes... I ended up moving all the functions of my MESmenu library to the .h file and delete the .cpp file.
I was stuck since a long time on that and in one day you help me getting out. Thanks.

@DavideTagliafierro Glad you made it. Anyway you should not include the cpp file too; and the common rule is thaty you should only include h files, and in h files you should never define variables (only declare them - as external, of course) nor implement functions outside class definition; these should be performed in cpp or ino files..


text:
Why does pulse sensor shows gaps when I move it?
I modified the serial code in this way and I don't think the gap is produced by my edit even because it made it even before:
//////////
/////////  All Serial Handling Code,
/////////  It's Changeable with the 'serialVisual' variable
/////////  Set it to 'true' or 'false' when it's declared at start of code.
/////////

void serialOutput(){   // Decide How To Output Serial.
 if (serialVisual == true){
     arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
 } else{
      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
 }
}

//  Decides How To OutPut BPM and IBI Data
void serialOutputWhenBeatHappens(){
 if (serialVisual == true){            //  Code to Make the Serial Monitor Visualizer Work
    //ASCII Art Madness
    Serial.print(BPM);
    Serial.println("");

 } else{
        sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
        sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
 }
}

//  Sends Data to Pulse Sensor Processing App, Native Mac App, or Third-party Serial Readers.
void sendDataToSerial(char symbol, int data ){
    Serial.print(symbol);

    Serial.println(data);
  }

//  Code to Make the Serial Monitor Visualizer Work
void arduinoSerialMonitorVisual(char symbol, int data ){
  const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 1024;    // sensor maximum, discovered through experiment

  int sensorReading = data;
  // map the sensor range to a range of 12 options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);

  // do something different depending on the
  // range value:
  switch (range) {
  case 0:
    Serial.println("");

  }
}

63

63
63
63
63
62
62
62
62
62
62
62
63
62
63
64
63
63
64
64
65
65

65
68
74
78
86
95
105
112
123
141
167
154
136
128
123
125
123
127
132
104
93
92
92
89
83
77
73
69
65
70
70
71

You can find all the code here:
https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino
In the code I posted there is some code I don'f find useful but I can't delete it for reason linked to variables used for other functions I don't know I'm using.
You can also see huge changes in the heart rate that surely don't reflect the reality.

probably because of the badly formatted switch() case: statement. Have a look at what the Serial.println('"");

that's where I deleted things

ok I deleted the code there and now no problem. Any idea on how to fix the erroneous heart rates?

That might be something with the sensor and how it is connected, loose connections possibly.

do you mean that it's probably not enough tight on my finger?

I was talking about the electrical wiring side of loose connections, but also I am sure not having an good attachment to the finger might give bad readings, if its loose try making it tight but not to the point of loosing a finger :)

probably also the wires to the arduino weren't so fitted.

if the wires are loose the Analog reading will be very noisy

noisy in this case means that I will get the values I had?

Try using another serial terminal program (such as br@y terminal, Hterm, YAT etc.). In these programs you can control the timeout and also view line breaks.

One of the possibilities is when you move your finger, the sensor grip loosened and doesn't count a "beat". So the sensor emits data = 0, and it will cause
Serial.println("");

in your switch-case.

Upvote because this seems most likely.  If changing code doesn't matter, and the wiring is intact, then it must be the movement that is causing it.  Like the old joke:  "Doctor, it hurts when I lift my arm" and the Doctor says, "Then don't lift your arm"


text:
Can I use two sensors with different baud rate without problems on arduino?
One sensor has a baud rate of 115200, the other 9600. I think this will create problems in the serial because I can only choose one baud rate.
What do you think?
The first sensor is the pulse sensor, while the other is the gsr sensor by grove.
Link: http://pulsesensor.com/
Link 2: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor

Do you have a link to the pulse sensor? And do you mean this (http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor) "Grove GSR sensor"?

details updated

I think you have totally misunderstood the example code. Both of the examples you linked to used the Serial port to send data to your PC, not the sensor. For that purpose just choose one rate (eg. 115200).

You can only have one sensor on one serial port, and the baud rate is set on the serial port.
So as long as you have two serial ports, or SoftwareSerial ports (I wouldn't, it causes more problems that it solves - get a board with multiple UART interfaces) then yes you can have two baud rates.

ohh I'm disappointed I didn't consider this before

I don't understand if genuino 101 has two serials or just one "Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data. These pins are connected to the Serial1 class."

I would assume the Serial port is connected direct to USB (CDC/ACM) and Serial1 connected to the GPIO headers. The 101 is all a bit of a mystery since it's all based around an Intel module that no one outside of Intel knows much about.

if you are using multiple sensor use Arduino Mega board because it have 3 serial ports and Software Serial on UNO supports max baudrate of 115200 but sometimes this max baudrate will create the issues and you will receive the garbage

Yes I read about the Mega and I wondered if it's the only one in the market with this advantage. I'm wondering what does Intel and Raspy offer

You might be better off looking at Teensy or chipKIT rather than heavy Linux embedded computers.

There seems to be a misunderstanding. I've checked the particular sensor (http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor). And it uses analogread. Probably, the two code-examples would use different baud-rates for transmitting "log info" to the USB connection. Just using the same baudrate for both logging is possible (which means you can use both sensors).

seems that now I just need to search a way to plug them on the breadboard without using the grovehat, or I can use 3 on 4 pin of the digital port of the hat? The pulse sensor has 3 pins and not four.

One sensor has a baud rate of 115200, the other 9600. I think this
  will create problems in the serial because I can only choose one baud
  rate.

Why do you think the sensor has a baudrate?

Both the sensors seem to use the "serial connection" of the Arduino to log their information.

What do you think? The first sensor is the pulse sensor, while the
  other is the gsr sensor by grove. Link: http://pulsesensor.com/ Link
  2: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor

I think it'll work fine.

Looking at the facts of your sensors, the pulse sensor does have some kind of weird low-level timing/ADC access. But your Grove GSR sensor can basically be read out through an analog input.
So what to choose?
You could choose 9,6k or 115k2 (9600 or 115200). It wouldn't make all that much difference. 9600 or 115200 will work fine. 115200 is a lot faster, but for debugging purpose 9600 is used, since it's often default and (often) more reliable.
Wrapping up
I don't think there is an issue with the two serials. You can easily log both messages to the same serial output.
Try using 115200 since timing is essential in your case, you want your sensor to be response/fast.
They do both use the same analog to digital converter on your board. An Arduino can't check both sensors at the same time. But by switching between them very fast, you will get a resolution that's good enough.

I will try to use the GSR with 115k. Do I change also the serialBegin of the GSR code to make it work or it's enough to change it just in the Serial monitor?

The code and monitor need the same baudrate.


text:
Power problems stacked Arduino shields
I have a weird problem. I am currently building a BB-8. Therefore, I am using an Arduino Uno. On top, I have stacked an Adafruit Motor Shield v2.3 and, again, on top of this, I have stacked the Sparkfun USB Host Shield. The Arduino is powered by a 9V-Block battery, the motors are powered separately by two 18650 Li-Ion batteries. To control the two Pololu motors, which have a stall current of 1.6 amps each, I use a Xbox 360 wireless controller, where the receiver is connected to the USB Host Shield.
Now to my problem. Every seems to work fine, until i cover everything with a styrofoam hemisphere. Yes, you've read right. If that happens, the controller signals is lost and does not connect again, unless I restart the Arduino. I have uploaded a small video on youtube, where you can see the problem.
I guess, this is a power problem, since this issue does not occur, when I connect the Xbox receiver to my Mac. Has anyone an idea, how to solve this problem?
I already tried another power source. And the USB host shield should give enough power, since the specs are saying, that 500 mA is no problem, and hit is exactly the USB 2.0 spec. The combination of the shield shouldn't be a problem, too. I carefully chose this shields, because the motor shield is just using the pins A4 and A5, the USB host shield is using some of the digital pins, so I think there is no interference.
Thank you for your help.
EDIT
I have tested it a bit more now and i think i can reduce the probable reasons. First, i tried some other power supplies, from AA batteries on the VIN pin to external power adaptors. Next, i tried other xbox receivers and controllers. I also tried a playstation 3 controller with a Bluetooth dongle. Nothing solved the problem. I also covered the Arduino with other things than styrofoam, like a garbage can, cardboard and some metal box. This worked, so the problem was only with styrofoam. Now i haven't covered the Arduino, but i slowly got closer. About 20 cm from the Arduino, it stopped working. My clue: static electricity. Do you think this can be a problem? And if yes, how can i solve this?

So, I solved the problem. As is mentioned in my question, the problem was static electricity. I primed the styrofoam sphere with some special primer to make the styrofoam a little more stable and so on. That's it. Luckily I didn't touch the Arduino with the sphere. I think it would have damaged the Arduino.

Those 9v batteries are not known for their ability to supply current. Their best uses are long-term powering of low-current standby devices like smoke detectors. I'd first try replacing it with 4 double- or triple-A cells, whatever you can scrounge up for a quick test. My guess is when you cover the robot the Xbox receiver's current demand increases just enough to crash or reset something. A-cells may supply enough more current without the voltage sagging.

Thanks for the reply, i heard this before. I will check as soon as possible and give an answer.


text:
Setting Up a JavaEE app on an Arduino Yun Board
I'm looking for some reference material to start on a project I'd like to do.
I have an Open House at my school. My group project has been to create a little timesheet app using JavaEE. I just started looking for how to do this and if I can. But I would like to wow people a bit by setting this up using an Arduino Yun board. I know it has WiFi and I'm pretty sure I can run Linux on the little guy.
Any help would be greatly appreciated.

Sorry, forget it. 64Mb ram, 16Mb flash what the Yun has.
Java EE is magnitudes bigger (and bugger) than that.
You might try with Java SE embedded, the smallest profile might fit to 11Mb:
http://www.oracle.com/us/technologies/java/oracle-javase-embedded-ds-365290.pdf
and then you can roll your own web server.
(Personal comments: For little timesheets JavaEE is overkill, for anything modern JavaEE is obsolete - consider modern Java micro web frameworks, which offer magnitudes better performance than JavaEE).
What you can try is Raspberry PI, which works well with network, and Java (SE).
Not that well but also Java EE works: https://blogs.oracle.com/theaquarium/entry/glassfish_4_on_the_raspberry

Unfortunately we have to use JavaEE thank you for your support. I have acquired a Raspberry Pi 2 I will post my results :)

I am developing enterprise software for 20+ years, and I know that many companies still stick to JavaEE (for some really really awkward and twisted reasoning). On the other hand, many professionals say that JavaEE is obsolete for 10+ years, basically since the advent of Java microframeworks and full stack frameworks. Which are quite mature, and surprisingly good. :)


text:
Connect a USB slave into Arduino using FTDI
Probably I'm asking a nonsense question but I'm new at interfaces.
I want to connect an USB barcode scanner to an Arduino (Uno or Mega). I've read that I need a USB host shield to achieve this. But I don't have any. I have a FTDI, so I suppose I could plug the USB output of the scanner into the FTDI and connect the FTDI to the UART port of Arduino. Then, I would be passing the USB output to Serial.
Is it correct? Thanks and sorry if I said something stupid!

No, that is completely wrong.
In USB you have hosts and devices. A device has to connect to a host. Your FT232 is a device. The barcode scanner is a device. Both of them need to be connected to a host for them to do anything.
So you need a USB host shield to act as that host.
However - check the manual for your barcode scanner: it may well have a RS-232 mode that it can be switched into (may need a different cable attached).

Okay thanks! Yes, RS-232 was my second option. I need extra hardware apart from the cable, don't I?

Maybe, maybe not. It depends on your barcode scanner. Read the manual - see what it says.


text:
Micro USB to USB adapter m/m
I'm looking into working with an Arduino micro, and I'd like to be able to plug it into my computer directly(without a cable). I've been looking around, and the best thing that I found was this. The reason I haven't bought the linked adapter is because I've seen a number of bad reviews of the seller with close to half of the reviews being 1-star. Anybody have an idea where I can find something similar?
EDIT: I'm going to be using this for security testing, emulating a rubber ducky usb, so I need the computer to recognize the Arduino as an HID, not an arduino, but I also (obviously) need to be able to load my code onto it

http://www.ebay.nl/itm/2Pcs-Micro-USB-Male-to-USB-Female-OTG-Adapter-Converter-For-Android-Tablet-Phone-/281886855395?hash=item41a1c410e3:g:-7IAAOSwwE5WXp6V . But it's the wrong one like Majenko said

Hack a usb male onto the board and plug it in.

http://www.ebay.nl/itm/USB-male-type-A-to-micro-USB-male-adapter-converter-for-cellphone-camera-mp3-4-/231488735028?hash=item35e5cdc734:g:Qk8AAOSwbqpTwPNc This is the smallest I could find at the moment.

@J. Doe, This isn't really the place for shopping recommendations. Questions on Arduino, code, usage, etc are fine. I also don't see how an adapter would be way better as a cable. And Gerben has a sufficient answer (in my opinion). So I'm voting to close this question since it's more about USB connectors as actually about Arduino.

That adapter is not suitable. Not only is it the wrong gender on the large end, but it is designed for a completely different purpose.
That is an "On The Go" adapter which is designed for connecting things with a USB A plug (such as a memory stick, etc) to a mobile phone's USB socket.  It is not suitable for connecting things to an Arduino.
I have never heard of an adapter like you want, but I have heard of Arduino-like boards that plug direct into a computer like you want. One example is the Digispark from Digistump which is an ATTiny85 on a USB plug.

I've updated my question to clarify what I'll be using it for to see if it makes a difference.


text:
Get strings from Serial.read()
I want to read strings from Serial.read() to send them later.
To get the data from the Serial monitor I'm doing this:
String stringOne  = "";
int  incomingByte;

if (Serial.available() > 0) {

  while(Serial.available() > 0)
  {
     incomingByte= Serial.read();
     stringOne = String(stringOne + String(incomingByte));
  }

  Serial.println(stringOne);
  stringOne = "";

The issue is that when I type:
'a'

I got:
'97'

for
    'abc'
I got
'979899'

so on and so forth.
What should I do in order to get the same string I type?

Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

You're adding the ASCII value of each char to your string, hence you get numbers. See the various String constructors at:
https://www.arduino.cc/en/Tutorial/StringConstructors
Either cast the read byte to a char:
stringOne = String(stringOne + String((char)incomingByte));

or consider receiving characters as chars, instead of ints:
char incomingByte;

There is a perfectly valid one-method call which does all of this hassle easier and more efficiently: https://www.arduino.cc/en/Serial/ReadStringUntil
Note that you'll sooner or later anyhow have to add a framing prototcol. For example, you're sending down text commands to Arduino, and each command is separated by a new line character. ReadStringUntil will handle that very nicely.

Instead of using:
while(Serial.available() > 0)
  {
     incomingByte= Serial.read();
     stringOne = String(stringOne + String(incomingByte));
  }

Use the following to cast them to character:
while(Serial.available() > 0)
  {
     char incomingByte= Serial.read();
     stringOne.concat(incomingByte));
  }
Serial.println(stringOne);
stringOne="";


text:
How to make servo rotate for angle bigger than 180°
Connected servo motor (180°) to Arduino Uno R3.
Currently I am using a servo motor which have rotation angle specified as 180°, but I have a requirement to rotate to certain angles greater that 180°.
So do I need to go for a continuous rotation servo motor (360°), so that I can stop the motor at different angles greater than 180°, was my assumption true, will continuous rotation servo motor satisfy this requirement?
I am referring to Servo - Generic High Torque Continuous Rotation (Standard Size)
Current code, which I am using 180° servo motor.
Servo myservo;
int pos = 0;
void setup() {
  myservo.attach(9);
}

void loop() {
   {
    myservo.write(180);
    delay(15);
  }
}

Indeed, you need a continuous servo or to hack away the blockade.  These servos are limited to angles < 360 degree. Also keep your 8 bit limit in mind - 360 degree / 256 steps is your maximum resolution.

continuos rotation servo motors aren't 360 degrees. They are "infinite degrees". They are more like a motor, than a servo. See this video

The drawback of a continuous rotation servo is you don't know where it is; you code only tells it how fast to move, not where to move to.

Welcome to Arduino SE.  Be sure to take the tour at https://arduino.stackexchange.com/Tour

No. The continuous rotation servo rotates continuously and you can not control where to stop. You can control the rotation direction and the speed at a little.
What you need is either a special 270 degree servo, or you can use some mechanic, e.g. gears to transform the 0..180 rotation to 0..whateverrotation you prefer, depending on the gearbox ratio.
Alternatively, you can use stepper motors, where you can control steps in 1.8 degrees, and at the same time free to move as many turns as you prefer. Note though that steppers have two disadvantages compared to servos:

steppers require electrical current to hold their current position - for servo, the gearbox works ok for this
steppers don't know their initial position. So you need an optointerrupter or other means to learn the initial position first, then drive the steps to get to any position.
steppers require a more serious driving circuit, as well as a good power supply. Not for DIY robot running on batteries.

In industrial solutions, the stepper motor + some gearbox + an absolute rotation encoder is used to compose an industrial servo drive. (Similarly as a DC motor + some gearbox + an inexpensive potentiometer works in a model servo.)


text:
Thermistor value correct on Uno backwards on Nano
EDIT: upon further investigation: I found out that if I wired it Thermistor > resistor > GND values go one direction. If I wired it Thermistor > Resistor > 5v, it goes the other direction. So my new question: Which way is correct? One sketch assumes it works one way, and one the other.
I have some Thermistors from here. I have an Arduino Nano and an Arduino Uno, both set up identically with pictures of the wiring below. On the sketch below, when I heat up the thermistor the value increases on the Uno and decreases on the Nano.
// which analog pin to connect
#define THERMISTORPIN A0
// resistance at 25 degrees C
#define THERMISTORNOMINAL 10000
// temp. for nominal resistance (almost always 25 C)
#define TEMPERATURENOMINAL 25
// how many samples to take and average, more takes longer
// but is more 'smooth'
#define NUMSAMPLES 5
// The beta coefficient of the thermistor (usually 3000-4000)
#define BCOEFFICIENT 3950
// the value of the 'other' resistor
#define SERIESRESISTOR 9800

int samples[NUMSAMPLES];

void setup(void) {
  Serial.begin(9600);
}

void loop(void) {
  uint8_t i;
  float average;

  // take N samples in a row, with a slight delay
  for (i=0; i< NUMSAMPLES; i++) {
       samples[i] = analogRead(THERMISTORPIN);
   delay(10);
  }

  // average all the samples out
  average = 0;
  for (i=0; i< NUMSAMPLES; i++) {
     average += samples[i];
  }
  average /= NUMSAMPLES;

  Serial.print("Average analog reading ");
  Serial.println(average);

  // convert the value to resistance
  average = 1023 / average - 1;
  average = SERIESRESISTOR / average;
  Serial.print("Thermistor resistance ");
  Serial.println(average);

  float steinhart;
  steinhart = average / THERMISTORNOMINAL;     // (R/Ro)
  steinhart = log(steinhart);                  // ln(R/Ro)
  steinhart /= BCOEFFICIENT;                   // 1/B * ln(R/Ro)
  steinhart += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
  steinhart = 1.0 / steinhart;                 // Invert
  steinhart -= 273.15;                         // convert to C

  Serial.print("Temperature ");
  Serial.print(steinhart);
  Serial.println(" *C");
  Serial.println();

  delay(1000);
}

On the sketch below, the Uno is backwards and the Nano is correct. I'm sure there's something simple I'm missing, but I sure can't find it. Any suggestions?
#include <math.h>

double Thermistor(int RawADC) {
 double Temp;
 Temp = log(10000.0*((1024.0/RawADC-1)));
 Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
 Temp = Temp - 273.15;
 Temp = (Temp * 9.0)/ 5.0 + 32.0;
 return Temp;
}

void setup() {
 Serial.begin(9600);
}

void loop() {
  int val;
  double temp;
  val=analogRead(7);
  temp=Thermistor(val);
  Serial.print("Temperature = ");
  Serial.print(temp);
  Serial.println(" F");
  delay(1000);
}

Nano Wiring
Uno Wiring

There is no "correct" way. The thermistor and the resistor combine to make a voltage divider. Whether the thermistor is connected to +5V (AKA R1) or to GND (AKA R2) determines the formula to use to calculate the resistance.
The general form is:
          R2
Vout = ------- x Vin
       R1 + R2

To solve for R2 (thermistor connected to GND) you re-arrange to:
                 1
R2 = R1 x --------------
          (Vin/Vout) - 1

To solve for R1 (thermistor connected to +5V) it's:
     R2 x Vin
R1 = -------- - R2
       Vout

Vin, of course, is 5V, and Vout is a voltage you calculate from the analog reading on the Arduino.
Once you have the resistance you can then calculate the temperature. That part doesn't change regardless of the orientation of the thermistor.


text:
How can I exactly put my sensor at 4 Hz readings?
I'm using the grove GSR sensor: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor with this code:
const int GSR=A0;
int threshold=0;
int sensorValue;
const long interval = 1000;
void setup(){
  long sum=0;
  Serial.begin(9600);
  delay(1000);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){
  int temp;
  sensorValue=analogRead(GSR);
  Serial.println(sensorValue);
  temp = threshold - sensorValue;
  delay(250);
  }

There is the delay way to skip milliseconds or the millis() function. Do you have ideas on how can I implement it? The delay has the problem that doesn't consider the time the sensor uses to read the data.
Here's what I am trying
const int GSR=A0;
int threshold=0;
int sensorValue;
const long interval = 1000;
unsigned long startTime=millis();

void setup(){
  long sum=0;
  Serial.begin(9600);
  delay(1000);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){

  if((millis() - startTime) % 250 == 0) {
   int temp;
  sensorValue=analogRead(GSR);
  Serial.println(sensorValue);
  temp = threshold - sensorValue;

  }
  }

The difference between your first code and the second one is that the first one is blocking execution when it reaches the delay function, but the second code keeps running without being blocked.
Now your algorithm has a drawback, the loop may or may not reach the if condition exactly when the modulo is strictly equal to 0. So you may prefer to use something like :
unsigned long T = millis();

...

if( millis() - T >= 250 ) {
    ... // sensor stuff
    T = millis();
}

This idea is also presented in this article https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.
Another approach is to use Timers and Interrupts, but this is far more complicated (http://playground.arduino.cc/Code/Timer1).

So the first code uses more time? I had this impression when I measured less than 7600 seconds of data and it turned out to be 8000.

Both other answers are correct, but my usual way of dealing with this is
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
...
void loop()
{
    if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        // Do your job, such as
        int temp;
        sensorValue=analogRead(GSR);
        Serial.println(sensorValue);
        temp = threshold - sensorValue;
    }
}

The difference between this way and the other ones (Nick's way, i.e. saving millis and setting the startTime variable to it, or nico's one - which is worse - , to set it again), is that this way if there is some error (e.g. 260ms between two calls) it gets recovered by the next cycle (which will be of 240ms), while in their way it is not.

+1. lastReading = now; is the most common, and also the most appropriate when you want to guarantee a minimum delay between readings. But lastReading += period; is the correct solution when you want to guarantee the correct average period.

Something like this should do it:
const byte LED = 13;
unsigned long lastReading;
const unsigned long INTERVAL = 250;

void setup()
  {
  pinMode (LED, OUTPUT);
  }  // end of setup

void loop()
  {
  unsigned long now = millis ();
  if (now - lastReading >= INTERVAL)
    {
    lastReading = now;
    digitalWrite (LED, HIGH);
    delay (50);  // simulate reading delay
    digitalWrite (LED, LOW);
    }
  }  // end of loop

This code saves when we are about to do a reading, and uses that as the basis for when to do the next one. This eliminates the reading time from the equation. In my example code I throw in a 50 ms delay to prove the point.
The LED flashes exactly at 250 ms intervals.


text:
How to perform a data transfer to an external server
So I'm doing a project that involves getting sensor data from several sensors, and then sending them to an external server when a tragic occurs. But I've been having trouble figuring out how to send this data, and I am welcome to advice (I'm still relatively new to Arduino coding).
I'm using an Arduino mega, with a sim900 GSM shield and an SD card. The sensors are just analog reads and a GPS.
I've looked into FTP, a Xively account and http requests to a web server but couldn't figure it out.

Do you have internet service in that GSM shield?

Yup. The shield has a SIM card with 3G

You should check for: "Sim900 HTTP POST" on Google. There also should be a lot of libraries for this. You'll have to set up a webserver that accepts HTTP post messages. But you might try using a post dump test server first (https://posttestserver.com/) this worked great for me in the past. But I had an PIC microcontroller.

There is a good example of using the SubmitHttpRequest() in this article:
GPRS Shield SIM900 Arduino
You could easily modify:
mySerial.println("AT+HTTPPARA=\"URL\",\"www.yourwebsite.com/testing.php\"");
to include a string of the sensor value, and then using a PHP script to MySQL on your webserver. Maybe something like:
http://yourwebsite.com/testing.php?sensor1=5&sensor2=10


text:
Need to make an action just once when condition is reached
I'm making a device for the visually disabled that makes a sound when the water in a bowl reach certain levels.
I've already made the sensors for three levels of water and if statements to make the sound, but I need the sound to be played just once for every level change and it loops over and over.
How can I make it to sound just one time?
Here is my code:
#include <PCM.h>
const unsigned char sample[] PROGMEM = { //Here goes the sample
};
int low = 0;
int mid = 0;
int high = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (high > 50){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
  }
  else if (mid >50){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
  }
  else if (low > 50){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
  }
  delay(100);

Have you ever think to use a boolean flag variable?

A possible solution to your problem can be the following:
#include <PCM.h>
const unsigned char sample[] PROGMEM = { //Here goes the sample
};
int low = 0;
int mid = 0;
int high = 0;
bool first = true;
bool second = true;
bool third = true;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (high > 50 && first){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
    first = false;
  }
  else if (mid >50 && second){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
    second = false;
  }
  else if (low > 50 && third){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
    third = false;
  }
  delay(100);

In this way the sound for each level will be played only once. I hope this is what you were looking for.

Thank you!!, never came to my mind. I also added that when one flag comes false the others come true so i can go up and down

@Mattia I've added an answer that includes my thoughts on speed. I'll delete my other comments to avoid having double-information and a garbage in the comment section.

As an addition to the answer of Mattia.
I suspect you have something like:
void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (resetVariables){
     first = true;
     second = true;
     third = true;
     resetVariables = false;
  }

  if (high > 50 && first){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
    first = false;
  }
  else if (mid >50 && second){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
    second = false;
  }
  else if (low > 50 && third){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
    third = false;
  }

  if(buttonPressed){
    resetVariables = true;
  }
  delay(100);
}

A better practice would be to use another function
void resetFlags() {
  first = true;
  second = true;
  third = true;
}

And the main code would be:
void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (high > 50 && first){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
    first = false;
  }
  else if (mid >50 && second){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
    second = false;
  }
  else if (low > 50 && third){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
    third = false;
  }

  if(buttonPressed){
    resetFlags();
  }
  delay(100);
}

Would this be faster?

It would at least make your loop code more readable, instead of juggling flags around.
resetFlags(); would act immediately and independent from the flag checking etc.
It saves checking unnecessary if's (which equals a very little speed increase).
It saves 1 boolean (byte maximal in memory) which equals a very little memory/speed increase.

But why mind speed if you have a 100msec delay?
You could make it only output the water level when it changes. Then you can run the water checking extremely fast!
(It wouldn't spam your console, plus, writing to console takes considerable amount of time, compared to checking if's.)


text:
Arduino Pro Micro troubles
I recently bought a brand new Arduino pro micro from Amazon, I set it up according to the instructions on sparkfun, except that when I plug it in, Windows doesn't even show that it tried to install device driver software. I figured it might just be a windows 10 thing because the tutorial was written on windows 7, so I forged ahead, and updated the device driver for COM3 in device manager, and attempted to upload a simple test for HID emulation:
#include <Keyboard.h>

void setup() {
  Keyboard.write('z');
}

void loop() {
  Keyboard.write('a');
  delay(5000);
}

It compiled just fine, and the IDE said it started uploading to the device, However, as it was uploading (or so I thought) I read a little farther and realized that the IDE wasn't set to use the right voltage (3.3V instead of 5V) I closed the IDE and reopened my sketch, changed the voltage to match up, and tried uploading it again. Here, it got stuck on the Uploading... text and so again, I closed the IDE.
Only the LED closest to the USB port is on, and it's solid green. I've connected to my computer using a Micro USB to USB adapter, and I initially plugged the board into a USB 3.0, but then switched to 2.0 to see if it made a difference. I have also tried it on Ubuntu 14.04 with no luck. I don't think it's bricked because if it was, my computer would still recognize it, but not know what it was (according to sparkfun), and as a result, I have yet to try the debricking method they suggest. Any thoughts?

Just to check, which method did you use to reset the pro micro mentioned by sparkfun, did tou use the double tap of the RST pin?

@RSM yes, I connected a jumper cable to the gnd pin and tapped the reset pin twice with the other end of the wire.

Ok, do you have another arduino board you can use as an ISP programmer

@RSM no, but I can easily get one

or you can get an ISP programmer. Also the LED by the USB is power it will always be on. Does the PC make a sound when you reset the board. And adding to this the board does not have the Pro Micro bootloader but the leonardo, try switching to that board in the IDE and let me know what happens

@RSM switch the board to Leonardo? And no, it doesn't make any sounds or recognize that a device has been plugged in.

the board you bought does not have the pro micro bootloader, but the Leonardo's. This means double press of RST won't do anything. So changing the board option in the IDE won't do anything. Also if there is no sound from the PC when a board is connected then it is bricked or at least corrupted the boot section in someway.

@RSM So should I get a refund? When I plugged it in for the first time, there wasn't any sound or recognition that I had plugged something in.

if it never showed up as a device the first time you used it it is probably faulty. IMO I would probably get a refund if it is possible. Although if you are able to get an ISP, possibly one you can borrow, and see if the board will take to having its bootloader being re-flashed as then you can tell if the whole board is faulty. Also before re-flashing, for interest sake, get the ISP to dump the flash data, you will need to use avrdude, there are TUTs on this, and if the data looks garbled then its possibly a bad board

The Pro Micro, like the Leonardo, cannot automatically reboot into the bootloader like boards such as the Uno and Mega.  Instead it relies on the sketch running on it listening for a special combination of events (open the serial port, set the baud rate to 1200 baud, close the serial port) to activate the bootloader.
If, for whatever reason, you don't have a working sketch installed on the board (such as you aborted the upload part way through) then there will be nothing there to listen for the "reboot into bootloader" instructions.
So you need to manually enter the bootloader. Fortunately it should be easy enough, but timing is all important.
When you first plug the board in, or when you press the reset button, you get a few seconds where the board is in the bootloader.  On the Leonardo that is signified by the LED glowing and pulsating - I don't know off hand what is shown on the Pro Micro.
As long as you press the reset button just before you compile and upload your sketch, and as long as the upload portion doesn't take too long to start (tip: compile it before uploading, it makes it faster) it should then install the sketch into the board and from then on the auto-reboot should start working.
(Note: I haven't used a Pro Micro - this is all from my experience with the Leonardo which I believe uses the same bootloader.)

Still no luck, I followed the instructions that sparkfun gave for resetting, using a piece of wire I had, and there was no change in the LED. I did accidently touch the other end of the wire to the "RAW" connector, and the LED turned off, but otherwise there was no change, I'm still stuck on Uploading...

You have to retrieve the VID/PID numbers your board actually has and change your boards.txt accordingly. On my Linux computer I made a USB connection with my corrupted pro micro clone, "lsusb" does not show it, but if I pull rst-pin down (pulse) "lsusb" does show it for a few seconds. Now I know the vid:pid numbers. I edited boards.txt (~/.arduino15/packages/Sparkfun/hardware/avr/1/1/5/:
promicro.build.vid=0x1b4f      (edited 1b4f with vid outcome of "lsusb")
promicro.menu.cpu.16MHzatmega32U4.build.pid.0=0x9205  (9205 edited)
Then in Arduino IDE I gave a reset pulse, the port showed up. I loaded the sample blinky script from sparkfun (https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide#faq-change-pid), clicked "upload" and once again gave a reset pulse. The upload succeeded and my pro micro clone is back to normal.

That "reset > upload > reset > done" procedure actually resurrected my stuck Micro Pro. Upvote :)


text:
Arduino Uno to Processing, using Serial
So I have 7 different sensor I’d like to send to Processing, then use each of their values as variables inside different webcam filters.
I’m going off of this tutorial which has been helpful, but it doesn’t give linear steps – more like different techniques depending on what you’re trying to use it for.
In that tutorial, it shows two ways to initialize connection between Serial and Arduino – the Punctuation method and the Call-and-response method. I used the Punctuation method.
To sum up the Punctuation method, you put the sensor values into one string, separated with commas. Once the values are sent over, you split the string and put all of the values into an array. Once in an array, you can individually take out each of the values and turn them into variables that are usable in the draw loop.
My Processing sketch runs perfectly fine sometimes. Otherwise it will give either this error :
  Error, disabling serialEvent() for /dev/cu.usbmodem1421
  null

Or this one :

Does anyone see anything fishy with the syntax or structure I’m setting up?
(I took out all filter functions except the temp -> blur to make debugging easier.)
// get the serial lib :
import processing.serial.*;

// give port a variable :
Serial port;

// get the webcam lib :
import processing.video.*;

// give webcam a variable :
Capture webcam;

// sensors
int cap1, cap2, piezo, temp, axisX, axisY, axisZ;

void setup() {
  size(480, 360, P2D);
  smooth();

  webcam = new Capture(this, width, height, 24);
  webcam.start();

  String portName = "/dev/cu.usbmodem1421";
  port = new Serial(this, portName, 9600);
  //port.bufferUntil('\n');
}

void captureEvent(Capture webcam) {
  webcam.read();
}

void serialEvent(Serial port) {

  String reading = port.readStringUntil('\n');
  if (reading != null) {
    reading = trim(reading);

    int values[] = int(split(reading, ','));

    for (int valNum = 0; valNum < values.length; valNum++) {
      print(values[valNum] + "|");
    }
    println();

    if (values.length > 1) {
      cap1 = values[0];
      cap2 = values[1];
      piezo = values[2];
      temp = values[3];
      axisX = values[4];
      axisY = values[5];
      axisZ = values[6];
    }
  }
}

void draw() {

  // temp
  float t;
  if (temp >= 100) { //when analog pin unplugged
    t = 6;
  } else {
    t = 0;
  }

  image(webcam, 0, 0);
  filter(BLUR, t);
}

//if down key pressed, saveImage();
void saveImage()
{
  saveFrame("images/captured-####.jpg");
}

void keyPressed() {
  if (key == CODED) {
    if (keyCode == DOWN) {
      saveImage();
    }
  }
}

I’m thinking it’s an issue with memory, or maybe the way I’m sending/receiving the data is shoddy.
Apparently one of the disadvantages to using Punctuation rather than Call-and-response is that it can slow down the program if it contains a lot of graphic work… but why would it work in perfect time sometimes and then not work at all?
Any insight would be amazing!!

What did the print in SerialEvent print out just before the error?  Also, why if (values.length > 1)?  Seems like if (values.length > 6) would work better

The baudrate is really low, try a higher one (115200) maybe it is just a timing problem (pipe full/unready). Remember changing both - arduino and your program.


text:
Arduino clone CH340G (ATmega328P), MIDI over USB
I just bought my first Arduino compatible device, and I am greatly enjoying it. I finally could not resist the urge after going to an Arduino meetup, where someone showed me their Teensy connected to their laptop and reacting to MIDI signals over USB.
Not knowing anything, I bought my clone and soon learned about the whole CH340G limitation where it doesn't "just work" (I cannot simply use the USBMIDI Arduino library), and instead I need to run a software MIDI-serial converter command (ttymidi) in order to send the signals to my Arduino clone.
I've been reading up a bit (the amount of information out there is perhaps too vast and often outdated or simply doesn't exactly solve my problem) and have learned of V-USB and the project V-USB-MIDI but I am really out of my element here and do not know how to approach this to get it all working (since it is not just an Arduino sketch and .h header). Or even if this is a solution to my problem. I've read about some solutions which require using an AVR via some of the pins (as opposed to over USB) since you have to reprogram the chip in such a way that it no longer is programmable over USB once the sketch is uploaded, but if I understood it correctly, you can't do even this on the CH340G.
In any case, are there any examples of getting this working? A sketch or something? I downloaded the latest V-USB release, but I really don't want to make a mistake that will brick or otherwise ruin my device.
Basically: I want to just upload my MIDI sketch (with whatever necessary modifications or code) such that I do not need ttymidi to have the device recognized as a MIDI device (over USB) that I can just "plug 'n' play".

The CH340G is a clear USB to "UART TTL" converter. Some Arduino's or types of them use another AVR chip for the serial connection and can be reprogrammed. And some have the USB stack in the chip.
AFAIK the CH340G is not reprogrammable. Best option would be to just get an Arduino that has a reprogrammable USB interface.

"Horses for courses." Get a USB based MCU board not a UART based MCU board and do it properly.

@Mattia - Thanks for all of the suggested edits, most of them are very high quality. However, some have been a little inconsistent, and not as thorough as others. For example, could you take a look at the edits you made in this post, and the additional edits that I made when I reviewed your edit? Also, could you be a little more descriptive in your "Edit Summary", i.e. "fixed typos, spelling, inlined links", etc., as it makes reviewing the edits easier. Please note that I am not trying to discourage you in any way - like I said, your edits are generally very good. Keep up the good work :-)

@Greenonline sure, I got your point!

@Mattia - Thanks... Like I said, you are doing a great job! :-)

V-USB bit bangs some GPIO pins so that they speak the low-speed USB protocol.
This does not use the 'normal' USB connection through the CH340; you would have to solder a separate USB cable to those GPIO pins.
Programming would be no problem; the V-USB code is just normal code that runs on the MCU. (Programming through ISP pins would be required on hardware where USB communication and programming is handled with a second AVR MCU; in that case, the USB/MIDI code would run on that second MCU.)
Low-speed USB is not supposed to be used for MIDI, and as a software emulation, V-USB does not work very well, or efficiently.
If you want to create a USB device, you should use an MCU that actually supports USB in hardware, such as the ATmega32U4 or AT90USB646 used on some Teensies.

Does that mean it cannot be done with my at328p/ch340g without extra hardware?

The CH340 is a fixed serial-port device; this cannot be changed in software.

I have now purchased a couple of USB to TTL converters like this: http://www.ebay.ca/itm/181847253057?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT and this: http://www.ebay.ca/itm/191674164272?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT  would connecting these to some digital pins on the Nano enable me to do what I am trying to do, over this USB connection?

The PL2303 is a fixed serial-port device; this cannot be changed in software.

Your problem is that the ATmega328 itself does not have built-in USB support. If you want to have USB/MIDI support, you could rip apart a USB/MIDI interface and connect it to your ATmega; alternatively, replace your board with a Teensy.

You mean since the USB-MIDI device has HID support, right? Which is what the CH340g and FTDI chips don't have that the atmega16u2 (etc) can be flashed to have? In other words, it's not sufficient to have a USB-Serial/TTL interface chip, it would have to be a chip that does HID, right?

The protocol that USB-MIDI devices speak is not called "HID" but "USB MIDI". But yes, you need a chip that speaks that protocol, or a chip that has USB support and can be programmed.


text:
HC-05 to low cost AB shutter 3
I'm trying to connect a HC-05 to AB Shutter3 module. However, when I try to search AB Shutter3 address via AT commands (AT+INQ) I could not find AB Shutter3.
I want to integrate both, so that I can send commands from an AB Shutter button click to HC-05.
I also want to know whether the HC-05 needs to be in master or in slave mode.

I agree with Majenko. According to here you can not do it with hc-05. You need a hc-06 for this at least.

Why is the HC-06 sufficient while the HC-05 not? AFAIK the HC-06 is a reduced version of the 05 (only slave instead of master/slave)

I rather suspect the AB Shutter 3 is a Bluetooth HID device (like a keyboard or a mouse). The HC-05 can only communicate with Bluetooth Serial devices, such as the HC-06 or systems that can emulate a serial device (such as a computer or a smartphone).
You won't get them to communicate no matter how hard you hit them.


text:
Arduino fried? Onboard blink ok; offboard blink not ok
EDIT :
I have plenty of weird bugs. I will open another thread, and come back to this one when I have better understanding, rather than completely modify this one halway through. Sorry to every answerer for my electronic incompetence which led me to ask the wrong questions; I hope the other thread makes more sense.
I have recently exhumed an arduino from a cupboard, and can't seem to make even a blinking LED circuit work correctly.
Here's the sketch :
void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(1000);
}

This has been tried without the circuit, on pin 13, using the onboard LED, and it worked.
However, using the following circuit, it did not result in a blinking LED, using several pins (8, 9, 12, 13) and LEDS.
May I assume the arduino is fried?
Here is a thumbnail of the circuit :

What happens if you plug the white jumper into 5V rather than the current digital pin 12 ?

The LED doesn't light. I also just tested the LEDs with 3 x 1.5 batteries, and they are functional.

Was the battery test using the circuit as above ? If so which pole of the battery was connected to the white lead ?

Positive. Anyways, I tested several pins, and inverted the led poles on each test, just to be sure; measure thrice, cut once ;)

Is it just me, or that resistor looks odd? What is its value? Can you measure it with a multimeter? Did you try changing the holes on the breadboard?

My arduino is not bricked, I just don't know how many things I don't understand about electronics, and make every single mistake I can make, especially while cabling.

Here's a guide posted by Nick Gammon for checking if your Arduino is bricked Is My Arduino Bricked ?

I will read this guide; thank you for the link.

Try lighting up the LED without using any resistance in the middle, if that doesn't work try with a LED which consumes less current even if that doesn't work put the pin to HIGH state in code and measure the voltage of the given pin using a multimeter it should read above 3.3V. If neither of these work then you can be sure that your arduino is fried

Measuring between ground and that pin, is that correct?

Yes, Measure between the ground and the pin

I put a LED between GND and the pin directly in the arduino, and it worked

It it possible the non-working LED got wired backward (it wouldn't be the first time!)? If the LED is clear enough, hold it up to the light and look inside the plastic bubble. There will be two bits of metal, one attached to each lead. One of them is significantly larger than the other; that's the cathode and it needs to be connected to the more negative side of the circuit. Here's a picture.

You haven't exactly got the LED connected to pin 9, as in the code, have you?
I find it hard to believe that you can upload new sketches, but none of the pins work. Try pins 0 or 1, in the sketch, for example. Or the whole lot:
void setup() {
  for (int i = 0; i < 20; i++)
    pinMode (i, OUTPUT);
}

void loop() {
  for (int i = 0; i < 20; i++)
  {
    digitalWrite(i, HIGH);
    delay(1000);
    digitalWrite(i, LOW);
    delay(1000);
  }
}

Now methodically test every pin.

What happens if you plug the white jumper into 5V rather than the current digital pin 12

The LED doesn't light.

Something's wrong with your testing. The processor cannot be powering up, and accepting new sketches, yet not have power to the +5V pin.

you're going to have to wait 40 seconds (worst case) for one blink? I would advise setting all pins HIGH, then put a delay, then put all pins LOW and put a delay again. (Instead of putting a delay between each set)