text:
Arduino Mega 2650 + Matlab/Simulink - Serial decimation
I am performing a control analysis on an Arduino board.
As such, I want to minimize the board cycle duration.
(Faster board = faster controller).
Introduction:
I use Mathworks Matlab/Simulink to program the board.
I created a model in Simulink,
and embedded this model into my Arduino Mega 2650.
The model includes an Arduino Serial Transmit block.
I am therefore able to use Matlab software on my PC to request
serial transmission from the Arduino board to Matlab.
The Arduino Mega 2650 has the following serial constraints:

Maximum output buffer: 64 [byte]
Maximum baud frequency: ~115,000 [bit/s]

Problem:
To perform my control analysis,
I want to minimize the board cycle duration, and
I want to read several signals simultaneously.
The time it takes to read all signals sent
(as dictated by the baud rate)
is the primary obstacle in reducing my board cycle duration.
Requested Information:
Is it possible to reduce the board cycle duration
without reducing the duration in which
the serial transmission must be completed.
For example,
what if I run my board at 0.001 [s],
but I can only send all of my signals in 0.010 [s],
what will happen during my reads?
If I read every 0.001 [s], obviously I will not receive all of the data,
as this is not feasible in the time that I am allotting.
My concern is regarding what will happen if I read every 0.010 [s]:

Will the passing of several board cycles before the read completes affect the read?
Is there a method to lock the serial output buffer while reading
(such that the data does not change midread)?
How long does it typically take to refill the serial output buffer with the next set of data?

Conclusion:
Ultimately, I would like to run the board as fast as possible,
since I believe that this could significantly improve my controller's performance,
despite not being able to read these additional cycles.

Decimation is not a problem, and is quite easy to do if you program the Arduino the “standard” way. The problem is you are programming with a tool that abstracts a lot of things away. You will then have to check whether this tool provides a “decimate” block.

@EdgarBonet Decimation in the standard sense is easy.  I could delay my read requests, such that they only occur every X board cycles. My concern is that if I start a read, and the read requires 10 board cycles to complete, then the variables which I am reading will change 10 times before I finish reading.  If this occurs, will these variables be rewritten to the serial queue before I finish reading.  If so, this could create racing conditions in which a read is occurring at the same time as a write.

@EdgarBonet You are correct that using a 3rd party tool obfuscates even more of the things going on under the hood.

@EdgarBonet - Adding a rate transition block before the serial transmit helped the decimation.  As stated in Michel's answer, the data otherwise was sent to the serial buffer no matter how long I waited to read it.

I don't think there will be a problem in this.
I do not understand exactly why you can only send signals every 0.010 s.
The board runs at 16 MHz, that's 16 million cycles per second, however, every 'instruction' normally takes many cycles (let along parsed C/Arduino language).
What you can do is to copy the read information into an array and use it later.
Keep in mind that the serial buffer is 64 bytes. If more is read, data will be overwritten. However, if you copy the buffer into your own (larger) buffer it might help. Also you can change the 64 bytes (it's somewhere in the Serial library).
The buffer works (afaik) with a sort of circular buffer, meaning it can store 64 bytes maximum 'unprocessed' bytes. So you don't have to wait until the buffer is full before processing (actually, this is not even the best method). You can process it as long as there are bytes available.
The pseudo code can be as follows:
lastSignalSent = millis(); // last time signals sent

void loop()
{
    while serial bytes available
    {
        process bytes
    }

    if (millis() - lastSignalSent > 10) // More than 10 ms ago
    {
        Send signals
         lastSignalSent = millis();
    }
}

This assumes the serial byte processing can be done faster than they arrive, but if not, you run into problems anyway, since the serial buffer (of only 64 bytes) will be full too fast.

Are these edits common? Mathworks provides no interface to make these edits by default with their standard library blocks, but I believe that it would be worth asking for if the changes were simple and unlocked faster  and/or larger communication.

This mentions increasing the serial rate to beyond 115,200 [Hz]. But it seems to require non-standard libraries, etcetera and references not a library specifically for faster transmission - rather, it mention a library intended for use with DMX (lighting) communication.

I thought the max speed for serial is 115.2KHz, but DMX is 250KHz; maybe it uses a specific way of using the UART (or not an UART at all). There are many other ways to communicate (like SPI, I2C).

About edits of common libraries, it's not common, but sometimes it is needed. It would be nicer if it was something that could be passed as argument. This edit is not inside Mathworks, it's in the Serial library (and unrelated to Mathworks). For Mathworks/matlab probably another forum is best to ask for details.

I tested some things.  I assumed that if I waited, that the old data was immediately overwritten by new data if I did not grab it.  Instead, the data just builds up in the buffer until I read it. @EdgarBonet was correct in that I'll need to decimate it before it hits the Serial Transmit block.

True ... so increasing the buffer only helps if there are just some occasions where you cannot handle it fast enough, if it is a chronical ' problem', decimating the data is needed. Circular buffers are very often used in resource critical systems.


text:
Looking for an existing lightweight RF protocol
I'm currently looking for an RF protocol that doesn't use much power (generally much less than wifi) Something similar to simple AM radio, but with an authentication library readily available. ZigBee has about 250kbps bandwidth. I don't need nearly as much, so something with ~5kbps (dial-up speeds) would be acceptable. Using the Arduino Yun; so i'm constrained to the 5V output.
I'm also trying to stay away from the 2.4 GHz band.
Is there anything out there with this in mind? I was thinking maybe Z-Wave?
As far as the ZWave chips go this is where i'm at: http://pastebin.com/B0Yif3LS

Have a look at http://www.anarduino.com/miniwireless/ or http://lowpowerlab.com/blog/category/moteino/ or even http://jeelabs.org/.

source: Stack Exchange

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

sort: votes


text:
How to use ITG-3500 evb

I am trying to make motion capture and someone gave me these boards.
I think it's a test board for MPU 9500. I tried to google but I only found datasheets. What boards are these?
"ITG-3500 evb" is written on the back of the green board.
I think this is datasheet of green board maybe
"EV_ARM_XXAXA_D" is written on the back of the blue board.

You mentioned that you found some datasheets - could you edit your answer to include the links, please?

I have had to, briefly, play with these boards a while back, and although I used different revisions and versions of the boards, they are probably the same functionally. Unfortunately, I don't have any of my old notes as I have moved country. Regardless...
As Majenko says in his answer the green board is an evaluation board for the ITG-3500 3-axis gyroscope, which is presumably the SMD chip (in a QFN format) mounted on it, in the lower part of the board (looking at your photo). A data sheet on the similar ITG-3200 (note not the evaluation board itself)  can be found on SparkFun. To quote part of the product description:

The ITG-3200 is the world’s first single-chip, digital-output, 3-axis
MEMS gyro IC optimized for gaming, 3D mice, and 3D remote control
applications. The part features enhanced bias and sensitivity
temperature stability, reducing the need for user calibration. Low
frequency noise is lower than previous generation devices, simplifying
application development and making for more-responsive remote
controls.
The ITG-3200 features three 16-bit analog-to-digital
converters (ADCs) for digitizing the gyro outputs, a user-selectable
internal low-pass filter bandwidth, and a Fast-Mode I2C (400kHz)
interface. Additional features include an embedded temperature sensor
and a 2% accurate internal oscillator. This breakthrough in gyroscope
technology provides a dramatic 67% package size reduction, delivers a
50% power reduction, and has inherent cost advantages compared to
competing multi-chip gyro solutions.

In addition, in case it is of any use, here is the datasheet for the, again similar, ITG-3701, which I located on the Digi sales site. Frustratingly, I am unable to locate a datasheet for the ITG-3500 - however, you mentioned that you found some datasheets - could you edit your answer to include the links, please?
The Blue board is a "Gyroscope Evaluation Board: EV_INV-ARM" manufactured by InvenSense Inc., and to quote its product description:

The InvenSense ARM reference board provides a bridge function between InvenSense evaluation boards and a PC. It connects to a PC via USB and to InvenSense evaluation boards via SPI or I2C. The ARM processor on the reference board is not meant to be reprogrammed by the user. It contains all code necessary to be used in conjunction InvenSense evaluation boards. (Note that separate demonstration software may accompany the individual evaluation boards with which this device connects.)

Here is a link to the EV_INV-ARM DataSheet. The Atmel chip on it is possibly the AT91SAM7SE512 MCU, and here is a link to its product specification.
Software wise, you may find this Linux kernel driver for the ITG-3500 extremely useful.

TL;DR
It seems like you need to get hold of the separate demonstration software for the ITG-3500 evaluation board, according to the EV-INV_ARM's product description, in order to easily make it do something.

i edit it
I'm not sure that is correct datasheet. but picture of board is same

i read both of data sheet. but i can't understand the EV_INV-ARM.
In datasheet it mentioned reference board is not meant to be reprogrammed by user.
then this board is just used as connect gyrscope board(ITG-3500) with pc?

@jen6 that is what I understood as well. It is purely a communication medium to use with the evb

The green board is an ITG-3500 (3 axis gyroscope) evaluation board of some form.
The blue board is some form of microcontroller evaluation board. It probably has one of the Atmel SAM chips on it since it mentions ARM.
That's about all you'll get from us I'm afraid, unless there is the highly unlikely situation that someone here happens to have the exact same boards as you.

can i upload program at blue board like atmega128?

I would imagine so, otherwise it would be useless. The real question is how do you do that. There appears to be a JTAG connection that could be used, but that is all I can tell you. Read what the chip is (it has numbers and letters on it), find a compatible JTAG programmer, and the right software, and you're half way there.

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


text:
Arduino uno + cnc shield v3 + Stepper Motor Driver A4988 + AccelStepper?
I successfully run the AccelStepper examples on an Arduino Mega with a RAMPS 1.4 shield, two A4988 stepper motor drivers and two 17HS16-0284S stepper motors.
I used 3 jumpers on the RAMPS to set the microstep resolution to 1/16.
I used this code inspired by the Polargraph Server for Polargraph:
#include <AccelStepper.h>

/*
// for the Arduino Uno + CNC shield V3

#define MOTOR_A_ENABLE_PIN 8
#define MOTOR_A_STEP_PIN 2
#define MOTOR_A_DIR_PIN 5

#define MOTOR_B_ENABLE_PIN 8
#define MOTOR_B_STEP_PIN 3
#define MOTOR_B_DIR_PIN 6
*/

// for the Arduino Mega + RAMPS 1.4
#define MOTOR_A_ENABLE_PIN 30
#define MOTOR_A_STEP_PIN 36
#define MOTOR_A_DIR_PIN 34

#define MOTOR_B_ENABLE_PIN 56
#define MOTOR_B_STEP_PIN 60
#define MOTOR_B_DIR_PIN 61

AccelStepper motorA(1, MOTOR_A_STEP_PIN, MOTOR_A_DIR_PIN);
AccelStepper motorB(1, MOTOR_B_STEP_PIN, MOTOR_B_DIR_PIN);

void setup()
{
  motorA.setEnablePin(MOTOR_A_ENABLE_PIN);
  motorA.setPinsInverted(false, false, true);
  motorB.setEnablePin(MOTOR_B_ENABLE_PIN);
  motorB.setPinsInverted(false, false, true);

  motorA.setAcceleration(100);
  motorA.move(1000);
  //motorA.setMaxSpeed(100);
  //motorA.setSpeed(100);

  motorB.setAcceleration(100);
  motorB.move(1000);
  //motorB.setMaxSpeed(100);
  //motorB.setSpeed(100);

  motorA.enableOutputs();
  motorB.enableOutputs();
}

void loop()
{

  motorA.run();
  motorB.run();

}

I tried to use the same code with the same stepper motor drivers and motors on a Arduino Uno and a CNC shield v3 without success (I also used the 3 jumpers to set the microstep resolution to 1/16). The motors do not work and jitter.
What is wrong with my code?
Bonus questions:
I have taken this setup and code from the Polargraph server but I didn't get how I'm suppose to know how to use setEnablePin() and setPinsInverted() methods. In fact, I have troubles finding documentation about the CNC shield V3 and the A4988 drivers (I only found this page) to work with AccelStepper.

I don't know if I solved my problem, but I eventually found out that the Arduino Uno has not enough memory for the code I use to run my motors.

Manually set the ENABLE pins as OUTPUTs, i.e. add in the setup() function:
pinMode(MOTOR_A_ENABLE_PIN, OUTPUT);
pinMode(MOTOR_B_ENABLE_PIN, OUTPUT);


text:
Did I fry my ESP8266 module or was it something wrong with it?
I was trying to connect my Arduino Nano to my home Wi-Fi. To do that, I connected my Arduino to ESP8266 module.
I connected pins
Arduino  | ESP8266
3.3V     | VCC
3.3V     | CH_PD
D10      | RXD
D11      | TXD
GND      | GND

to connect to Wi-Fi, I used code which I found on internet.
What I'm getting is "FAILED - Timeout exceeded" which indicates there is no response from the ESP module. Is it possible I did something wrong and I fried it, or I connected it wrong? Or maybe it does not have enough power (I'm powering my Arduino via computer USB port)? I also read reviews which indicates customers who bought similar product from different vendors they had issues with firmware. Is it possible I have same problem?
Code
#include <SoftwareSerial.h>
SoftwareSerial softSerial(10, 11); // RX, TX
String WSSID = "xxxxxxxxxxxx";
String WPASS = "xxxxxxxxxxxx";
bool r;

void setup() {
  /* SETUP SERIAL COMMUNICATION */
  espSerialSetup();
  delay(2000); // Without this delay, sometimes, the program will not start until Serial Monitor is connected
  r = espSendCommand( "AT+CIFSR" , "OK" , 5000 );
  if( !r ) {
    r = espSendCommand( "AT+CWMODE=1" , "OK" , 5000 );
    r = espSendCommand( "AT+CWJAP=\""+WSSID+"\",\""+WPASS+"\"" , "OK" , 15000 );
  }
}

void loop(){
  r = espSendCommand( "AT+CIPSTART=\"TCP\",\"108.59.11.102\",80" , "OK" , 5000 );
  String getRequest = "GET /shiznic/ HTTP/1.1\r\nHost: www.rootpower.com\r\n";
  int getRequestLength = getRequest.length() + 2; // add 2 because \r\n will be appended by SoftwareSerial.println().
  r = espSendCommand( "AT+CIPSEND=" + String(getRequestLength) , "OK" , 5000 );
  r = espSendCommand( getRequest , "+IPD" , 15000 );
  //r = espSendCommand( getRequest , "world" , 15000 ); // page should respond with Hello, world.
  if( !r ) {
    Serial.println( "Something wrong...Attempting reset...");
    espSendCommand( "AT+RST" , "ready" , 20000);
    espSendCommand( "AT+CWMODE=1" , "OK" , 5000 );
    espSendCommand( "AT+CWJAP=\""+WSSID+"\",\""+WPASS+"\"" , "OK" , 15000 );
  }
  delay(3000);
}

void espSerialSetup() {

  // change baud rate so SoftwareSerial works better -- need a certain version of ESP for this to work and be retained after power cycle
  // make sure Serial Monitor port speed is set to 9600
  softSerial.begin(115200); // default baud rate for ESP8266
  delay(1000);
  softSerial.println("AT+CIOBAUD=9600");
  delay(1000);
  softSerial.begin(9600);
  Serial.begin(9600);
}

bool espSendCommand(String cmd, String goodResponse, unsigned long timeout) {
  Serial.println("espSendCommand( " + cmd + " , " + goodResponse + " , " + String(timeout) + " )" );
  softSerial.println(cmd);
  unsigned long tnow = millis();
  unsigned long tstart = millis();
  unsigned long execTime = 0;
  String response = "";
  char c;
  while( true ) {
    if( tnow > tstart + timeout ) {
      Serial.println("espSendCommand: FAILED - Timeout exceeded " + String(timeout) + " seconds" );
      if( response.length() > 0 ) {
        Serial.println("espSendCommand: RESPONSE:");
        Serial.println( response );
      } else {
        Serial.println("espSendCommand: NO RESPONSE");
      }
      return false;
    }
    c = softSerial.read();
    if( c >= 0 ) {
      response += String(c);
      if( response.indexOf(goodResponse) >= 0 ) {

        execTime = ( millis() - tstart );
        Serial.println("espSendCommand: SUCCESS - Response time: " + String(execTime) + "ms");
        Serial.println("espSendCommand: RESPONSE:");
        Serial.println(response);
        while(softSerial.available() > 0) {
          Serial.write(softSerial.read());
        }
        return true;
      }
    }
    tnow = millis();
  }
}

UPDATE
I changed connections to
  D11      | RXD
  D10      | TXD
and i also simplified my code
#include <SoftwareSerial.h>

SoftwareSerial esp(10, 11);

void setup() {
   Serial.begin(115200);
  while (!Serial);
  Serial.println("Started");
  esp.begin(115200);
  esp.write("AT\r\n");
}

void loop() {
  if (esp.available()) {
    Serial.write(esp.read());
  }

  if (Serial.available()) {
    esp.write(Serial.read());
  }
}

now I'm sending basic AT command to test connection, and still not getting any response. LED on ESP module is on, so I'm assuming it is working.

What kind of ESP8266 module? There are about 8 of them and they all have different wiring requirements.

@Majenko I'm using ESP-01

By the looks of the information you have provided, it looks as though you have not made the crossed serial connection: rx-tx tx-rx.
Your wiring:
Arduino  | ESP8266
3.3V     | VCC
3.3V     | CH_PD
D10      | RXD
D11      | TXD
GND      | GND

And when you intialize the software serial library:
SoftwareSerial softSerial(10, 11); // RX, TX

You declare D10 as RX and then connect it to the ESPs RX and ditto for the TX line.
What you need to do is the following:
Arduino  | ESP8266
3.3V     | VCC
3.3V     | CH_PD
D10      | TXD   //change to this
D11      | RXD   //change to this
GND      | GND

Also you need to ensure that the arduino TX line does not exceed 3.3V you can use a voltage divider, logic-level shifter board or a 74LVC245. This is important as the 5V arduino pins will damage a 3.3V device. This is a note as arduino nano is a 5V device from what I know(I may be corrected).

I swap connections, and i connected D10 to TXD and D11 to RXD as you suggested, but there is no change. I'm not an expert on Arduino, and I heard same thing about voltage, but i have two power pins, one with 3.3V and one with 5V. So I assume 3.3 from board should be fine.

If it is a 5V arduino, as in the voltage that the pins on the microcontroller go when set to HIGH, you will need to have a voltage divider as 5V WILL damage the ESP. Could you specify the exact model of you Arduino board? The 3.3V form the boards power is fine for the ESP power. The problem is if the 5V pin was exposed to the ESP pin.

I have clone of Arduino Nano v3, which as I said has 3.3v output. By any chance do you know best way to check is my ESP is fried or is it firmware problem?

You can use an arduino as a USB to serial device by bypassing the MCU and then using the terminal to send commands to the esp and see the response, also you can change baud rates to see where it is. This article would describe what I suggested, and I think there are programs people have made to reflash the firmware on theses things.

I tried to recreate same thing what was in that question, and i failed. When he cross cennected RX and TX, and he got something in response, and i didn't got anything. I don't think it is something which i did , as i got another one from same vendor, and i have same problems. I also tried to connect ESP directly to PC using FTDI module, but same issue, no response. do you have any idea what should be my next step?

What I could recommend then is attempt to see if you can flash new firmware onto the esp, follow http://www.esp8266.com/wiki/doku.php?id=loading_firmware, its from the esp forums so it is probably the most reliably source. Also I think there is probably a FAQ there to you can also check if it has any other ideas not mentioned here, might be worth a shot if the firmware doesn't fix it.

As far as I know, the 3.3v on the Arduino board might not have enough current for the ESP module, as it is very 'power hungry'.
I've had some hard time making my modules work properly, and your problem could be a number of things.
I will stick to Ockam's razor principle and go by the simple side.
In your code you are using 9600 baud,but the ESP8266 'base' speed is 115200. Try that speed (and CR+LF) also on your Usb cable and it might work.

have you looked at update? in that code i'm using 115200baud. I also connected to external power source which was around 3.15V and 0.65A. Still same result.

Oh, sorry, I haven't noticed. I still think it is not fried, it might have something to do with firmware update, my modules were stuck for a while untill I figured how to do it properly. Check this page for some details: http://www.electrodragon.com/w/Category:ESP8266_Firmware_and_SDK . Also, take a look at the ESPlorer IDE, http://esp8266.ru/esplorer/  (you need to connect GPIO0 to GND when flashing)

actually i'm getting somewhere, i think previous arduino was duff, now i'm getting some response, but it is meaningless crap. I tried using different boudrates  but still nothing.

That's a good sign, I am even more convinced it is about firmware update.


text:
Using ATtiny85, NRF24L01+, DHT2: can't get data from DHT22
I am trying to make a sensor that gets temperature and humidity values from a DHT22 and send it through NRF24L01+ to a Raspberry Pi 2 Model B.
To connect NRF24L01+ to ATtiny85 and to free two pins for the DHT22, I used this link.
There is a scheme of my sensor:

There is a photo of the test board with the sensor (sorry, it is very untidy, because I remade it many times before to fix the problem):

I program the ATtiny85 with Arduino IDE (with 8 MHz clock).
I used this library and radio communication is working perfectly (it can't be an error during the radio transmission).
Here is the code of my ATtiny85:
#include <DHT.h>
#include <RF24.h>

byte currentNodeAddr[6] = "1Node";  // Address of this node

// Struct for sending measured data
struct Data {
  uint16_t temp;  // Temperature value
  uint16_t hum;   // Humidity value
  int status;     // DHT22 module status
} data;

RF24 radio(2,2);  // Create instance of RF24 radio object
DHT dht;          // Create instance of DHT22 module object

void setup() {
  // Set up the radio
  radio.begin();
  radio.openWritingPipe(currentNodeAddr);
  radio.stopListening();
  dht.setup(3); // Set up the sensor on PB3 pin
}

void loop() {
  // This DHT library can calculate the delay but it may be 2+ sec
  delay(dht.getMinimumSamplingPeriod());
  // Get values from DHT22
  data.temp = dht.getTemperature();
  data.hum = dht.getHumidity();
  radio.write(&data, sizeof(Data));  // Send data to the Raspberry
}

But I can't the get temperature and humidity values from the DHT22. I used a lot of different libraries for DHT22 (for example, github.com/ringerc/Arduino-DHT22, github.com/nethoncho/Arduino-DHT22, github.com/jscrane/DHT22, etc.) and none of them works (they return zeros, NAN, or, generally, timeout error). And it seems that the connection with the DHT22 is correct (there were connection errors and I fixed them). I tried to use a lot of DHT22 modules, so the problem can't be a defective module.
Yes, I put a 2 second (and more) delay in between read requests. Yes, I added a 10k resistor between pin 1 and 2 of the DHT22.
Now I am thinking that the libraries work fine, but may be free pins (PB3 or PB4) of ATtiny85 can't receive data for some reason.
Tell me please where may be an error or a bug? Thank you in advance! And also many thanks to authors of all links and repositories that I have mentioned here!
EDIT (in accordance with frarugi87's answer):
At first I have grounded 3 and 4 pins of the DHT22.
When I program ATtiny at the 1 MHz, values are sent every 2 seconds (as it should be), but when I program ATtiny at 8 MHz, values are sent every 16 seconds (is it correct?).
I used the suggested code to check the radio library and it seems it works pretty well (values are being incremented and sent):

After that I used the suggested library (RobTillaart/Arduino v. 0.1.21) and at first time it returned some strange values (humidity and the status were 0 and temperature was MAX_INT value), but when I have tried to get only status value as string, the library also has returned -2 (DHTLIB_ERROR_TIMEOUT). This time I program ATTiny at 8 MHz:

Also I tried to get values without NRF24L01+ through I2C connection between the ATtiny85 and the Raspberry Pi. Result was the same (DHTLIB_ERROR_TIMEOUT):

Maybe the problem is in timings of ATtiny85 or in the program process?
I used these links (1, 2, 3) to set up Arduino IDE on Raspbian.
Here is list of useful links for this project which I found to implement it (I hope the authors will not mind that I posted their links here):
Arduino/AVR DHT projects and libraries:

Arduino Wireless Weather Station
Mini weather station with Attiny85
Easy IoT weather station with multiple sensors
ATtiny84 & RFM12B wireless sensor node
DHT11 HUMIDITY & TEMPERATURE SENSOR MODULE
DHT22 running @ 8MHZ
DHT22 not working with 8mhz clockspeed?
Adafruit DHT Library and ATtiny85
Class for DHTxx sensors
An Arduino library for reading the DHT family of temperature and humidity sensors
Using a RHT03 (aliases: RHT-22, DHT22, AM2302) temperature/humidity sensor from Arduino
Arduino-library for DHT11/DHT22 sensors reading
Efficient DHT library for Arduino
Feuchtesensor AM2302/DHT22
7 Segment Digital Thermometer using ATtiny 85
Wiring up DHT humidity sensors
Attiny85 RF Transmitter to Arduino Uno Receiver
Arduino library for the DHT22 humidity and temperature sensor
Arduino library for DHT11DHT22, etc Temp & Humidity Sensors
A simplified DHT11/DHT22/AM2302 library for use with the Trinket/Gemma
Arduino library for the DHT22 humidity and temperature sensor
Arduino sketch code for reading RHT03 (also known as DHT22, RHT22, and AM2302) temperature/humidity sensor

Arduino/AVR nRF24L01 projects and libraries:

Optimized fork of nRF24L01 for Arduino and Raspberry
Optimized Network Layer for nRF24L01(+) Radios on Arduino and Raspberry Pi
nrf24l01+ control with 3 ATtiny85 pins
NRF24L01 real life range test
Optimized fork of nRF24L01 for Arduino and Raspberry Pi
NRF24L01 SIX CHANNELS TO ONE RECEIVER
Arduino attiny support files for nRF24L01 RF modules
ARDUINO + RASPBERRY PI Switching light with NRF24l01+

Programming the ATtiny85 from Raspberry-Pi:

Programming the ATtiny85 from Raspberry Pi
Arduino IDE Installation
Arduino for other Chips
Tiny AVR Programmer Hookup Guide
ATtiny85 with Arduino IDE and Gertboard
Setting up the Arduino IDE on Raspbian

Arduino/AVR FR433 libraries:

433Kit is a collection of code and documentation designed to assist you in the connection and usage of RF 433MHz transmit and receive modules to/with your Arduino and Rapberry Pi
Tiny AVR Programmer Hookup Guide

Troubleshooting:

Wrong reading value for DH22 & get stuck after running for a while
DHT22 Sensor - sync timeout

Did you try the examples coming with the DHT library? Just to check if the library is working... or if the DHT is faulty...

Do you have access to another Arduino? If you had an Uno or some other Arduino with a serial support it would make debugging easier.

@frarugi87 Thank you for the suggestion. I tried to run examples all these days (and also without the radio module) but nothing changed.

@dlu Unfortunately I have no such boards.

@Alexander ok, then if neither the examples (without modifications) work, probably the DHT is faulty. Do you have another one to test?

@frarugi87 Yes, I have a pack of 15 DHT22 modules. I tried to use almost all of them. I have read in many forums that this module requires careful timing to grab data. Maybe there is something wrong with it.

I added an answer with two sketches for you to try. Try them and then report back

Probably I don't have an answer... but... I need same identic project. What libraries for Arduino AND Raspberry PI are used here? I hope someone will respond me...

@sineverba I added some links to the question that I used for the project or that were helpful for me.

@Alexander fantastic! Thank you very much. One question, please: you don't have neither one Arduino, all right? And you can program the ATTiny85 from the PI simulating Arduino / loading sketchs with the PI, all right? This is my also another my trouble... Thank you

@sineverba That's right. In this project I only worked with ATtiny85. As you can see in the question and in articles of the "Programming the ATtiny85 from Raspberry-Pi:" section, with Raspberry Pi you can assemble a scheme for programming AVR microcontrollers, install Arduino IDE and program ATtiny in the same manner as Arduino. But look at the answer. You have to choose microcontroller speed carefully (thats why I asked this question). But I used pretty old software 8 month ago. Maybe for now situation is better. By the way, I also plan to continue the work on this project in this month.

@Alexander thank you. Last question. In 2nd imahe I see on the right the PI console sniffing data. Path in title "/home/examoles" etc. Do you remembre what exactly script from which libraries was? Thank you!

@sineverba I have added the final code for both ATtiny85 transmitter and Raspberry Pi receiver to my answer below.

@sineverba I have also added the Makefile code to compile Raspberry Pi receiver to the answer below.

@sineverba Also in the answer I wrote that I used the next libraries: RobTillaart/Arduino DHT11, 21, 22, 33 library, Arduino driver for nRF24L01 http://maniacbug.github.com/RF24

Thanks to Rob Tillaart, the autor of the Arduino DHT library suggested by @frarugi87 (also thank him), the problem has been solved (see this issue for more information).
In my case to fix the problem there is only needed to to set a specific value of DHTLIB_TIMEOUT by leaving the definition #define DHTLIB_TIMEOUT 1000 in the dht.h file of this library and commenting other definitions written next to it:
// #ifndef F_CPU
#define DHTLIB_TIMEOUT 1000 // should be approx. clock/40000
// #else
// #define DHTLIB_TIMEOUT (F_CPU/40000)
// #endif

The ATtiny is programmed on 8 MHz. The DHT22 is working at a voltage of 3.3V with a 3K3 resistor.
The cause of the problem may be the way I program the ATtiny85 with old version of Arduino IDE installed in the Raspberry Pi (see comments to the @frarugi87's answer).
Libraries used:

RobTillaart/Arduino DHT11, 21, 22, 33 library
Arduino driver for nRF24L01 http://maniacbug.github.com/RF24

Here is the final code of the ATtiny85 transmitter and the Raspberry Pi reseiver respectively (I took the most part of the code from different examples of RF24 libraries and DHT libraries! Excuse me, if the code is not tidy.).
NRF24Transmitter.ino:
#include <dht.h>
#include <RF24.h>

#define DHT22_PIN 3
#define LONG_DELAY_MS 900000

byte currentNodeAddr[6] = "1Node";  // Address of this node

// Struct for sending measured data
struct Data {
  float temp;  // Temperature value
  float hum;   // Humidity value
  int status;     // DHT22 module status
} data;

RF24 radio(2,2);  // Create instance of RF24 radio object
dht DHT;          // Create instance of DHT22 module object

void setup() {
  // Set up the radio
  radio.begin();
  radio.openWritingPipe(currentNodeAddr);
  radio.stopListening();
}

void loop() {

  unsigned long startMillis = millis();
  while (millis() - startMillis < LONG_DELAY_MS);

  do {
    data.status = DHT.read22(DHT22_PIN);
    data.temp = DHT.temperature;
    data.hum = DHT.humidity;

    if (data.status != DHTLIB_OK) {
      delay(1000);
    }

  } while(data.status != DHTLIB_OK);

  radio.write(&data, sizeof(Data));  // Send data to the Raspberry
}

Receiver.cpp:
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <unistd.h>
#include <RF24/RF24.h>

using namespace std;

uint8_t addresses[][6] = {"1Node", "2Node", "3Node", "4Node", "5Node"};

// Struct for sending measured data
struct Data
{
    float temp;  // Temperature value
    float hum;   // Humidity value
    int status;     // DHT22 module status
} data;

RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ);

int main(int argc, char** argv)
{
    uint8_t currentPipe = 1;
    data.temp = -888;
    data.hum = -888;

    printf("BEGIN: %d\n", (int)radio.begin());

    radio.setAutoAck(1);
    radio.setRetries(15,15);
//  radio.setDataRate(RF24_1MBPS);
//  radio.setPALevel(RF24_PA_MAX);
//  radio.setCRCLength(RF24_CRC_16);

    radio.openReadingPipe(1, addresses[0]);
    radio.openReadingPipe(2, addresses[1]);
    radio.openReadingPipe(3, addresses[2]);
    radio.openReadingPipe(4, addresses[3]);
    radio.openReadingPipe(5, addresses[4]);

    radio.startListening();

    radio.printDetails();

    sleep(1);

    cout << "Start!" << endl;

    while(true)
    {
        cout << "Waiting for data..." << endl;

        while (radio.available(&currentPipe))
        {
            cout << "Reading: " << addresses[currentPipe - 1] << "..." << endl;

            radio.read(&data, sizeof(Data));

            cout << "Temp: " << data.temp << endl;
            cout << "Hum: " << data.hum << endl;
            cout << "Status: " << data.status << endl;
        }

        sleep(1);
    }

    return 0;
}

Here is Makefile to compile the receiver.cpp:
#############################################################################
#
# Makefile for librf24 examples on Raspberry Pi
#
# License: GPL (General Public License)
# Author:  gnulnulf <arco@appeltaart.mine.nu>
# Date:    2013/02/07 (version 1.0)
#
# Description:
# ------------
# use make all and make install to install the examples
# You can change the install directory by editing the prefix line
#
prefix := /usr/local

# Detect the Raspberry Pi by the existence of the bcm_host.h file
BCMLOC=/opt/vc/include/bcm_host.h

ifneq ("$(wildcard $(BCMLOC))","")
# The recommended compiler flags for the Raspberry Pi
CCFLAGS=-Ofast -mfpu=vfp -mfloat-abi=hard -march=armv6zk -mtune=arm1176jzf-s
endif

# define all programs
#PROGRAMS = scanner pingtest gettingstarted
PROGRAMS = receiver #gettingstarted gettingstarted_call_response transfer pingpair_dyn test
SOURCES = ${PROGRAMS:=.cpp}

all: ${PROGRAMS}

${PROGRAMS}: ${SOURCES}
    g++ ${CCFLAGS} -Wall -I../ -lrf24-bcm $@.cpp -o $@

clean:
    rm -rf $(PROGRAMS)

install: all
    receiver -d $(prefix) || mkdir $(prefix)
    receiver -d $(prefix)/bin || mkdir $(prefix)/bin
    for prog in $(PROGRAMS); do \
      install -m 0755 $$prog $(prefix)/bin; \
    done

.PHONY: install

Ok, let's troubleshoot it.
Try with the following sketch:
#include <RF24.h>

byte currentNodeAddr[6] = "1Node";  // Address of this node

// Struct for sending measured data
struct Data {
  uint16_t temp;  // Temperature value
  uint16_t hum;   // Humidity value
  int status;     // DHT22 module status
} data;

RF24 radio(2,2);  // Create instance of RF24 radio object

void setup() {
    // Set up the radio
    radio.begin();
    radio.openWritingPipe(currentNodeAddr);
    radio.stopListening();
    data.temp = 0;
    data.hum = 1;
    data.status = 2;
}

void loop() {
    data.temp++;
    data.hum++;
    data.status++;
    radio.write(&data, sizeof(Data));
    delay(2000);
}

You should see a bunch of data being sent to the raspberry every second (you should see temp = 1, hum = 2, status = 3 then, after two seconds, temp = 2, hum = 3, status = 4 and so on. Of course you need something to display the data.
If there is some problems then it's the radio library fault, otherwise let's integrate the DHT22.
So, AFTER having tried the previous sketch and confirming that everything is working, download the library from here, install it and then use this sketch:
#include <RF24.h>
#include <dht.h>

dht DHT;

const byte DHT22_Pin = 3;

byte currentNodeAddr[6] = "1Node";  // Address of this node

// Struct for sending measured data
struct Data {
  uint16_t temp;  // Temperature value
  uint16_t hum;   // Humidity value
  int status;     // DHT22 module status
} data;

RF24 radio(2,2);  // Create instance of RF24 radio object

void setup() {
    // Set up the radio
    radio.begin();
    radio.openWritingPipe(currentNodeAddr);
    radio.stopListening();
}

void loop() {
    data.status = DHT.read22(DHT22_Pin);
    data.temp = (int)DHT.humidity;
    data.hum = (int)DHT.temperature;

    radio.write(&data, sizeof(Data));

    delay(2000);
}

Now, instead of displaying increasing numbers, it should say the temperature, the humidity and, most important, the status:
 0 -> OK
-1 -> ERROR_CHECKSUM
-2 -> ERROR_TIMEOUT
-3 -> ERROR_CONNECT
-4 -> ERROR_ACK_L
-5 -> ERROR_ACK_H

Check if this works.
IMPORTANT NOTE: I read somewhere that sometimes the ground pin on the DHT is 3 instead of 4. Try grounding both pins if something does not work.

Thank you very much for your answer! I will describe results by editing the question.

Done! The question has been edited.

This "When I program ATtiny at the 1 MHz, values are sent every 2 seconds (as it should be), but when I program ATtiny at 8 MHz, values are sent every 16 seconds (is it correct?)." is absolutely not normal You should have experienced the opposite behavior. First of all I onticed you are using an old version of the Arduino IDE (1.0.1). Try updating to 1.6.x (instructions here if sudo apt-get upgrade does not find the version; you need to use latest raspbian version - jessie)

Then setup arduino 1.6.x to use the attiny85: see here how to do that, particularly "Adding Third Party Boards to the Arduino v1.6.4+ IDE" and I think you can use the recommended attiny85 board repository, but the second one (drazzy) is more updated; you can choose one. Then select the board from the list and try uploading again. With both 1MHz and 8MHz the 2seconds delay should remain 2 seconds delay

You are right, it is not normal. But this is all I could install and get to work on the Raspbian Wheezy. I will try it again later with your suggestion. By the way, a solution has been finally found. I will post it a little bit later in another answer. Thank you for your your help and for useful links!


text:
What is the proper way to send data through http using sim908?
Preamble:
I have a sim908 shield and I'm trying to send some data periodically to a server using AT commands.
For every command, I wait for the response to check if everything is working.
Actually the sketch works but, often, I noticed errors during http request.
State of the art:
Here it is the sequence of AT commands (not the entire code) into the loop:
1) Check the Network Registration and, if necessary, wait
AT+CREG?

2) Set params for GPRS connection (no user or password required)
AT+SAPBR=3,1,"Contype","GPRS"
AT+SAPBR=3,1,"APN","web.omnitel.it"

3) Get current bearer
AT+SAPBR=2,1

4) If bearer == 0,0,0,0 (not assigned) get a new bearer
AT+SAPBR=1,1

5) Init HTTP
AT+HTTPINIT

6) Set CID and URL
AT+HTTPPARA="CID",1
AT+HTTPPARA="URL","www.someurl.com/service.php?p1=1&p2=2"

7) Execute the HTTP command (POST)
AT+HTTPACTION=1

8) Close HTTP connection
AT+HTTPTERM

Question:
Why HTTP init (step 5) or HTTP posting (step 7) often fails? What is wrong in this procedure? I'm missing something? There is a way to make the procedure more stable?
Thank you in advance :)
Important update:
If occurs an error during sending data via HTTP, is a great idea to renew the bearer (step 4)
Answers to the comments:
a) Shield has an antenna and it works. If I try to disconnect the antenna, code still  search the network (step 1) untill I reconnect the antenna.
b) Some times I have this error initializing HTTP (step 5):

AT+HTTPINIT
+CME ERROR: 3

Some times I have only "OK" as response posting data (step 7) instead of:

+HTTPACTION:1,200,xxx

Or this response:

+HTTPACTION:1,600,0

c) I have error at step 4 (AT+SAPBR=1,1) only if I execute the command when I have yet a bearer. The error in this case is:

AT+SAPBR=1,1
+CME ERROR: 3

For this reason I do a check (step 3)

Does it have an antenna? And what particular error do you get back? Post messages should get an http+error back with a nummer.

Did you get the results of the new bearer settings returned by AT+SAPBR=1,1? Post the exact +CMEE error code you're seeing.

I edited the original post

CME ERROR: 3 is "operation not allowed".
And HTTP response code 600 isn't officially something, try reading the message header and body, but it may be "invalid request".

Thank you Paul. From documentation (http://www.waveshare.com/w/upload/4/4e/SIM908_AT-Command-Manual.pdf) 600 is "Not HTTP PDU".
This error doesn't appear every time. For what you know, my procedure is correct?

@Lipsyor, hard to tell, has been quite a time since I worked with those GSM modules and I don't have one available to test. If AT+HTTPINIT fails, you might want to force close an existing http setup with AT+HTTPTERM.

You mention two different error messages.
1. AT+HTTPINIT fail
You get +CME ERROR 3. Which means "operation not allowed".
This can be due to an improperly closed HTTP setup.
If you get this error (or just always do before setting up), call AT+HTTPTERM to be sure that it's closed.
2. AT+HTTPACTION=1
I notice you're trying to do a POSTmessage, while your variables are in the URL (which is GET style afaik).
I've found a source that states you need to call AT+HTTPDATA with apropriate values.

Tell the module that you will be sending 192 bytes of data and it can timeout after 10 seconds of inactivity.

After that, the device will say DOWNLOAD, and you can send the POST body.

After this command you get the DOWNLOAD URC then you can type in 192 bytes of data within 10 seconds. The typed data is filled in a local buffer of the module and is not yet posted to the server. In the post body is the multi part form data which contains the necessary headers and data to post a file with name data.txt with 10 bytes of data.
  AT+HTTPDATA=192,10000

And after that you can send the POST message.

Execute the HTTP POST command so that the buffer contents are POST to
  the server AT+HTTPACTION=1 OK

You will get a return message that states the HTTP code (200 'OK') and the amount of bytes received in the return message.

+HTTPACTION:1,200,141
  This URC means that the data was successfully posted to the server and received 141 bytes of data.
  which is the server response to your HTTP POST

You can use AT+HTTPREAD to receive these bytes.

The below command tells the module that we want to read the received data AT+HTTPREAD The below is the data
  received from the server
  +HTTPREAD:141 Successfully dumped 0 post variables. View it at http://www.posttestserver.com/data/2015/10/07/07.41.291690063480 Post
  body was 0 chars long. OK

(Scroll a fair bit down in the source, the first part is on HTTP GET: http://www.raviyp.com/embedded/194-sim900-gprs-http-at-commands)
You could also omit this by using HTTP GET since it's somewhat easier.
If all else fails, you can set up a TCP IP connection with the GSM module and manually set up the HTTP GET/POST message.

Thank you for answer. About HTTPINIT fail, note that (step 8) I use HTTPTERM for each loop. I'll try what you suggest about GET and POST.
However I don't understand why sometimes my code works and other times no.

I tried but without results. Now I'll try to wait more time for responses.

@Lipsyor which option did you try? I suggest trying to make a GET request working before you try the POST requests.

I tried to wait more time for response: now GET and POST works. I have some problems with HTTPINIT: when it fails I can't recover with HTTPTERM and I had to try more times.
I'm considering to reset shield if more than two or three errors occurs consecutively.

Hmm, atleast we're making progres here ;) have you checked how other libraries handle errors? If http init fails, you could check all the above again, at+creg?, at+sapbr and whatnot. Having to reset it is a bit crude (if it happens often). But it's good to have such a feature built in anyway.

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


text:
How can I be engaging the arduino mega with OBD-II UART card?
Currently I have been doing a project where I need to know the speed of the vehicle, I have implemented the following code but the results have not been good because when the vehicle is in motion always prints STOPPED.
I connected the OBDII-UART card from Sparkfun with Arduino MEGA.
The connection of the cards shown in the image attached below

  1.   char rxData[20];
  2.   char rxIndex = 0;
  3.   String inputString = "";
  4.   boolean stringComplete = false;
  5.   void setup(){
  6.   Serial.begin(9600);
  7.   Serial1.begin(9600);
  8.   Serial.flush();
  9.   Serial1.flush();
  10.   //Reset IC
  11.   Serial1.println("ATZ");
  12.   delay(1500);
  13.   getOBDResponse();
  14.   Serial.println(rxData);
  15.   clearBuffer();
  16.   getOBDResponse();
  17.   Serial.println(rxData);
  18.   clearBuffer();
  19.   //Sets IC to defults
  20.   Serial1.println("ATD");
  21.   delay(1000);
  22.   getOBDResponse();
  23.   Serial.println(rxData);
  24.   clearBuffer();
  25.   getOBDResponse();
  26.   Serial.println(rxData);
  27.   clearBuffer();
  28.   Serial1.println("ATSP0");
  29.   delay(1000);
  30.   getOBDResponse();
  31.   Serial.println(rxData);
  32.   clearBuffer();
  33.   getOBDResponse();
  34.   Serial.println(rxData);
  35.   clearBuffer();
  36.   Serial1.println("010D");
  37.   delay(1000);
  38.   getOBDResponse();
  39.   Serial.println(rxData);
  40.   clearBuffer();
  41.   getOBDResponse();
  42.   Serial.println(rxData);
  43.   clearBuffer();
  44.   Serial1.println("ATDP");
  45.   delay(1000);
  46.   getOBDResponse();
  47.   Serial.println(rxData);
  48.   clearBuffer();
  49.   getOBDResponse();
  50.   Serial.println(rxData);
  51.   clearBuffer();
  52.   //Bus initiation
  53.   Serial1.println("ATSI");
  54.   delay(3000);
  55.   getOBDResponse();
  56.   Serial.println(rxData);
  57.   clearBuffer();
  58.   getOBDResponse();
  59.   Serial.println(rxData);
  60.   clearBuffer();
  61.   Serial.flush();
  62.   Serial1.flush();
  63.   }
  64.   void loop(){
  65.   /*
  66.   if(stringComplete){
  67.   Serial.println(inputString);
  68.   inputString = "";
  69.   stringComplete = false;
  70.   }
  71.   */
  72.   Serial1.flush();
  73.   Serial1.println("010D");
  74.   getOBDResponse();
  75.   Serial.println(rxData);
  76.   clearBuffer();
  77.   getOBDResponse();
  78.   Serial.println(rxData);
  79.   clearBuffer();
  80.   }
  81.   void getOBDResponse(){
  82.   char inChar = 0;
  83.   while(inChar != '\r'){
  84.   if(Serial1.available() > 0){
  85.   if(Serial1.peek() == '\r'){
  86.   inChar = Serial1.read();
  87.   rxData[rxIndex] = '\0';
  88.   rxIndex = 0;
  89.   }else{
  90.   inChar = Serial1.read();
  91.   rxData[rxIndex++] = inChar;
  92.   }
  93.   }
  94.   }
  95.   }
  96.   void clearBuffer(){
  97.   int i;
  98.   for(i = 0; i < 20; i++){
  99.   rxData = '';
  100.   }
  101.   }
  102.   void serialEvent1(){
  103.   while(Serial1.available()){
  104.   char input = (char)Serial1.read();
  105.   inputString += input;
  106.   if(input == '\r'){
  107.   stringComplete = true;
  108.   }
  109.   }

I have based on the example is the page of the card https://learn.sparkfun.com/tutorials/obd-ii-uart-hookup-guide/connecting-to-an-arduino, but when I set the protocol sends me Ok, but when I ask for the speed I send a message from Seeking I do not understand.Information truck tried to read from the console on a laptop
How can I accuratley get the speed of the car?
Well, now I require to get the speed I have entered the command according to the command table ELM327 I quickly attached.

I haven't studied the linked code in detail, but could you please add some more information? Comparing the example on the linked website (respectively on https://github.com/sparkfun/OBD-II_UART/blob/master/Firmware/obdIIUartQuickstart.ino), your commands are totally different. The linked sources send "010D" for vehicle speed and "010C" for RPM, what seems to make sense.

I have not achieved anything, still no answer card I tested with different cars but still showing me an error, someone who can help me please

Only was a baudios

On behalf of @Alejandro: I've been trying to make this circuit work but the only thing I am receiving after de 010D command is "SEARCHING......." "STOPPED" "SEARCHING......." "STOPPED" "SEARCHING......." "STOPPED". Do you experienced this problem? Or can you please share the code, bauds configuration, etc, that you used? Thanks in advance


text:
Arduino server to read from multiple clients
Socket programming question here.
My interface comprises of an Android device(client), A wireless module hosting an access point, and an Arduino Uno(server).
My Android client class works when 1 user connects and sends commands to my Arduino server class.
I want to make my program friendly to many users at the same time.  My server will only read in values from 1 connected client at a time.
After some research I've found that Arduino does not allow multithreading naturally, which is why i've decided to look into a number of libraries.
The Arduino library that I've decided to use for this specific issue is protothreads.  Unfortunately, i've been unable to find any examples of creating a server with Arduino to accept a client's commands.  Furthermore I'm having a lot of trouble figuring out how to make this library work in my favor.
Now for my question,

How exactly can I allow my Arduino server to constantly listen for
  incoming messages from more than 1 client device?

Or is there something I can do on the client side that would make this communication possible?
A lot of work is handled by my Wifly Module.
I was able to telnet in and set my ipaddress/port#/etc..
Anything sent over IP goes straight through my Module and straight to my arduino.
My
Client Code:
My Server:
WiFlySerial wifi(rxPin ,txPin);

void setup() {
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  //Serial.println("I'm in the LOOP!!");
  androidLed();
  serialLed();

}

void androidLed()
{
  if(wifi.available() > 0){
    data = wifi.read();
    Serial.println(wifi.getDeviceStatus());
    Serial.println(data);
}
}

Without knowing your exact implementation details...
You should be OK as long as you don't have multiple clients connected at the same time. You may think that there are multiple clients connected to your server, but the connection is closed after the resource is obtained by the client over a protocol.*
The standard flow of a server on Arduino:

A client connects to the Arduino.
The Arduino code realizes this connection and reads the data provided by the client.
The Arduino then sends some data back to the client.
The Arduino closes the connection and waits for another client to connect.

This happens relatively fast so multiple people can connect.
If you call a function like .close(); after you send data to your client, you should be okay. If you don't, redesign your code to have this element (avoid loops and blocking functions) and make sure to have your client reconnect every time it sends a command.
I wouldn't mess with this and Protothreads because I'm not sure that the Arduino hardware is designed to be able to handle multiple connections at the same time. [Citation needed]

Good, I was hoping I was overthinking this.  I'm not using a .close() and maybe put too much focus on the android aspect of my code.  I will try this and see if it works.

@TheTokenizer are you using the Ethernet shield connected to a wireless access point or what?

I'm hosting an AP using an RN-131C.  A wifly wireless module.  With this I am able to create my AP and send commands through it via my Android device.  I am using my Arduino as a server to respond to these commands and I am using the Wifly Serial Library.

@TheTokenizer you are doing this a different way than I thought. Can you post a minified working example of your code so I can look at it and see if it closes the connection each time? (I.e. remove everything except what's needed to make a connection)

This is my working code with only 1 android device sending signals.. I'm going through the library and looking for close/open functions that would be of use now.

@TheTokenizer looking at that it seems like it's using a UART type of protocol. I'm afraid that this device only allows one connection at a time at the hardware level, forget the software level.

IS there no work around?

I don't know I'm looking it up now

@TheTokenizer does it even compile right https://github.com/perezd/arduino-wifly-serial/blob/master/WiFlySerial.h that says that there is no available() in that library...

Let us continue this discussion in chat.


text:
Mysterious behavior when using objects
I am writing a project that involves using complementary filters to combine gyroscope and accelerator readings in 3 directions. The relevant code is below.
class CompFilter {
 public:
   long prevTime;
   float alpha;
   int angle;

   CompFilter(float Alph);
   int combine (float gyroRate, float accelAngle);
};

CompFilter::CompFilter(float Alph) {
 alpha = Alph;
 prevTime = 0;
 angle = 0;
}

int CompFilter::combine(float gyroRate, float accelAngle){
  Serial.println("Here THREE");

 long timeStep = millis() - prevTime;
 if (timeStep == 0) { timeStep = 1;}

 angle = alpha * (angle + gyroRate * timeStep);

 angle += (1.0 - alpha) * accelAngle;

 prevTime = millis();

 return angle;
}

//Global Objects
CompFilter *senPitch; CompFilter *senRoll;  //Declare Complementary Filters

//Adjustable Parameters
float alpha = .5;   //Constant affecting Gyro's vs. Accel's influence on sensor reading

void setup(void)
{
  //Open Data Channel
  Serial.begin(115200);
  Serial.println(F("IMU Complementary Filter Tester")); Serial.println("");

 //Initialise TMU sensors
 sensorInit(accel, mag, gyro);
 senPitch = new CompFilter(alpha); senPitch = new CompFilter(alpha);
  Serial.println("HERE ONE");
}

void loop(void)
{
 //Variables for reading sensors
 sensors_event_t accel_event, mag_event, gyro_event;
 sensors_vec_t   orientation;

 // Retrieve Sensor Readings
 accel.getEvent(&accel_event);
 gyro.getEvent(&gyro_event);
 mag.getEvent(&mag_event);

 Serial.println("HERE TWO");

 int anglePitch = senPitch->combine(gyro_event.gyro.y, orientation.pitch);
 int angleRoll = senRoll->combine(gyro_event.gyro.x, orientation.roll);

}
I had to keep track of a couple of pieces of information for each direction, so rather than trying to use parallel arrays, I created a CompFilter class. I think I am using the correct syntax in the class and constructing the object, but I am getting very unusual outputs from Serial.print().
RE ONE
RE TWO
Here THREE
Here THREE
entary Filter Tester

Depending on how I fiddle with the code, I can get setup() repeating over and over or loop() running once before silently failing.
I suspect that I have misdirected a pointer somewhere, but I am not sure. I would appreciate any help.

senPitch = new CompFilter(alpha); senPitch = new CompFilter(alpha); -- looks like a duplicate.

Simply remove that line and use static instances instead i.e. CompFilter senPitch(alpha); CompFilter senRoll(alpha); You might need to move the declaration of alpha or use a default constructor and a setter instead.

Dave X is absolutely right.
I never assigned the senRoll pointer to an object. Then when I tried to dereference it, it went to some random address. I guess there are very few memory protections, so rather than causing a seg fault it just caused erratic behavior.
Thanks for the help.


text:
Connecting arduino to an existing circuit
I have a little clock with a button on it that i need to push four times every second hour. I am trying to get the arduino micro to do it for me.
I am trying to figure out how to connect the arduino to trigger it. The clock is operated by a CR2 (3.0V) cell battery. Is there a way to do this without a transistor? If not what do i need? How can i find out how much amp my circuit requires?
The red arrow is pointing on the cable i think triggers the clock, and i think the black arrow is pointing on the cable that is the clock gnd.
(edit: I have found similar questions explaining the process with transistor, but not without..)

What happens if you do not push the button four times every second hour?

This might be answerable by someone who has the same model of clock to test, but its otherwise unlikely unless you add a bunch of information. Eg:  What brand and model is it?  Is it battery operated? What's the battery voltage if so?  Do you have a digital voltmeter to take measurements?  Do you have an oscilloscope to look at waveforms?  By "black cable is the clock gnd", do you mean the red wire with a black arrow pointing to it, or do you mean that bit that appears to be a black wire next to a gray wire, near test point P14 at lower left?

The voltage of the battery is 3.0V. "black cable" should be "black arrow". I have a digital voltmeter and when a push the button with the yellow arrow it is connection between the the cables that i have pointed out with arrows.

Guess an opto-isolator could work. https://en.wikipedia.org/wiki/Opto-isolator

@MikaelPatel Have you never watched Lost?

Why is a transistor not allowed? If it's a case of doing it with only the Arduino then you may struggle to achieve it. If you don't care how it's done so long as it doesn't use a transistor then you may have more luck. However, a transistor is by far and away the easiest solution; a MOSFET doubly so.

You might try attaching an Arduino IO through a resistor to pin 4 (where your red arrow points), and Arduino ground to pin 1 (where your black arrow points).  Because the clock is battery-operated, you can connect its ground to the Arduino's ground without problem.
Before attaching the Arduino, use your DVM to measure the voltage between pins 4 and 1, with the switch open and with the switch closed.  In following, I'll suppose you have measured 3V when the switch is open and 0V when it's closed.  This would indicate that the clock's circuit pulls or drives pin 4 high when the switch is open.  In initial experiments, I'd start with a 1KΩ or so resistor (eg, any resistor between 500Ω and 2000Ω) in series with an ammeter and the Arduino IO.  If you measure at most a few microamps of current in both the “switch open” and “switch closed” cases (see below) then the circuit should function ok with the resistor in place (since there will be only a tiny voltage drop across it).  [If, on the other hand, you measure several milliamps of current in either case, then my ideas about the clock circuit might not apply; in which case you might need an optoisolator or relay.]
To represent switch operation, put the Arduino IO into INPUT mode to represent an open switch, and into OUTPUT LOW to represent a closed switch.  For example, in setup() say
pinMode(ClockPin, INPUT);  // Also does digitalWrite(ClockPin, LOW);

and in your loop() say stuff like
if (TheTimeHasCome) {
   for (int k=0; k<4; ++k) {
      pinMode(ClockPin, OUTPUT);  // Presses the button
      delay(50);                  // Holds the button
      pinMode(ClockPin, INPUT);   // Releases the button
      delay(50);                  // Wait between buttons
   }

The comment // Also does digitalWrite(ClockPin, LOW); is a reminder that pinMode(ClockPin, INPUT); has two actions: it sets ClockPin to be an input instead of an output, and takes the corresponding PORTx bit low (ie, resets a bit in PORTB, PORTC, PORTD, or whatever).  If we had said pinMode(ClockPin, INPUT_PULLUP);, then the corresponding PORTx bit would have been set high, and the pin would be weakly pulled to Vcc, eg +5V.  It would be a mistake to send 5V to the clock, as it's likely that would exceed its voltage tolerance.
Since pinMode(ClockPin, INPUT); leaves the appropriate PORTx bit low, there is no need to use digitalWrite() separately in the sketch.  When ClockPin is an input, its high impedance allows the clock to pull pin 4 high; when ClockPin is an output, its 0 level connects pin 4 to pin 1.

Connect the Arduino and your clock grounds together.
Get a small resistor - no less than 1 kOhm - and connect your VOM (in current mode) in series with the resistor and your Arduino output pin.
Set the output pin to LOW and observe
Did the clock reset?
What was the current on your VOM?
If the clock reset and the current was more than 20 mA get a bigger ( 10 kOhms )  resistor and try it again.
If the clock reset and your current was less than 20 mA you are done.
And if you really want to isolate the clock from Arduino use low current LED and connect the cathode to the output pin and anode to the clock.
Keep the resistor in the circuit.
Than you will also have an indicator of "circuit is active".

Yes, This can be achieved without a transistor.
As the circuits would be on isolated power supplies: Arduino circuit on one and the clock on another, you can use a Solid State Relay.

Use the relay with your Arduino (5v or 3.3v) and wire the relay contacts parallel to the clock switch. This will isolate any power issues as clock will be powered with its own power and Arduino will be powered with its own.
You can program Arduino with proper delays to actuate the relay accordingly.
Hope this helps.

Very few relays will have a coil current low enough to allow it to be powered directly from an Arduino - you'll need a transistor for the relay.

@CharlieHanson thanks for the pointer; a SSR is also a relay. I'll update my answer.

authors: Асмир Абдимажитов


text:
What would be the Western / American equivalent of the Troyka Shield and modules?
I'm taking an online course on Arduino robotics, produced by the Moscow Institute of Physics and Technology. The lectures are translated into English, but all of the parts referenced are by the Russian company Amperka.
It seems the key parts I need to follow along are

The Troyka Shield
Troyka modules, like the potentiometer, Hall sensor, etc
Matryoshka Z set

As fun as it would be to order from the Russian store, there are several practical reasons I'd prefer an American (or Western) equivalent. If they even ship to the US, payment would be difficult, shipping slow, instructions in Russian, etc, etc.
I've spent time and money shopping around Adafruit and SparkFun, but as an Arduino beginner, I'm not 100% sure which parts are analogous to these Russian ones. If a more experienced hobbyist recognizes any of these and can help me identify it, that would be most appreciated.
I think the Troyka components are a necessity, but the Matryoshka Z is a "nice to have" bundle of components. I'm using Arduino Uno, so compatibility with that would be preferable, but I think one of his Russian controllers is supposed to be a clone of the Leonardo, so if these parts only work with a Leonardo that's fine too.
The shield is shown here:

In this view it's combined with its modules using this special snap-together PVC:

The instructor said that he helped invent the PVC components, so I guess there may not be an American version of that yet (or is there)?

This probably has no complete, general solution.
The Troyka Shield looks to be just a prototype shield with footprints for ground/power/data cables.  Likely you can just use a different mechanism to connect things, solder some additions to an everyday proto shield, or you could relatively quickly duplicate this in a PCB design program and have boards made.
There are probably many alternatives for the mechanical structure, ranging from cardboard and foam tape or hot glue to various toy building block sets, or you could try to duplicate their idea by making some grids on an everyday 3D printer.  Likely none of these satisfy formal ESD concerns - but then, Arduino projects are usually considered disposable enought that people rarely worry about this.
The modules are going to be the most problematic part.  They seem to encompass many of the peripheral parts and chips usually used in Arduino projects, and most of those are already available in canonical modules from a range of vendors like Adafruit, Sparkfun, Seeed, etc on down to clones and simple executions of chipmaker's recommended circuits.  So for most of these, you'll probably have no problem finding a substitute, the possible complication is if you have enough understanding of the details of each assignment to make any necessary changes to accommodate for differences in pinouts, components values, etc between the specified Troyka module and the chosen substitute.
You may in the end find it's better to just follow tutorials written around the specific parts and modules you find more readily available for purchase, and thus avoid the needs to translate the details.
Do beware however, that there are some really bad tutorials out there on the Internet - some in places like Instructibles are simply terrible engineering to the point where it is a minor miracle if they even worked once for their authors, and even some on the Arduino site cut corners in ways that can't be recommended.

Thanks, I upvoted; will accept as the answer if no one comes up with any direct solution. You're right - it's supposed to be some sort of expansion board that reduces the need for breadboards. I guess it is supposed to make the sensor modules more plug n play. It would've been nice to kind of accelerate things. I especially wanted the PVC plastic holders because right now trying to connect multiple sensors is just kind of a mess and I'm worried about the connections coming loose when I move from room to room or plug it into the computer to upload code.

You really could make your own version of that shield from a cheap proto board, a few snappable headers broken into 3-pin pieces, and an hour or two soldering bus wires across for the power rails and soldering short wires from the signal pins to the corresponding Arduino ones.

You have a very high opinion of my skill level! ;) But seriously, how concerned should I be that the Russians are beating us in the Arduino race?? This is feeling more and more like a matter of national security. Jkjk. It might be a good business opportunity to sell it domestically though. I really like those plastic holders for the parts. It's a minor thing but looks convenient and cool IHMO.

This one looks kind of like the shield https://www.adafruit.com/product/2077?gclid=EAIaIQobChMInu-ppMeg1QIVj0oNCh1inwcTEAQYASABEgIUUPD_BwE

That's the sort of generic proto shield I mean you could adapt.  If you like the modules in the question, you could contact them about being an importer/distributor.  I'm not yet seeing anything revolutionary in the collection of physical parts.


text:
Which component is described as a "jumper" (NOT jumper wire) when working with a motor shield?
In this video I'm watching then instructor talks about using "jumpers". He's got a motor controller shield and at first he says that "during the making of this video we only had 1 jumper, thus only Pin 4 is working", and that as a result he could only move a motor/wheel in 1 direction.
He proceeds to find another jumper, uses it to make Pin 5 work, and then he can reverse polarity and change the direction the the wheel spins.
At first I thought that he must mean header pins, but when he holds the tiny component up, it looks like it's something else:

I read about a "power jumper" on an Adafruit page, but it only applied to one version of the Arduino and sounded like it was to do with Power joining (using the same power source for the motor and controller), so I really don't know if that's the same thing.

It's one of these (or similar). It connects two adjacent male header pins.

Thanks +1, will mark this as the answer. How are they used? I mean why would I want to connect 2 header pins together?

They can be used to form a connection that a user can elect to connect or disconnect as required for an application, or they can be used to choose between multiple mutually exclusive connections, e.g. powering a shield with either 3.3V or 5V sourced from the Arduino.

I mean why would I want to connect 2 header pins together? - it's very commonly done. For example I have a "minimal" board where I sometimes want a power LED to come on, and sometimes not (for measuring low-power consumption). So, I solder on two header pins side by side to make a gap in the circuit to the LED. To make the LED work I just slide on one of the jumper devices that Ignacio showed, and it bridges the gap and completes the circuit.


text:
Visibility of #define between sketch and library
I want to have a define from my sketch be picked up by a library.
Here is a similar question for references: Using #define and multiple classes
I have a CI server that compiles my arduino sketchs on commmit. It pulls all my personal libs from an other repository and compiles the sketch using arduino-builder.
Now i want it to also make a debug build. (Some of my library's have debugstatments in them i enable using a #define debugsomething.
Is there any way i can get the compiler to pickup the #define in the sketch or am i better off making a very complex build script that modifies the headers between builds?

You need a common place that the building of all the places can get the definition from.
That isn't the sketch. The sketch is one of the things that would have to look at that common place.
That can either be a single shared header that everything else (that needs it) includes, or it can be a -D flag added to the compilation command.
For instance, adding:
-DDEBUG=1

to your compilation command is the same as adding
#define DEBUG 1

to every single file you compile.

Thanks for the replay. The -D options looks great for my purpose. Do you have any clue how to do this with https://github.com/arduino/arduino-builder?

I haven't a clue. Never used arduino-builder, and I don't speak "go", so I can't even work out what it's supposed to be doing. The lack of documentation makes it impossible to know how to actually use it, as well.

I made a issue over there. Hope they can help me : https://github.com/arduino/arduino-builder/issues/138

Can i also do multiple defines with one -D argument? Looks to me something does wrong when i try multiple -D arguments see issue 138

You can use as many -Dxxx=yyy arguments as you like.

There is no way to hack it into one argument? As the builder currently fails to give me the second one.

Nope. Not unless you want to re-program the AVR GCC compiler - which you don't.

Wow your fast. Indeed i won't. I rather fix the arduino-builder :). I hope i get a response there.