text:
Trying to make a heart rate analyser with Arduino that will calculate the BPM of a person
I am trying to make a heart rate analyzer device using an Arduino board that will calculate the BPM of a person by using raw sensor signals greater or equal to the threshold value to calculate pulses/heartbeat in 10 seconds and then multiply the number of pulses by 6.
The circuit is fairly simple: it has a led that is going to flash on the finger of the person. In-front of the finger there is going to be a photoresistor that is going to read changing values of light falling on it. The values will be varying because of the blood flowing through the finger. When there is going to be a  pulse/heart-beat the amount of light falling on the photoresistor will increase, hence the reading of the photoresistor will also increase.
If the raw values read by the sensor are equal to or greater than the threshold value the code will increment the number of pulses by 1. To calculate the heartbeat rate we will have to count the number of pulses/heart-beats for 10 seconds and then multiply the count by 6.
In short the code that I will use will convert raw analog sensor data into BPM (Beats Per Minute) so that a user can get a standard measurement of his pulse rate.
I took the code that I am going to use from a website. Here is a link to page so that you can also have a look at the code.
I had some problem in the code and was wondering if anyone could help me with it. The full code is given below:
int sensorValue = 0;
int sensorValue = 0;
// variable to store the value coming from the sensor
int count=0;
unsigned long time1=0; // store the initial time
unsigned long time2; // store the current time

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(sensorPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  if(count==0) {
    time1=millis();
  }
  time2=millis();
  sensorValue = analogRead(sensorPin);
  if(sensorValue>156) {
    increment();
  }
  if(time2>=time1+10000) {
    counter();
  }
}

void increment() {
  count++;
  while(sensorValue>156) {
    Serial.print("Sensor value is greater than .75V\n");
  }
}

void counter() {
  count=count*6;
  Serial.print("Heartbeat rate is ");
  Serial.print(count);
  Serial.print(" per min\n");
  time1=0;
  time2=0;
  count=0;
}

Part of the code I'm not able to understand. This is located at the very top of void loop():
[note: i pretty much understand how increment and counter functions work but i am not able to understand how the program is able to take input for 10 seconds.basically how the counter function runs for 10 seconds]
 if(count==0) {
    time1=millis();
  }
  time2=millis();
  sensorValue = analogRead(sensorPin);
  if(sensorValue>156) {
    increment();
  }
  if(time2>=time1+10000) {
    counter();

Although I know that this part of the code that I am not able to understand counts the pulses for 10 seconds by taking raw sensor values and checking if these values are above or equal to the threshold value, I am not able to understand how it is working.
I would be highly obliged if anyone could help me with this problem of mine.

What that block does is fundamentally linked with the counter and increment functions. Replace those function calls with the function contents and what they do will become obvious.

Note: Most photo resistors are very slow to respond to changes in light.  I would be very surprised if you could even see significant fluctuations if the input changed as fast as 90 cycles per minute.

@Majenko  u misunderstood me. I am aware of what counter and increment functions do. im interested in knowing how the program is able to run for 10 seconds and and increment the value of the integer count, when the photoresistor detects raw input greater or equal to the threshold value.

@Majenko here are the lines of code in specific that i want to understand:

Is the problem that the code is not working as expected?  It it working correctly and you want it to do something different?

You must know this method has an error of up to 6, which is nearly 10%. Do you know that you can be much more accurate if you count the length of time 12 heartbeats takes instead of counting the heartbeats in 10 seconds? Once you have an exact period, 1/period is an exact frequency, without the error that came from multiplying to up-scale the per-interval frequency to a per-minute frequency.

// Record the start time into time1
if(count==0) {
  time1=millis();
}

// Set time2 to the current time
time2=millis();

// Read the sensor
sensorValue = analogRead(sensorPin);

// If the sensor value is high enough, increment the beat counter
if(sensorValue>156) {
  increment();
}

// If the current time is greater than, or equal to, the start time
// plus 10,000 milliseconds (10 seconds), show the heart rate
if(time2>=time1+10000) {
 counter();
}

int sensorValue = 0;
// variable to store the value coming from the sensor
int count=0;
unsigned long time1=0; // store the initial time
unsigned long time2; // store the current time

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(A1, INPUT);
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  if(count==0) {
    time1=millis();
  }
  time2=millis();
  sensorValue = analogRead(A1);
  if(sensorValue>800) {
    increment();
  }
  if(time2>=time1+10000) {
    counter();
  }
}

void increment() {
  count++;
  while(sensorValue>800) {
    Serial.print("Sensor value is greater than .75V\n");
  }
}

void counter() {
  count=count*6;
  Serial.print("Heartbeat rate is ");
  Serial.print(count);
  Serial.print(" per min\n");
  time1=0;
  time2=0;
  count=0;
}

try the above code

roll-over problem here.


text:
Uploading Arduino code, OTA, via connected ESP8266-12E running Esp-Link
1. A short preliminary introduction
I'm deploying a small network of three MEGAs connected trough an RS-485 bus.
Each MEGA is connected to up to 16 push-buttons (wall-mounted) and two relay-module (2 x 8-SSR; located close to the MEGA). The objective is to manage the lighting of the whole house (aka: "switching 'ON' the relay 'R1' when the push-button 'PB1' is pressed").
At the moment, everything runs fine: MEGAs are able to 'broadcast' events along the BUS and each node is able to properly react to both locally-generated events, as well as events coming from the BUS.
Above system is running from a couple of weeks and... I'm starting struggling about "updating" the code: having around 40 push-buttons and 35 relay distributed on the three nodes, chances are "high" that some "tuning" (aka: "trial-and-error") is required.
Things get even worse when... you start enjoying the powerfullness of the system (aka: "Hai! What about turning-OFF ALL the lights of the main-floor by long-clicking PB1?"). This, obviously, requires a "patch" to the code and a related "upload" the the MEGAs. And so on: LOTS of uploads :-(
Having some ESP8266-12E modules sitting around, I decided to investigate the possibility to use them, as a sort of "WiFi gateway": reaching them via WiFi; sending them the new code; asking them to kindly "upload" the code to its own MEGA that is phisically connected via USART.
As mentioned in lots of places (including a comment on this other question) I decided to test the ESP-Link firmware.
As I'm having problems interconneting the MEGA with the ESP, here I'm, asking this community :-)
2. Hardware involved
As for the Arduino side, I'm using a common MEGA (a Chinese one, BTW), so I don't get into details, here, 'cause there is nothing special.
As for the ESP8266, strictly speaking I'm NOT using a straight ESP8266-12E, but a Development Board. Actually, I'm using a Lolin NodeMCU v3, this, that you can see here below:

My plan is to connect DIRECTLY the USART of the ESP to the USART of the MEGA. This raises some problems, described below.
3. GPIO voltage issues
One of the very first issues that I addressed relates to GPIO voltage.
While it's crystal clear that:

GPIO PINs, on MEGA, are 5V based and, as such:

the TX on the MEGA side will send out a 5V current;
the RX on the MEGA side expect to receive a 5V current;

GPIO PINs, on ESP8266-12E, are 3.3V based and, as such:

the TX on the ESP side will send out a 3.3V current;
the RX on the ESP side expect to receive a 3.3V current;

I still am NOT able to understand if this is --in my case-- a real problem. I'm saying this, 'cause:
1 - Transmission from ESP to MEGA should NOT be an issue, as the HIGH/3.3V signal coming in into MEGA should still be recognized as HIGH, from the MEGA, as it's higher than 2.5V;
2 - Transmission from MEGA to ESP COULD be a problem, if PINs on the ESP are NOT 5V tolerant
As for point 2) I deeply searched all-around and found plenty of contradictory assertions. In the end, I would like to "trust" the Hackaday article: "Ask Hackaday: Is The ESP8266 5V Tolerant?" as, in several comments, reports various semi-official statements (like a message from Expressif CTO sent from a Facebook account or a message from an "internal" of Espressif) asserting that: "Yes! GPIO PINs on the ESP8266-12E are 5V tolerant").
So, again, I decided: "Ok! Let me go! Let's connect the two, straight, without a level-shifter". And yes: I know that with such a decision, I'm taking some risks and... can "burn" something, especially on the ESP side.
So, here's my:

Question 1: How much I'm "brave" in connecting straight-away the TX/RX of the ESP8266 to the RX/TX of the MEGA? Would you suggest it? And why?

4. Ground issues
While working on my RS-485 bus, I learnt that it's critically important to have a "common ground" among my MEGAs. That sounds understandable... as otherwise there is NOT a common reference to evaluate the same signal among different devices.
So, now that I've TWO equipment and I'm giving them POWER via two distinct sources (MEGA directly connected to my PC; ESP connected to another PC), I'm wondering if:

Question 2: Do I need to connect a GND PIN on the MEGA to a GND PIN on the ESP? Do the two boards, to properly operate, need a shared/common GND?

5. RESET line on the MEGA
In order to trigger the flashing of the new sketch on the Arduino side, the ESP need to RESET it. To do this, the ESP need to be connected to the RESET line of the MEGA. The RESET PIN is clearly shown on the MEGA so the connection is really easy.
Nevertheless, after some preliminary test... it looks to me that the ESP is UNABLE to reset the MEGA.
This lead to:

Question 3: Is, an ESP8266-12E OUTPUT PIN (operating at 3.3V), able to properly handle the RESET PIN of the Arduino?

I'm asking also 'cause based on the official documentation of the MEGA I read:
Reset PIN: Bring this line LOW to reset the microcontroller.
Typically used to add a reset button to shields which block
the one on the board.

6. Physical connections
In the official documentation of ESP-Link I read about potential problems generated (to Arduino) by the ESP as, right after a reboot of the ESP, it send out on TX some debug messages. Due to the USART connections, such characters transmitted by the ESP to the MEGA are received by the MEGA. It's not clear, to me, WHY this could be a problem. Anyway, the same documenation say: "...If you need to avoid this, you can configure esp-link to swap the uart pins..."
So, in the end, I connected the two devices following the official doc, with USART PINs swapped:

GPIO13: connect to TX of microcontroller
GPIO15: connect to RX of microcontroller and use a pull-down to ensure proper booting
GPIO12: connect to RESET of microcontroller
GPIO14: connect to ISP of LPC/ARM microcontroller (not used with Arduino/AVR)
GPIO0: either a 1k-10k pull-up resistor to 3.3v or a green "conn" LED via a 1k-2.2k resistor to 3.3V (indicates wifi status)
GPIO2: either a 1k-10k pull-up resistor to 3.3v or a yellow "ser" LED via a 1k-2.2k resistor to 3.3V (indicates serial activity)

As I don't need (currently) any LED feedback, I haven't used GPIO0 and GPIO2. Also, as I don't have an ARM, I haven't used GPIO14.
With help of this mapping I ended with following connection:

7. Results (...and problems)
To test what's going on, I've uploaded to Arduino a simple sketch that turn ON/OFF the internal LED every second and dump an increasing counter on the console. Here it is:
unsigned long counter;

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  counter = 0;
}

void loop() {
  Serial.print("[");Serial.print(counter);Serial.print("] ");
  Serial.println("on");
  digitalWrite(13, HIGH);
  delay(1000);
  Serial.print("[");Serial.print(counter);Serial.print("] ");
  Serial.println("off");
  digitalWrite(13, LOW);
  delay(1000);
  counter++;
}

so, from the console output, I can see if Arduino is correctly operating and if it's restart.
On the ESP-Link side, I've configured the PIN as shown below:

With all the above in place, up to know, I've been experimenting the following:

If I connect ONLY the RESET line and the TX/MEGA to the D7/GPIO13/ESP, I can succesfully reset the Arduino from the ESP-Link web interface and I can see the "console" of the MEGA (I can be sure of succesfully reset, as the counter in the Arduino console, restart);
Above apply:

when the MEGA is powered via a full-USB connection from a PC;
when the MEGA is connected via a power-only USB cable from the PC;
when the MEGA is powered via a USB-power-bank, but in this case ONLY if thereis a shared-GND between ESP and MEGA

As soon as I connect the D8/GPIO15/ESP to the RX/MEGA, everything still work, but up to next reset. If I "reset" the Arduino via the ESP-Link web-interface, it reset but.... never boot (I'm sure, as the "blinking" never start).

So, the last question:

Question 4: What's wrong with above testbed? Why the D8/GPIO15/ESP disrupt the boot process on the MEGA? I've swapped the UART PINs exactly to avoid this... as far as I understood...

Sorry to be so long but... I think that details matter :-)

do you have a common ground between the boards? The ESP's GPIO 4+5 are the only pins that are low during reset+default on boot; you might want to use those two to avoid issues with "boot noise". You can use a relay/mosfet to reset the mega w/o shared electrical connections.

@dandavis: As for "common ground" the boot-problem (Arduino NOT booting properly after a "reset", when the ESP/TX is connected to Arduino/RX) persist even with shared ground. As for "relay/mosfet" to restart Arduino, please note that it's not needed: I've tested that ESP is surely able to reset Arduino. Problem is that after a reset, Arduino "hang" in the boot-process, and never launch the sketch. As soon as I plug-away Arduino/RX and reset it again (via ESP), boot process complete regularly - Currently I'm investigating problems related to the bootloader, even evalutating to "upgrade" it.

I have successfully used ESP-link firmware with esp-01 and Arduino Pro Mini.
For the ESP-01 and Pro Mini, you can find out more on my blog post. I have connected GPIO 0 of ESP-01 to reset pin of Pro Mini and the Pro Mini can be reset using ESP-Link the web interface. I try to use the same voltage level for both micro-controllers and a single power source. For my example, the Pro Mini is driving the ESP-01 and of-course sharing the common ground.
To answer your questions.

I try not do that as ESP has stated that all the GPIO pins are only 3.3v compatible.
Yes, both controller must share a ground.
My understanding is RESET is an output pin. If connected to ESP8266, there is a possibility that the ESP will be damaged.
Not sure if your wiring is correct. You may reference my diagram on how the ESP and Arduino Pro Mini is wired up. For your case, I will recommend a level shifter to prevent damaged to your ESP.

source: Stack Exchange

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

sort: votes


text:
Arduino Com port and PHP Bug
so please read this whole thing.
My Project: I am making a bell system that is based on PHP. The bell is connected to the arduino UNO via a relay and the arduino is connected to the computer via a USB cable. The interface with the database is built with PHP and MySql. Then we have the code which checks every minuit if the bell has to be rung and if it does send a numeric value to the arduino. There is also an option for a longer bell if we send a '0' to the arduino.
My Code: So this is the file that checks if bell has to rung and sends value to arduino
<?php
include('database.php');
$usb_comPort = "COM3";
date_default_timezone_set("Asia/Kolkata");
$time = date("H:i");
$time = trim($time);
$sql = "SELECT bell_amount FROM bell_db WHERE DATE_FORMAT(bell_time,'%H:%i') LIKE '$time'";
$result = mysqli_query($conn, $sql);
$numRows = mysqli_num_rows($result);
if ($numRows == 0) {
  echo 'Error: Nothing found!';
} else {
  $row = mysqli_fetch_assoc($result);
  $bellAmount = $row['bell_amount'];
  $runCommand = "ECHO " . $bellAmount . " > $usb_comPort";
  echo $runCommand;
  exec($runCommand);
}
?>
<html>
<meta http-equiv="refresh" content="60">
<body>
</body>
</html>

and this is the arduino's code:
int b = 0;
void setup() {
Serial.begin(9600);
pinMode(10, OUTPUT); //relay
}

 void loop() {
  b = Serial.read();

    b = b - 48;
    if(b == 0){
      digitalWrite(10,HIGH);

      delay(3000);
      digitalWrite(10,LOW);
      }
    else{
    for (int i=0; i < b; i++){
      digitalWrite(10, HIGH);
      delay(200);
      digitalWrite(10, LOW);
      delay(200);
      }

    }

}

The Issue that i am facing: My aim is that the code should run automatically when the computer is turned on. The code works fine but there is random bug. The code is uploaded to the arduino. When the computer is turned on i want that the system should work but when i run the file  (the one that checks if there is a bell to be rung or not ) it processes the code but it is not able to send a value to the com port so the bell does not ring(the serial light on the arduino does not flash). But if i go to the arduino ide and send a value through the serial monitor once then run the php file, it works!
I am running this on a windows 10 computer, i have an arduino UNO and i have tried this with 2 arduino's same result on both.
So anyone know what i can do?

To make your question easier to read and answer you should remove all the database- and time-related stuff from your PHP code and concentrate only on the communications with Arduino. This forum isn't the place to be debugging non-Arduino code.
I suggest you create a function that tells the Arduino to ring the bell. You debug that by calling it directly and post that function here if you have problems with it. You can simply print out what you would pass to the function when debugging your database and other code.

You need to look at Serial.available() rather than blocking on Serial.read().  Also what happens if your code receives a space?  b = b -48 = -16 and then for (int i = 0; i < -16; i++) it isn't going top work how you expect.

@Matt I have made sure that white space and alphabets are not sent and even if blank is sent nothing happens.

Sounds like the COM port is not setup. Opening the Arduino IDE probably does this automatically.
Try running the following command, only once, after turning on your pc to initialize the COM port.
mode COM3 BAUD=9600 PARITY=n DATA=8

Ps. I'm not a windows user, so this is an educated guess - reference.
Pps. I think you're winning the award for the most complicated way to ring a bell. :)

Thanks dude.. well do you have any other better methods of doing this?

Well I'm not exactly sure what your requirements are, I'll assume is to ring the bell based on information in the database. In that case you could eliminate the webpage and browser all together and write a command line application/daemon/service. You could still write it in php if you wanted, and it would be more accurate and less error prone than relying on the meta/refresh in a browser.

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


text:
Is setting clock divider worth changing on delay() to save power?
Along all the "advanced" methods described in this article, does simple method as downscaling processor while delay makes a difference on power consumption? How much time does the clock alternation takes itself?
Is below example valid?
#include <avr/power.h>

void setup() {}

void loop {

    /*
       here some jobs to do...
    */

    clock_prescale_set(clock_div_256); // downscale clock
    delay(200); // wait
    clock_prescale_set(clock_div_1); // restore clock
}

i don't think that will accomplish anything; it's not like there are background threads...

It's not running background threads, no, but the delay function doesn't just 'pause'. It runs a loop waiting for the time to pass. If you scale down the clock the cpu will process slower and use less power. I'm not super familiar with the clock prescaler, so perhaps someone could verify, but a delay(200) with a div 265 prescale would actually take just over 51 seconds, i think. ?

@Mazaryk: if that's the case, power-saving mode would be better right? I just don't see shaving empty cycles as a big savings, but i could be wrong; most of my experience is with ESP8266s...

@dandavis: I'm not sure, but I would think sleeping would yield better power savings but that's just a guess. Best way to know for sure would be to test and measure it.

@dandavis setting the clock divider is major power-saver, see the article i linked (esp. reply #7 http://www.gammon.com.au/forum/?id=11497&reply=7#reply7)

@madneon: interesting. i think sleeping still shaves more, but that's nice and simple whilst still pretty good for not screwing around with watchdogs and brownouts or suspending IOs like spi and serial. With the right setup, you can get a 3.3v one all the way down to ~5µA. but not as easily for sure. thanks for sharing!

Reducing the CPU frequency should work, but I would expect better
savings by sleeping during the busy loop:
#include <avr/sleep.h>

void sleepy_delay(uint32_t duration)
{
    uint32_t start = millis();
    while (millis() - start < duration) {
        sleep_mode();
    }
}

Note that the sleep will be interrupted at least on every Timer 0
overflow interrupt, which happens every 1024 µs (that's what
increments the value returned by millis()), so there is no risk of
oversleeping. You could add some power_*_disable() calls for better
savings.

1024 µs "wakeup" thats 1 ms, so your loop will execute every milisecond assuming that it takes less then 1 ms to execute millis() with 2 operations (substract, compare+jump), right? So does this method actually saves power, aka is Arduino that fast? ;)

@madneon: millis() is fast, and subtract+compare+jump is only a few CPU cycles. With this loop the Arduino will be awake only a tiny fraction of the time, mostly executing the Timer 0 overflow ISR.


text:
Interface with mux-controlled LED rope
I'm working on using a GUI in Processing to control some LED rope from Adafruit, and using this multiplexer.
I've gotten the following Arduino code working the way I want to cycle through the various strands of LED rope and turn them on:
#include <SoftwareSerial.h>

//Mux1 control pins
int s0 = 8;
int s1 = 9;
int s2 = 10;
int s3 = 11;

//Mux2 control pins
int s4 = 12;
int s5 = 13;
int s6 = 14;
int s7 = 15;

//Mux in "SIG" pin
int SIG_pin = 3;

//Voltage vlaue to write to the LEDs
int testValue = 255;

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

  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(s4, OUTPUT);
  pinMode(s5, OUTPUT);
  pinMode(s6, OUTPUT);
  pinMode(s7, OUTPUT);
  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  digitalWrite(s4, LOW);
  digitalWrite(s5, LOW);
  digitalWrite(s6, LOW);
  digitalWrite(s7, LOW);
}

void loop(){

  for(int i = 0; i <= 19 ; i ++){
    Serial.println(i);
    testValue = 255;
    writeMux(i);
    delay(500);
//    testValue = 0;
//    writeMux(i);

  }

}

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3, s4, s5, s6, s7};

  int muxChannel[20][8]={
    //Mux 1
    {0,0,0,0,0,0,0,0}, //channel 0
    {1,0,0,0,0,0,0,0}, //channel 1
    {0,1,0,0,0,0,0,0}, //channel 2
    {1,1,0,0,0,0,0,0}, //channel 3
    {0,0,1,0,0,0,0,0}, //channel 4
    {1,0,1,0,0,0,0,0}, //channel 5
    {0,1,1,0,0,0,0,0}, //channel 6
    {1,1,1,0,0,0,0,0}, //channel 7
    {0,0,0,1,0,0,0,0}, //channel 8
    {1,0,0,1,0,0,0,0}, //channel 9

    //Max 2
    {1,1,1,1,0,0,0,0}, //channel 0
    {1,1,1,1,1,0,0,0}, //channel 1
    {1,1,1,1,0,1,0,0}, //channel 2
    {1,1,1,1,1,1,0,0}, //channel 3
    {1,1,1,1,0,0,1,0}, //channel 4
    {1,1,1,1,1,0,1,0}, //channel 5
    {1,1,1,1,0,1,1,0}, //channel 6
    {1,1,1,1,1,1,1,0}, //channel 7
    {1,1,1,1,0,0,0,1}, //channel 8
    {1,1,1,1,1,0,0,1}, //channel 9
  };

  //loop through the 4 sig
  for(int i = 0; i < 8; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
//    Serial.println("CHANNEL IS ");
//    Serial.println(muxChannel[channel][i]);

//    Serial.println("Control pin IS ");
//    Serial.println(controlPin[i]);
  }

  //write the value at the SIG pin
  analogWrite(SIG_pin, testValue);

//    Serial.println("Test value IS ");
//    Serial.println(testValue);

  //return the value
  return 0;
}

I'm working on converting this Arduino code to a Processing sketch so I can control the lights with a GUI. I've run the Standard Firmata sketch on my Uno before running my Processing sketch. However, nothing seems to happen...I know that my circuit is working (since it worked for the Arduino sketch), and most of my Processing code should be correct. Logging shows the sketch is trying to write the values I want. Anyone have any ideas? Below is the relevant part of the Processing sketch:
import cc.arduino.*;
import processing.serial.*;

int [] muxChannel;

//Mux1 control pins
int s0 = 8;
int s1 = 9;
int s2 = 10;
int s3 = 11;

//Mux2 control pins
int s4 = 12;
int s5 = 13;
int s6 = 14;
int s7 = 15;

//Mux in "SIG" pin
int SIG_pin = 3;

//Voltage vlaue to write to the LEDs
int testValue = 255;

void setup() {
  size(700,400);
  noStroke();
  cp5 = new ControlP5(this);
  println(Arduino.list());

  //// Set up Arduino and pin output modes
  arduino = new Arduino(this, Arduino.list()[1], 96000);

  arduino.pinMode(s0, Arduino.OUTPUT);
  arduino.pinMode(s1, Arduino.OUTPUT);
  arduino.pinMode(s2, Arduino.OUTPUT);
  arduino.pinMode(s3, Arduino.OUTPUT);
  arduino.pinMode(s4, Arduino.OUTPUT);
  arduino.pinMode(s5, Arduino.OUTPUT);
  arduino.pinMode(s6, Arduino.OUTPUT);
  arduino.pinMode(s7, Arduino.OUTPUT);
  arduino.pinMode(SIG_pin, Arduino.OUTPUT);

  arduino.digitalWrite(s0, Arduino.LOW);
  arduino.digitalWrite(s1, Arduino.LOW);
  arduino.digitalWrite(s2, Arduino.LOW);
  arduino.digitalWrite(s3, Arduino.LOW);
  arduino.digitalWrite(s4, Arduino.LOW);
  arduino.digitalWrite(s5, Arduino.LOW);
  arduino.digitalWrite(s6, Arduino.LOW);
  arduino.digitalWrite(s7, Arduino.LOW);
}

void draw() {
  background(bgColor);

    for(int i = 0; i <= 19 ; i ++){
    testValue = 255;
    writeMux(i);
    delay(500);
  }
}

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  final int[][] muxChannels = {
    //Mux 1
    {0,0,0,0,0,0,0,0}, //channel 0
    {1,0,0,0,0,0,0,0}, //channel 1
    {0,1,0,0,0,0,0,0}, //channel 2
    {1,1,0,0,0,0,0,0}, //channel 3
    {0,0,1,0,0,0,0,0}, //channel 4
    {1,0,1,0,0,0,0,0}, //channel 5
    {0,1,1,0,0,0,0,0}, //channel 6
    {1,1,1,0,0,0,0,0}, //channel 7
    {0,0,0,1,0,0,0,0}, //channel 8
    {1,0,0,1,0,0,0,0}, //channel 9

    //Max 2
    {1,1,1,1,0,0,0,0}, //channel 0
    {1,1,1,1,1,0,0,0}, //channel 1
    {1,1,1,1,0,1,0,0}, //channel 2
    {1,1,1,1,1,1,0,0}, //channel 3
    {1,1,1,1,0,0,1,0}, //channel 4
    {1,1,1,1,1,0,1,0}, //channel 5
    {1,1,1,1,0,1,1,0}, //channel 6
    {1,1,1,1,1,1,1,0}, //channel 7
    {1,1,1,1,0,0,0,1}, //channel 8
    {1,1,1,1,1,0,0,1}, //channel 9
    };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++){
    arduino.digitalWrite(controlPin[i], muxChannels[channel][i]);
  }

  //write the value at the SIG pin
  arduino.analogWrite(SIG_pin, testValue);

  int val = 0;
  return val;
}

EDIT: I put the project and a little explainer on GitHub to show what this type of project can or can't be useful for here: https://github.com/narner/Analog-LED-Multiplexing-Example

It makes no sense to have that stupid muxChannels[][] array, which wastes 128 bytes of RAM.  Comments in the bildr.org webpage you referenced pointed out that it's unnecessary, but the webpage author had a lame excuse for not fixing it.  Instead of for(int i = 0; i < 4; i ++)     arduino.digitalWrite(controlPin[i], muxChannels[channel][i]);, say
for(int i=0; i<4; ++i)     arduino.digitalWrite(controlPin[i], (channel>>i)&1); or alternately, PORTB = (PORTB & 0xF0)|channel;

Hey @jwpat7, I think I follow what you're saying there. I tried your suggestion; and it works for the lights connected to the first multiplexer, but nothing seems to happen with the lights on the second one.

I didn't see code for the second multiplexer, and don't know what channel numbers you will use for it, so didn't say how to treat it.    But if its list of control pins is in controlM2[] and the channels are 0 to 9, try for(int i=0; i<4; ++i) if (firstMux())  arduino.digitalWrite(controlPin[i], (channel>>i)&1); else  arduino.digitalWrite(controlM2[i], (channel>>i)&1); or you could say for(int i=0; i<4; ++i) arduino.digitalWrite( firstMux()?  controlPin[i] : controlM2[i], (channel>>i)&1); where firstMux() is true for the first mux but not the second

Comments are for clarifying the question. Please post answers as answers.

You're using a 16-channel analog multiplexer to talk to your devices (the LED ropes) via a single pin on your Arduino. "Multiplexer" is just a fancy name for a switch; "analog" means that it's switching analog connections, basically, wires that can have any voltage on them, as opposed to digital connections that carry only logic high (usually +5 volts) or low (0 volt) signals.
The first place to start is the datasheet. From the product link, we can see that the chip we're using is a CD74HC4067. Their datasheet links don't work, but searching in Octopart for just "74HC4067" eventally led me to an actual datasheet. These datasheets are the key source for information on the parts you're using and are always worth reading through. Even if you don't understand everything in them, they'll usually have the information you need, and reading them gets easier with practice.
Section 5 has a functional diagram (Fig. 1) which shows the important connections.

Z is what you'll hook up to an I/O pin on your Arduino. When the
chip is enabled, Z will be connected to one of the Y connections.
Y0 through Y15 are what you'll hook up to your individual devices;
one (and only one) of these at a time will be connected to Z,
connecting the device to your Arduino I/O pin.
(The other Y connections will be in a high impedance state.)
Ē is the "enable" signal, the bar over top indicating that it's
"active low." That is to say, when you ground (0 V) Ē the mux will
be active and the selected Y will be connected to Z. When you hold Ē
high (5 V) the mux will be inactive and all the Ys and Z will be
disconnected (high impedance again).
S0 through S3 are the select inputs to the mux; they determine which
Y is connected to Z (when the device is active) in a way we'll show
below.

Depending on the project, you may not want to switch the connection between the Z and Y pins (by changing S0-S3) while the devices connected to the Ys are active so that you don't accidentally get a a little bit of signal meant for one device going to another. The steps to do this would be as follows:

You start by having Z connected to, say, Y0, with the signal you
want to send to Y0 going through Z.
Disable the device by bringing Ē high. Now Y0 (and all other Ys)
are disconnected.
Change the value on S0-S3 to select, e.g., Y1.
Change the signal you're sending to Z to the correct signal for Y1.
Bring Ē low to enable the device and now Z will be connected to Y1.

In your project you likely don't need to worry about being this careful with your switching so long as you change S0-S3 and Z as closely together as possible, so I'm going to simplify the code I show here by leaving out the enabling and disabling step; you can just wire Ē to ground for the moment.
The key to the switch is what you send on S0-S3 to select which Y is connected to Z. This input is just a binary number, which you'll need to understand to use it effectively. Following is a short summary, but if you don't understand it completely (or the C code later on), there are plenty of tutorials on the web that can give you further help.
Counting in binary is just like counting in tens except you have only the numbers 0 and 1. So instead of counting 0, 1, 2, ..., 9, 10, 11 you count 0, 1, 10, 11, 100, 101, ... (which represent the numbers 0, 1, 2, 3, 4, 5, ... in decimal). The S0 input on the mux is the least signifcant bit (the one furthest right), the S1 in put the second least significant bit (second from the right) and so on.
So you need to hook up four digital ouput pins from your Arduino to the S0 through S3 inputs on the mux and then manipulate those pins to send the appropriate number to the mux to select your chosen Y that you want to connect to X.
The following program, which counts sequentially from 0000 (0) through 1111 (15) on the four output pins; shows you how to do this. It would be a good idea to build up a small circuit on a breadboard with four LEDs (remember to use a 330 Ω or so resistor in series with the LED) that you can hook to your four pins so you can see visually what your program is doing as you experiment.
We start by declaring some constants for the pins:
// Multiplexer control pins are assumed to be sequentially
// assigned from `mux_base` onward.
//
const int mux_base = 8;
const int mux_len = 4;                  // 2^4 values, 0 through 15
const int mux_max = (1 << mux_len) - 1;

mux_base is the first pin of the four sequental pins you'll hook up to the S0-S3 (or the LEDs); I use pin 8 here but you can use pretty much any pin you like. mux_len is the number of bits in the mux selector input; S0, S1, S2, S3 is 4 bits, so this determines that I'm using pins 8, 9, 10 and 11 on the Arduino to control the mux.
mux_max is purely a calculation (from the previous two constants) of the highest value you can select on the mux; in this case it's 15. The details of how I caculate it are a bit beyond the scope of this answer, but it's worth working out yourself how that C code works from what you learn later in the code and can find out elsewhere on the web.
We need, as usual, to set up our chosen pins as digital outputs; setup_mux() does just that:
void setup_mux() {
    for (int pin = mux_base; pin < mux_base+mux_len; pin++) {
        pinMode(pin, OUTPUT);
        digitalWrite(pin, LOW);
    }
}

We start with the first selector pin and loop through to the last one, for each one setting it to output mode and setting the current value to LOW so that we have known starting conditions.
For the selection of the Y to connect to Z on the multiplexer, it's convenient to have a function that takes an int indicating that Y and sets our selector pins to the correct values for this. Thus, set_mux(value) below. This is probably the most complex part of this answer, and bears detailed study.
void set_mux(int value) {
    for (int offset = 0; offset < mux_len; offset++) {
        int bit = (value >> offset) & 1;
        digitalWrite(mux_base + offset, bit ? HIGH : LOW);
    }
}

The first line loops through our mux_len (4 from above) selector
pins; each of these will have to be set to the correct HIGH or
LOW value for the desired Y selection.
The second line determines the binary bit from value for the
particular selector pin we're setting in this iteration of the
loop. We do this by doing a binary shift of the value to the right,
and then clearing all bits except the lowest one, leaving us with a
final value for bit of 1 or 0. For example, if we pass 14 to the
function, which is 1110 in binary, when the offset is 2 in the loop
we'll use the >> operator to shift that right two bits, through 0111
to 0011. (With each shift the right bit drops off and a 0 is added
at the left.) Doing a logcal AND (the & operator) of 0011
with 0001 keeps only the bits that are set in both, leaving us
with 0001. (Only the far right bit is set in both.)
We then need to set the output pin to HIGH if bit is 1 or LOW if
bit is 0; the ternary operator (condition ? when-true :
when-false) provides a concise way of doing this.

That's our core "library" code, if you will. In this simple example the only setup we need to do is to call setup_mux():
void setup() {
    setup_mux();
}

Our main program, for demonstration, will count upwards in binary on the selector outputs, delaying a half second between each count so you can see your LEDs blink:
int counter = 0;

void loop() {
    set_mux(counter);
    delay(500);
    counter++;
    if (counter > mux_max)
        counter = 0;
}

Once you understand this example, you have everything you need to start using your multiplexer with something more sophisticated than just counting.
One last important thing to emphasize: the mux allows you to use just one signal I/O (plus the four selector outputs) on your Arduino, but that signal I/O is connected to only one device at a time. This won't work if you must always be sending a signal to several devices at the same time, which it appears might be the case from your other question. That said, if there's any time at which you're sending 0 V to a device, that is time you could be spending sending a non-0 V signal to another device.
For example, holding Z at +5 V and cycling the signal outputs through Y0-Y3 quickly will give you what's effectively a +5 V PWM with 25% duty cycle on Y0-Y3. In some cases, this technique can be useful.
Oh, one additional note: this example controls just one multiplexer; you can easily control two with two sets of selector pins, but this starts to use up a lot of pins. Instead, you may wish to have one set of selector pins on the Arduino hooked up to both your muliplexors (and one I/O pin hooked up to both Zs) and use two more Arduino pins to control the Ē on each mux, having only one mux enabled at a time. This will save you three pins, at the cost of some complexity, but it's a good exercise to see if you really understand multiplexing technique since it's a straightforward extension of what you're doing with a single mux.

This is such an awesome answer - thank you for your time and input; this helped me a lot. Thank you!!!

I'm glad to hear it! The research to do this answer helped me learn, too, so thanks for the question!

Note that, if you don't mind direct port access (which is non-portable), set_mux() can be simplified to PORTB = PORTB & ~mux_max | value;. If you don't use pins 12 and 13, it can simplified further to PORTB = value;.

I put the project and a little explainer on GitHub to show what this type of project can or can't be useful for here: https://github.com/narner/Analog-LED-Multiplexing-Example

After reading your github page, I came to realize that:

you do not require full color control, but only setting the strips to
full red or full blue
you are using MOSFETs for driving them.

Given these conditions, I believe the project may be feasible with your
current setup. The trick is that MOSFETs have some gate capacitance: if
you set the gate either HIGH or LOW, and then disconnect it, it will
keep that state for some time, until the charge stored in the gate
leaks. This means you do not need to address each MOSFET continuously:
you can just periodically “refresh” them, and let the gate capacitance
“remember” the state between refreshes. This is similar to how DRAM
memory works.
I wrote the following code based on this idea. Note that I did not test
it, as I do not have the required hardware. It uses a timer interrupt
firing every 1024 µs to cycle through the ten used mux channels:
each channel gets then refreshed every 10.24 ms. It also uses
direct port access instead of digitalWrite(): not only it's way
faster (and you want to be fast in an ISR) but, more importantly, it
allows changing several outputs simultaneously. This is important in
order to avoid glitches.
/*
 * Patterns to send to the multiplexers. bit_patterns[mux][chann] is the
 * pattern to send to the multiplexer `mux' in order to update the
 * channel `chann'. Bits 0..3 hold the channel number, bit 4 is the
 * data. The data bits are all initialized to zero.
 */
volatile uint8_t bit_patterns[2][10] = {
    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
};

/*
 * Periodically cycle through the 10 used multiplexer channels, updating
 * the MOSFETs. The TIMER0_COMPA interrupt has to be enabled for this to
 * automatically run every 1024 microseconds.
 */
ISR(TIMER0_COMPA_vect)
{
    static uint8_t i;            // channel index
    PORTB = bit_patterns[0][i];  // update MUX 0
    PORTC = bit_patterns[1][i];  // update MUX 1
    if (++i >= 10) i = 0;        // cycle channels
}

void setup()
{
    DDRB   =  0x1f;         // set PB0..PB4 as outputs
    DDRC   =  0x1f;         // set PC0..PC4 as outputs
    TIMSK0 |= _BV(OCIE0A);  // enable TIMER0_COMPA interrupt
}

This code relies on Timer 0 being in the standard Arduino configuration,
where it loops every 1024 µs. It also needs a specific wiring,
where each multiplexer is connected to a single AVR port, as follows:
Arduino   multiplexers
----------------------
   8      S0 of MUX 0
       ...
  11      S3 of MUX 0
  12      SIG of MUX 0
  A0      S0 of MUX 1
       ...
  A3      S3 of MUX 1
  A4      SIG of MUX 1

In order to change the strip colors, you just have to update the stored
bit patterns:
/*
 * On each of PORTB and PORTC, bits 0..3 are wired to the address select
 * pins of a multiplexer, whereas bit 4 goes to the SIG pin of the same
 * multiplexer.
 */
const uint8_t SIG_BIT = 0x10;

/* These are the only available colors. */
typedef enum { BLACK, RED, BLUE, MAGENTA } color_t;

/* Set the color of a strip. Strips are numbered from 0 to 9. */
void set_color(uint8_t strip, color_t color)
{
    /* Find the relevant multiplexer and channels. */
    uint8_t mux, red_ch, blue_ch;
    if (strip < 5) {
        mux = 0;
        red_ch = 2 * strip;
    } else {
        mux = 1;
        red_ch = 2 * (strip - 5);
    }
    blue_ch = red_ch + 1;

    /* Update the bit patterns. */
    if (color == RED || color == MAGENTA)
        bit_patterns[mux][red_ch] |= SIG_BIT;
    else
        bit_patterns[mux][red_ch] &= ~SIG_BIT;
    if (color == BLUE || color == MAGENTA)
        bit_patterns[mux][blue_ch] |= SIG_BIT;
    else
        bit_patterns[mux][blue_ch] &= ~SIG_BIT;
}

The function set_color() assumes the following connections between the
multiplexers and the strips:
MUX  channel    strip  color
----------------------------
 0      C0        0     red
 0      C1        0     blue
 0      C2        1     red
 0      C3        1     blue
            ...
 0      C8        4     red
 0      C9        4     blue
 1      C0        5     red
 1      C1        5     blue
            ...
 1      C8        9     red
 1      C9        9     blue

Hardware considerations
All this scheme may or may not work depending on some hardware factors
such as the gate capacitance of your MOSFETs, the leakage current of the
multiplexers when in high-impedance and the timing characteristics of
the same multiplexers. If the gate capacitance is too weak to hold the
value for 9 ms, you may want to add capacitors in parallel, maybe
something in the 100 pF range. If you add more than that, you may
also want to put resistors in series with pins 12 and A4 of the Arduino,
in order to protect them from the inrush current. But then you may also
want to slow down the scanning of the channels, which would require
configuring a timer.


text:
Need Help to implement MODBUS TCP Master over Atmega32 MCU
I am doing a project where I have to interface with Fronius Solar Inverter with Atmega32 MCU over MODBUS TCP. I want to set the MCU as client and The inverter as Server and I have to implement two MODBUS Function only these are READ_HOLDING_REGISTER and WRITE_SIGLE_REGISTER and Function Code are 0x03 and 0x06 respectively.  I am newbie in this field and dont know about networking. Please anybody help me How can I develop the Software in C for this purpose??
The Document of Fronius Inverter for MODBUS TCP is Fronius MODBUS TCP Datamanger

Create A TCP connection (your inverter is TCP server) Check this, your device got modbus pattern so not modbus

So if you want to the atmega as client this means it will start the conection and made the request for values, so translating into modbus words your atmega will be a modbus master and the solar will be a modbus slave.
first you need a way to interface the micocontroller to the tcp/ip stack. you can use an ic or arduino shield which has this ic like a w5100 or enc28j60.
then you can write a library over tcp sockets to start the comunication or change some from the arduino.
https://www.google.com.br/url?sa=t&source=web&rct=j&url=http://myarduinoprojects.com/modbus.html&ved=0ahUKEwj9zMvjiYDTAhXJkpAKHfsNBz0QFggpMAE&usg=AFQjCNEfRhDgPGJNK-IUqrUw1FXEnBcxwQ&sig2=Xs0JNEWi_F_XiPgkTQdy-w

Thank You @Luiz Henrique Diniz Ferreira  for your Kind Information. Is this good and working Library for Arduino Client?. If it is woks good on Arduino as Client then I will drag from Atmega32 to Arduino.

this link  http://myarduinoprojects.com/modbus.html has a library for using on arduino, i didn't tested it but maybe should work. You can install it, and if you are using windows download a program called modbus poll which simulate devices on a modbus network, first try with the program and then the fronius, this way u can deal with less errors at once.


text:
How to connect receiver in an Arduino with a motor shield?
I have an Adafruit motor shield v1 stacked on an Arduino Uno. I want to add a 433Mhz receiver to the Uno so I can control it wirelessly. However as you know the motor shield completely covers the Arduino board and all its pins, except perhaps the analog ones (it appeared to me).
So can you please suggest a way to connect the receiver if possible. I desperately need it and can't afford to buy a Mega now.
Please help asap.

are there not through-hole "test pads" on the shield PCB that you can solder onto? can you not use the analog pins?

Adfruit Motor Shield v1 takes digital pins(D12 to D2) left only digital pins (D13,D1,D0) and all Analog pins of Arduino uno. So if you want to hookup RF receiver with Arduino then you have go this way.. connect RF Receiver output to the Digital pin D0 that is RX.
Here the schematic

Okay i just google about the sheild and found out pin 2 also remains unused so can i connect the receiver with it? And as u said to connect the receiver with rx,  wont there be problem uploading the sketch to arduino  d another point is does rx pin has any benefit ovr pin 2 for connecting the receiver? Plz confirm regarding the above points

Yeah You can also connect RF receiver output with pin 2. RF receiver gives DIGITAL output and both pin and Digital pin so there are no difference between Rx pin and Pin 2 for this case . Rx and Tx pin used only for some special cases (like Bluetooth, Serial Terminal e.t.c). while you uploading Sketch on Arduino just disconnect the Rx and Tx pin after uploading sketch connect again otherwise you might have get some error.


text:
My ESP8266 01 is saying at espcomm_sync failed, espcomm_open failed, and (2x) espcomm_upload_mem failed. OS X
I'm extremely frustrated at my ESP8266 right now, with the Arduino. I am using a 6v DC battery power supply (4xAA batteries), and a 3.3v voltage regulator (NTE1904). I have the connections as shown:

Vcc - 3.3v rail
CH_PD - 3.3v rail
RST - 3.3v rail (I put it into GND when I need to reset)
GPIO 0 - GND (I momentarily put the reset in ground after)
TXD - Rx
RXD - Tx

I have the 6V from the 4xAA batteries into the Vin of the 3.3V voltage reulgator, it's ground to the ground of batteries (and therefore connected to Arduino), and the output connected to the 3.3v rail.
I had the circuit working before, and I had it not receiving a packet header, but when I resembled the circuit fully I am now getting these errors when uploading my code:
Sketch uses 232778 bytes (53%) of program storage space. Maximum is 434160 bytes.
Global variables use 31981 bytes (39%) of dynamic memory, leaving 49939 bytes for local variables. Maximum is 81920 bytes.
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed
I've tried a bunch, and I am not sure where my problem is. Note:

I have changed my platform.txt (Arduino15/packages/.../esp8266/2.2.0/platform.txt)'s tools.esptool.upload.pattern to: tools.esptool.upload.pattern="{path}/{cmd}" {upload.verbose} -cd {upload.resetmethod} -cb {upload.speed} -cp "{serial.port}" -ca 0x00000 -cf "{build.path}/{build.project_name}.bin" (or have I? It seems quite unorganized I've changed it in the past from a tutorial saying that esptool doesn't work properly on OS X, but the page is quite hard to locate again. Please tell me what you use currently)

Again, I am on OS X (10.11.4)
Thank you for any help. It is extremely frustrating trying to get this, and I cannot seem to find any up-to-date tutorials with my problem. If you know anything I could try, that would be great.

Can you describe in better detail what hardware you're using? I am not clear on if you're using a single ESP 8266 board acting as the CPU, or some sort of other microcontroller on a board (e.g., an Arduino Uno) with a separate pre-programmed ESP 8266 board acting as a peripheral. Links to datasheets or product pages for your exact hardware are best. Also, if you can provide a schematic of some sort so we can see exactly what pins are connected to what, that will be a lot more clear than your textual description.

don't ground gpio0

Depending on you hardware you might need level shifters on the serial lines (both of them)

any luck after un-grounding? if not, please post more wiring details.


text:
MPU6050: Setting Gyro Output Range Throws of Positional Reading
I am using the MPU6050 in conjunction with an Arduino and Jeff Rowberg's i2cdev library, and my project requires that the gyro rate outputs be more precise than the default setting, which is 1/16.4 of a degree (+/-2000 deg/sec range). The gyro outputs can be changed with mpu.setFullScaleGyroRange(uint8_t range) for which I passed in MPU6050_GYO_FS_500 for range to get a higher precision
In this project, I also need the YPR position, which I obtain through mpu.dmpGetQuaternion(&q, fifoBuffer) and mpu.dmpGetGravity(&gravity, &q) and mpu.dmpGetYawPitchRoll(ypr, &q, &gravity).
The problem is with the new gyro output range, the YPR position changes drastically when the MPU is being rotated and slowly catches up again once the MPU is held still. I think there is an error in the filter that combines the gyro and accel data that is making the gyro to sensitive. Maybe the DMP is dividing the GYRO rate data by the default sensitivity factor (16.4) when it should be dividing by the new one (131)?
How can I get accurate YPR readings without delay?
Here is a screenshot of the data. The axis aren't labeled, but the x-axis represents about 16 seconds of time. The blue line is the gyro rate data, and the pink line is the roll position of the MPU. The graph shows two rotations of the MPU.

Had the same problem, it appears that MPU6050 DMP code works like that once you change accelerometer and gyro scales.
Works better once you use +-2000 deg/sec and +-2g scaling settings.
    mpu.setFullScaleGyroRange(MPU6050_GYRO_FS_2000);
    mpu.setFullScaleAccelRange(MPU6050_ACCEL_FS_2);

The issue lies in the way "DMP" inner logic fuses data, i suppose it has "constants" that are tuned for these settings only.
In case you need both "changed settings" and "yaw\pitch\roll" data, you might want to implement sensor data fusion by yourself or use existing libs.
The easiest i may suggest would be implementing Complementary Filter.
More complex, yet accurate would be using Kalman Filter, all depends on time and patience you have to research those topics :)

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


text:
Using MCP23017 to control Servos
Using Servo.h it is possible to run a servo from just about any pin.....obviously the more pins the more servos...hence the question
" how can I do this with a MCP23017 ? ".
I have searched the web a fair bit but no luck.
Is there a modified Servo library out there??
It's such an obvious solution i figure it must have been done before.
Any suggestions..Thanks.

Using Servo.h it is possible to run a servo from just about any pin.....obviously the more pins the more servos...hence the question " how can I do this with a MCP23017?

The Servo library could be modified to allow toggling of GPIO pins on a MCP23017 but there are some issues with timing.
The library uses Timers and Interrupt Service Routines (ISR) to handle the pulse width. The servo pin is toggled in the ISR.
At 100 KHz (100 Kbps) I2C at least 3 bytes need to be transmitted to the MCP230017 to toggle a pin. That is approx. 300 us and not possible to do from the Servo ISR. Another execution pattern is required.
Cheers!

Thank All for the feedback...modifying a library is not an option at this time...not that good yet...The more research I do the less likely the option seems so I will cheat and purchase a 386 MEGA board...54 I/O's is sufficient for my needs on this project. 13 Servo (seperate power supply) and 28 repeater LED's ....track side LED's will be handled by MCP23017 x 2 in series. I was using the Adafruit 16 servo board but I think I fritz-ed it. Oh well thats life.

Theoretically, yes. It would be pretty interesting to see, but running multiple servos would account for a huge amount of what you can reasonably do with your code and probably be a huge headache.
Perhaps a better solution would be to use a PWM expander like the PCA9685.

how can I do this with a MCP23017 ? ".

you can but it would be fairly expensive in processing power, as you need to keep track of both rising and falling edges of every channel at all times, and send the data to the chip -> may not be doable given i2c's speed limitations.

I have searched the web a fair bit but no luck.

I wrote a variety of approaches / implementations on driving multiple servo channels off of one timer, with or without output compare, here: https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/
it will branch out to a few other variants, depending on resources available to you.

For PWM, the MCP23017 would have to be software-driven.
I would suggest one of the PCA9685 boards, which give you hardware PWM (and can also provide digital pins).
These are a bit more expensive, but very easy to use, and are driven by I2C in the same way.

Indeed, the PCA9685 is used to control servos, I also use them to dim lights with an array of mosfet switches !

For example...
unsigned long long servo_timing[2]={0,0};
int A_data=0;
void servo_ini()
{
  Wire.beginTransmission(0x20);
    Wire.write(0x00);      // address bank A
    Wire.write(0x00);
    Wire.endTransmission();
}
void servo_set(unsigned int servo_tim,bool servo_mod){
   if(servo_mod==1){
    servo_tim=map(servo_tim,0,180,200,1900);
   }
   //if(servo_vector<=0)/*lcd_tim=650;*/servo_tim=220;/0
   //if(servo_vector==1)/*lcd_tim=1400;*/servo_tim=1000;/90
   //if(servo_vector>=2)/*lcd_tim=2255;*/servo_tim=1870;/180
   if(micros()-servo_timing[0]>servo_tim)
   {
     A_data&=0b11111110;
     Wire.beginTransmission(0x20);
     Wire.write(0x12);      // address bank A
     Wire.write(A_data);
     Wire.endTransmission();
     if(micros()-servo_timing[1]>(20000-servo_tim))
     {
       A_data|=0b00000001;
       Wire.beginTransmission(0x20);
       Wire.write(0x12);      // address bank A
       Wire.write(A_data);
       Wire.endTransmission();
       servo_timing[0]=micros();
       servo_timing[1]=micros();
     }

  }
}

I succeeded in pwm (servo control) with mcp23017.
Moreover, it is 16ch.
The mcp23017 in the Arduino Library also has a wordwrite write, but the frequency still couldn't catch up.
There is no choice but to create a library by yourself and generate a pulse of 0.5msec .. 2.5msec in 20msec 50Hz to drive the servo motor.
We are currently organizing the library
thank you
https://twitter.com/chrmlinux03/status/1534834169737789441?s=20&t=EqkVXJ2v1H3i_tfZsXfjHQ
https://github.com/chrmlinux/


text:
Software flashing attiny167 from RPi with avrdude
I am trying to flash a program onto an attiny167
(already bootloaded with the micronucleus bootloader)
with a Raspberry Pi via avrdude and USB.
Background
I have 50 Raspberry Pi 3B's connected to an amazon server collecting data.
I have 50 custom attiny167 based USB sensor PCBs which I will connect to the Pis
via USB (see this previous issue for more detail)
It is a struggle to access and connect each device (especially 50 of them),
and I thus need to be able to reflash a program to them via the commandline of an RPi.
I have bootloaded them all from my windows 10 machine and can flash any program via USB.
RPis
I have flashed programs from the RPi with an Arduino Uno, both with the IDE and avrdude.
 Arduino and avrdude are installed and working (installed both with apt-get).
The RPi can run an already flashed program, with reading and writing
 possible from the USB device.
 When plugged in the device is viewed by the lsusb command for 5 seconds.
 The pre-flashed program then runs and lsusb shows no device:
lsusb immediately after device is plugged into port

 pi@raspberrypi:/usr/bin $ lsusb
 Bus 001 Device 005: ID 046d:c077 Logitech, Inc.
 Bus 001 Device 006: ID 413c:2011 Dell Computer Corp. Multimedia Pro Keyboard
 Bus 001 Device 004: ID 413c:1005 Dell Computer Corp. Multimedia Pro Keyboard Hub
 Bus 001 Device 007: ID 16d0:0753 MCS Digistump DigiSpark
 Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
 Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
 Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

lsusb ~5 seconds after device is plugged into port

 pi@raspberrypi:/usr/bin $ lsusb
 Bus 001 Device 005: ID 046d:c077 Logitech, Inc.
 Bus 001 Device 006: ID 413c:2011 Dell Computer Corp. Multimedia Pro Keyboard
 Bus 001 Device 004: ID 413c:1005 Dell Computer Corp. Multimedia Pro Keyboard Hub
 Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
 Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
 Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

udev rules
I have followed the
tutorial for udev rules by digistump
and placed the file at /etc/udev/rules.d/49-micronucleus.rules
UDEV of tinseey (similar to bootloaded micronucleus for attiny167)
AVR Device
this post
hints it may not be possible,
however this issue may have been resolved, as I am using an attiny167 (rather than an 85),
and the Pi does not reboot on the USB being plugged in.
On using dmesg you can see it is unable to enumerate.
dmesg

[ 9820.701327] usb 1-1.2: new low-speed USB device number 7 using dwc_otg
[ 9820.803813] usb 1-1.2: New USB device found, idVendor=16d0, idProduct=0753
[ 9820.803838] usb 1-1.2: New USB device strings: Mfr=0, Product=0, SerialNumber=0
[ 9825.208851] usb 1-1.2: USB disconnect, device number 7
[ 9828.001334] usb 1-1.2: new low-speed USB device number 8 using dwc_otg
[ 9833.081359] usb 1-1.2: device descriptor read/64, error -110
[ 9833.271389] usb 1-1.2: device descriptor read/64, error -71
[ 9833.461352] usb 1-1.2: new low-speed USB device number 9 using dwc_otg
[ 9833.541349] usb 1-1.2: device descriptor read/64, error -71
[ 9833.731352] usb 1-1.2: device descriptor read/64, error -71
[ 9833.921349] usb 1-1.2: new low-speed USB device number 10 using dwc_otg
[ 9834.341388] usb 1-1.2: device not accepting address 10, error -71
[ 9834.421361] usb 1-1.2: new low-speed USB device number 11 using dwc_otg
[ 9834.841371] usb 1-1.2: device not accepting address 11, error -71
[ 9834.841480] usb 1-1-port2: unable to enumerate USB device

avrdude
I'm using the command, with different serial ports

usr/bin/avrdude -p attiny167 -c arduino -C /etc/avrdude.conf -b 19200 -P [COM PORT] -U flash:w:[MyHexFile.ino.hex]:i

this gives the error

avrdude: ser_open(): can't open device "[COM PORT]": No such file or directory

avrdude done.  Thank you.

The same method works with the Uno on the Pi, and the AVR device on my windows 10 machines.
I have updated the configuration file avrdude.conf to include the attiny167,
as I did with my windows 10 machine.
Serial port
serial and ttyACMO appears with Uno in /dev, not for the AVR device.
Arduino IDE
I've attempted to do this through the IDE but get the error:

/home/pi/Downloads/arduino-1.8.1/arduino-builder -dump-prefs -logger=machine -hardware /home/pi/Downloads/arduino-1.8.1/hardware -hardware /home/pi/.arduino15/packages -tools /home/pi/Downloads/arduino-1.8.1/tools-builder -tools /home/pi/Downloads/arduino-1.8.1/hardware/tools/avr -tools /home/pi/.arduino15/packages -built-in-libraries /home/pi/Downloads/arduino-1.8.1/libraries -libraries /home/pi/Arduino/libraries -fqbn=digistump:avr:digispark-tiny -ide-version=10801 -build-path /tmp/arduino_build_279218 -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.micronucleus.path=/home/pi/.arduino15/packages/digistump/tools/micronucleus/2.0a4 -prefs=runtime.tools.avr-gcc.path=/home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5 -verbose /home/pi/sensicorn/sensicorn/indoorSoftware/Arduino Code/neopixel_simple/neopixel_simple.ino
/home/pi/Downloads/arduino-1.8.1/arduino-builder -compile -logger=machine -hardware /home/pi/Downloads/arduino-1.8.1/hardware -hardware /home/pi/.arduino15/packages -tools /home/pi/Downloads/arduino-1.8.1/tools-builder -tools /home/pi/Downloads/arduino-1.8.1/hardware/tools/avr -tools /home/pi/.arduino15/packages -built-in-libraries /home/pi/Downloads/arduino-1.8.1/libraries -libraries /home/pi/Arduino/libraries -fqbn=digistump:avr:digispark-tiny -ide-version=10801 -build-path /tmp/arduino_build_279218 -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.micronucleus.path=/home/pi/.arduino15/packages/digistump/tools/micronucleus/2.0a4 -prefs=runtime.tools.avr-gcc.path=/home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5 -verbose /home/pi/sensicorn/sensicorn/indoorSoftware/Arduino Code/neopixel_simple/neopixel_simple.ino
Using board 'digispark-tiny' from platform in folder: /home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7
Using core 'tiny' from platform in folder: /home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7
Detecting libraries used...
"/home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/bin/avr-g++" -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections  -w -x c++ -E -CC -mmcu=attiny85 -DF_CPU=16500000L -DARDUINO=10801 -DARDUINO_AVR_DIGISPARK -DARDUINO_ARCH_AVR  "-I/home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7/cores/tiny" "-I/home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7/variants/digispark" "/tmp/arduino_build_279218/sketch/neopixel_simple.ino.cpp" -o "/dev/null"
Generating function prototypes...
"/home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/bin/avr-g++" -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections  -w -x c++ -E -CC -mmcu=attiny85 -DF_CPU=16500000L -DARDUINO=10801 -DARDUINO_AVR_DIGISPARK -DARDUINO_ARCH_AVR  "-I/home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7/cores/tiny" "-I/home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7/variants/digispark" "/tmp/arduino_build_279218/sketch/neopixel_simple.ino.cpp" -o "/tmp/arduino_build_279218/preproc/ctags_target_for_gcc_minus_e.cpp"

fork/exec /home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/bin/avr-g++: no such file or directory
Error compiling for board Digispark (Default - 16.5mhz).

when I type which avr-g++: /usr/bin/avr-g++, this is just a copy from my windows machine.
I found this github issue
and it seems to be irrelevant for now, just a path issue.
I've had to use a custom json file for the board manager to find micronucleus and Digispark Pro.
When I plug in the AVR device no new serial port is shown in Tools->Port (unlike Arduino UNO, ttyACM0 appears).
I'd much prefer to do flash via avrdude or similar on the commandline, so I have not focused on this.

My question
Is it possible to flash the AVR device with a Raspberry Pi over USB?
If so, what am I doing wrong?


text:
Confusion about String handling
I am trying to execute some webbased calls, but my string keep "disappearing", and I am highly confused about why.
I can println a string directly, but if I have it in a variable, it will disappear :I
I tried googling around, but could not find a reason for it. Is it because of the curly brackets ? Is it a memory issue ?
I feel I really can't code on and juggle web calls, if I can't even handle regular string commands..
Code:
Serial.println(" - CONSOLE/STRING WEIRDNESS - ");
String message = "Testing time {0}";
Serial.println(message);
Serial.println(String(message));
Serial.println("Testing time {0}");
Serial.println(message.substring(3,6));

Response:
- CONSOLE/STRING WEIRDNESS -
(nothing)
(nothing)
Testing time {0}
(nothing)

Update
This seems to happen whenever there is a number inside a string, it even happends with a simple string like this:
Code:
Serial.println(" - CONSOLE/STRING WEIRDNESS - ");
String message = "Testing time here is a number 0";
Serial.println(message);
Serial.println(String(message));
Serial.println("Testing time here is a number 0");
Serial.println(message.substring(3,6));

Response:
- CONSOLE/STRING WEIRDNESS -
(nothing)
(nothing)
Testing time here is a number 0
(nothing)

Out of memory? Looks like the String constructor failed to allocate storage on the heap.

Give this article a read, it highlights how strings are actually stored in the Arduino memory, and explains how strings should be used.
https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

Turned out it was string weirdness indeed. Thank you so much for this, I will be cautious with the String class from now on.

Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference. Feel free to add a more complete answer that directly answers the question.

The {0} denotes an extra parameter (which you want to print), it seems you just want to print the string without any variable 'value' so you can remove the {0}.
I'm not so familiar with using {0} in C++, but in C# {0} means argument number 0 (after the initial string), since this argument is not given, probably an empty string is created ... it would be more intuitive if the compiler give an error or warning (maybe it gives a warning and you can check for it).
Also converting a string to String() does not do anything but I think it was just for debugging/checking purposes.
Also in Arduino to save SRAM space, normally it is wise to add before each string, the F function like:
Serial.println(F("Some string to print"));

This will create a memory in Flash and will not be copied to SRAM which is normally quite scarce.
To print out arguments you can simply use multiple print commands (which does not add a new line) and the last part of the line with println, like:
Serial.print(F("Test time: ");
Serial.println(test_time);

I can see why "{0}" would cause weirdness, but the fact that just having a number in it, and it still disappears, really confuses me... http://i.imgur.com/EzNmxOU.png

{0} is the argument number (I edited the answer).

Roger that, but did you see my update about a pure string with an integer in it (no curly brackets), and that still fails. Can I really have no numeric characters in a string ?

I don't have a compiler, but normally  it should work like Serial.println("Test time {0}, test_time);    where test_time is the variable (not sure if you have to cast it to a string, I don't think so.


text:
What is the correct way to create large project files?
I am currently working on a 10x10 RGB LED screen (using Neopixels from Adafruit) and my project files are starting to get rather large.
I have several different devices used in this project:

The LED matrix
A DS3232 RTC
An MSGEQ7 DSP chip
7 push button switches

Currently i'm using separate classes for each of the devices (RTC, DSP & buttons) as well as the Adafruit GFX and Neopixel library.
What would be the best way to organize this project? Should I put the patterns for the screen in the main.ino file or should they have their own class.
Any help would be greatly appreciated, I can upload the source code if its needed.
Cheers
As a side note, I'm using "Sublime Text 3" along with Stino.

i throw the major parts in their own file/tab. these have names like "main", "server", "adc", "sdcard", "utils", etc

Good to hear you are splitting large amount of code, it will benefit you a lot in the long run.
It's very hard to say what is best, it depends on the interaction of those patterns with other classes. Normally it is best to put them in the location where they BEST belong to, i.e. where the least association with other classes exist.
If it has a lot of interactions, maybe you should put the patterns itself in a different class.
Normally what I keep as guidelines:
- Not more than a few hundred lines in a class
- Not more than 7 (class) variables in a class
- Not more than 7 functions/methods in a class
Of course these are guide lines. If you have a lot of simple (constant) pattern definitions the file will become larger without getting more hard to understand.
Also try to think of a class to have only ONE responsibility. If you want to be serious about splitting classes or how to organize them, read about SOLID.

Nice one cheers, i'll look in to SOLID.


text:
Specific noise while using arduino ADC in free running mode
To make an oscilloscope in matlab environment, for data acquisition on arduino side, when inbuilt analogRead() is used, it's working fine, but with very low sampling rate, that aliasing is clearly observed. That too, non-uniform sampling. Thus listing out the drawbacks:

Very slow data rate, even if, sent with 115200 baudrate,
Aliasing
Non-uniform sampling

Thus, to overcome above, ADC in free running mode was used, with 16 as prescaling factor, thus 76.9KHz sampling rate (counting each ADC as 13 clock cycles). Thus, data is uniformly sampled now. Also it is quite fast, because of sampling, and is observed. The only problem now exists is, output has a specific noise. The data being sampled is 50Hz sinusoidal current waveform by current sensor ACS712. It overlays instantaneous current waveform over a bias of 2.5V. Thus, when signal is not present, a constant voltage of 2.5V is observed, thus, 512, because of mapping to 255 range.. 127. But in the case of free running mode, along with 127, 191, 63 only are observed. And it can also be seen that nearly 127 = 63*2, and 191 = 63*3. And when current waveform exists, it's highly distorted, but perceptible that it's not the previous signal of just 127, 191, 63. In the below plot, current is passed since 33.5sec.

I am unable to understand this, structured noise. What may be the reason ? I have once read, last two MSB bits get noisy at this sampling rate, but then how would 127, jump to 191. Why is 63 getting added, subtracted at each instant ?
I understand the reason for non-uniform sampling now is because of Serial.print(), whose interrupts are obstructing the ADC interrupts, but don't understand the reason behind the noise observed.
Following is the code uploaded in arduino. Serial data is read from matlab by fread() function.
long t1=0,ts1=0,ts2=0;
int aval=0, val=0;

void setup() {

 TIMSK0 = 0x00;           // disable timer (causes anoying interrupts)
 DIDR0 = 0x3F;            // digital inputs disabled
 ADMUX = 0x40;            // measuring on ADC0, right adjust, AREF reference
 ADCSRA = 0xAC;           // AD-converter on, interrupt enabled, prescaler = 16
 ADCSRB = 0x00;           // AD channels MUX on, free running mode
 bitWrite(ADCSRA, 6, 1);  // Start the conversion by setting bit 6 (=ADSC) in ADCSRA
 sei();
 Serial.begin(115200);
 t1=millis();
 }

ISR(ADC_vect)
{
 aval = ADCL;
 aval += ADCH << 8;
}

void loop() {
val = map(aval, 0, 1023, 0, 255);
Serial.write(val);
delay(10);
}

I wonder how are the functions like millis() and delay(10) working as you've disabled it's interrupt.

Also, if you want 8-bit data, have the ADC left-adjust the result, don't enable it's interrupt, and Serial.write(ADCH);.

You might want to define aval as volatile.

@KIIV, even though TIMER0 is disabled, millis() was still working fine, but it's not the important problem now. I'll enable it, when I use millis() from now. Thank you, for making me aware of it.

@Edgar Bonet, I have used interrupt to handle ADCL, ADCH registers properly, instead of facing a situation of reading them while they are being written (for I thought, ADC writes into these registers the instant they are obtained at 13th clock cycle). I lean't now, that it was my misconception. It was given in datasheet, "When ADCL is read, the ADC Data Register is not updated until ADCH is read, when right adjusted". I'll try it now. Thank you.

If you use an ISR to retrieve the ADC result, you will need to protect the read of the variable. An interrupt may occur when reading aval in the loop(), as this is a 16-bit value and the read requires several instructions. This may give corrupt values.
void loop() {
  noInterrupts();
    val = aval;
  interrupts();
  val = map(val, 0, 1023, 0, 255);
  Serial.write(val);
  delay(10);
}

Cheers!

You're right, but running an ISR every 16 CPU cycles is a bad idea to start with.

Yes, especially if there is a delay(10) in loop().

but running an ISR every 16 CPU cycles is a bad idea to start with. It is a bad idea to put a slow transmission inside of an isr, not to mention issues from re-entrance of serial.print().

It is very unclear what you are trying to achieve here. You are clocking
the ADC at its maximum frequency, which has it take one reading every
13 µs, and yet you are delaying for 10 ms after sending one
reading through the serial port. So basically your Matlab program is
getting one reading out of every 769 you take.
If you want fast data acquisition with a consistent sampling frequency,
you basically have two options:

clock the ADC as fast as you dare, buffer the data in RAM and, when
the buffer is full, send it to the host computer
set a high baud rate and take the data as fast as the UART can send
it.

The first option allows for faster sampling rates, but only as short
bursts, as limited by the available RAM. Given what you have already
written I assume you want continuous acquisition, and thus the second
option. I also assume you are using an Arduino Uno or similar.
At 115.2 kb/s (actually 117.647 kb/s given the rounding), every bit sent
takes 136 CPU cycles, or 8.5 µs. One byte takes 10 bits
(start bit + 8 data bits + stop bit), i.e. 85 µs.
This means there is no point in clocking your ADC that fast: you can set
the prescaler to 64 and each reading will take 52 µs.
What I would do here is configure the ADC to be triggered by
Timer 1, and have that timer deliver the trigger signal every
1360 CPU cycles exactly. Then,
ISR(ADC_vect)
{
    Serial.write(ADCH);
}

assuming of course you have set the left-adjust mode (ADLAR bit in
ADMUX).
With the ADC and the UART working at the very same frequency, you keep
the UART busy without ever filling the output buffer. If your ADC runs
faster than the UART, the buffer will fill out and your timings will get
nasty. On the other hand, if you are really confident in your timings,
you could skip the Serial managing of that buffer and just do
UDR0 = ADCH in the ADC ISR.

What Serial communication baudrate would 1360 CPU cycles related to, for ADC and Serial to be in sync ?

@WupadrastaSantosh: Assuming a 16 MHz clock (like in the Uno), if you Serial.begin(115200);, the UART will take exactly 1360 CPU cycles per byte.

Not sure what "structured noise" you are referring to but some advices.

Check the datasheet to see adc timing requirement. When not enough time is given, acc results are highly correlated serially.
In the acc isr, make sure that atomicity is preserved.
Isr has its overhead so make sure that it is consistent with your acc speed setting.
If you are using only the msb. You can configure the acc to be left alighened, saving you lots of time and headache.

What I meant by structured noise is that the output which has to be at 127, is reaching to either 191 (1.5127) and 63 (0.5127). Isn't this very exact form of pulses... Like it's pdf has just three values, where as the actual one is 127.

For serially correlated results, check your reference, supply decoupling, input signal conditioning, and acc clock setting, to name a few.


text:
Problem with Micro SD card breakout
I was connecting my arduino uno to a adafruif micro SD card breakout and everything worked just fine, i could read the sd, write to it and see all the info about it. To do it i just followed the tutorial in here.
My problem is that when I arrived home the exact some thing wouldn't work and I couldn't read the SD card anymore.
I was thinking it could be a bad contact problem since sometimes i get:
Initializing SD card...initialization failed. Things to check:
* is a card inserted?
* is your wiring correct?
* did you change the chipSelect pin to match your shield or module?

And other times (almost never), i would just get:
Initializing SD card...Wiring is correct and a card is present.
Card type: SD2
Could not find FAT16/FAT32 partition.
Make sure you've formatted the card

I would like to know if I can assume it is the breakout board failling and I would buy a new one, or if it can be any other thing.
Thank you in advance!

Did you try:

Reading the SD card in your computer ... if  you can read (or write) files, that means the SD card is intact
Use a SD card that worked before or similar. Some bigger SD cards (like SDHC, SDXC have less good compatibility). Preferably use a 2 GB or smaller card (unless you have used bigger cards successfully and of the same or smaller type, e.g. SD, SDHC, SDXC).
Try different formattings, like FAT, FAT16, FAT32. I think FAT is the mostly recognized formatting.
Check connections/wires to/from SD breakout, maybe during your leave accidentally you (or someone else) or due to pressure/tension, a contact/wire got loose.
Check another SD card in the SD breakout where the SD card you know is good. If this also does not work, it must be the breakout (or Arduino).
Replace every piece of hardware (including wires) one by one and recheck if it works (after you are sure the SD card itself is ok).

Thanks for your answer, yes i tried a new sd card that i just bought for this and still nothing, and i also formated both cards to fat32 (they are 8 GB), and both of them work on my laptop. I remade alreadythe wiring a thousand times with new material, thats a thing i didnt think of, how can i check if it is the arduino? I have accessonly to a breadboard, wires and the sd breakout

Was your original SD card that worked also 8 GB and formatted by FAT? I will add some more items in my answer (for you and possibly others).

First time i used and worked it was a 8 GB micro SD HC, it worked before and after i formated it. So i guess now i will try a new SD breakout board.

If you ruled out that all other components are still working, probably yes I'm afraid.


text:
Communication between Genuino Zero and Arduino Uno using UART
I want to make my Arduino Uno and Genuino Zero communicate using UART. My Genuino Zero is the transmitter and the receiver is the Arduino Uno.
For the Arduino Uno, I am using the SoftSerial library. I have uploaded the transmitter and receiver codes.
My connection is as below:

Genuino Zero (RX) pin 0 ---------------- Arduino Uno pin 11
Genuino Zero (TX) pin1  ---------------- Arduino Uno pin 10
Ground ----------------------------------   Ground

The Arduino Uno's pin 10 is Rx and pin 11 is Tx, using SoftSerial.
The transmitter transmits 'a'. The receiver receives 'a' and turns a LED on. My problem is that on the receiver, I am not getting anything.
My code is here:
https://www.dropbox.com/s/4w8o2h2k4zs0it5/transmitter.txt?dl=0
https://www.dropbox.com/s/d50uizoz3iove9w/receiver.txt?dl=0
-------------------receiver---------------------
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX

/* Simple Serial ECHO script : Written by ScottC 03/07/2012 */

/* Use a variable called byteRead to temporarily store
   the data coming from the computer */
byte byteRead;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(9600);
   mySerial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  char a[8];
  /*  check if data has been sent from the computer: */
  if (Serial.available()) {
    /* read the most recent byte */
    byteRead = Serial.read();
    Serial.print("rushin\r\n");
    /*ECHO the value that was read, back to the serial port. */
    if(byteRead == 0x61) {
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.write(byteRead);
    }
  }
  if (mySerial.available()) {
    /* read the most recent byte */
    byteRead = mySerial.read();
    mySerial.print("rushin\r\n");
    /*ECHO the value that was read, back to the serial port. */
    if(byteRead == 0x61) {
      digitalWrite(LED_BUILTIN, HIGH);
      mySerial.write(byteRead);
     }
  }
}

-------------------transmitter----------------------------------

/*
  DigitalReadSerial
 Reads a digital input on pin 2, prints the result to the serial monitor
 This example code is in the public domain.
 */

// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 7;
// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println("a");
  delay(1000);
  // delay in between reads for stability
}

Post the code here. Links tend to disappear.

sorry. can't upload text file here. and link is ok

Just copy paste the code here and format it into code block.

What does the product information say? "Unlike most Arduino & Genuino boards, the Zero runs at 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. Applying voltages higher than 3.3V to any I/O pin could damage the board."

yes i know that. and i am working with 3.3 v

And the Uno? How did you connect that? At least pin 11/TX would be 5V if you have not used any signal conversion.

Your receiver code won't say anything to the PC in response to data over the software serial - you only send the indication back on that.  Likely you want to send some indication to the PC instead or as well.  Also be wary of triggering messages that are longer than the ones sent, as they will take more time to transmit and could lead to missing new incoming data.

Your Arduino Zero transmitter code transmits to the USB Serial ('Serial') only. If you want it to transmit to the serial comm on pin 0 and pin 1, you must have it write to Serial1. (Check variants.cpp file ) you will see that Serial1 is uses SERCOM0 which is on pin 0 and 1.
So, Your code should look like this (noitce "Serial" is replaced with "Serial1"):
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial1.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial1.println("a");
  delay(1000);
  // delay in between reads for stability
}


text:
Arduino UNO USART problems
I need to send 6 bytes value from Arduino UNO to the actuator using serial port in order to make it extends. I have added a button to send the data. For example, 0 20 1 1 0 0. The communication settings are 9600 baud rate, 8 data bits, no parity and 1 stop bit. I have used MAX 232 to build a TTL to RS232 circuit. The actuator does not move. Are there any problems on my program? I am new to create USART code. I think I have some problems on transmit function. I am using the build in USART with c code. Here is my code:
#define BAUD_PRESCALER 0x67
int buttonPin1 = 4;
int buttonState1 = 0;

void setup() {
    // put your setup code here, to run once:
    pinMode(buttonPin1, INPUT_PULLUP);
}

unsigned char data1 = 0x00; // 0
unsigned char data2 = 0x14; // 20
unsigned char data3 = 0x01; // 1
unsigned char data4 = 0x01; // 1
unsigned char data5 = 0x00; // 0
unsigned char data6 = 0x00; // 0

void USART_Init(void) {
    /*Set baud rate */
    UBRR0 = BAUD_PRESCALER;
    UCSR0A = 0x00;
    /*Enable receiver and transmitter */
    UCSR0B = 0x08;
    /* Set frame format: 8data, 1stop bit */
    UCSR0C = 0x06;
}

void USART_Transmit( unsigned char data ) {
    /* Wait for empty transmit buffer */
    while ( !( UCSR0A & (1<<UDRE0)) )
    {
        ;
    }
    /* Put data into buffer, sends the data */
    UDR0 = data;
}

void loop() {
    // put your main code here, to run repeatedly:
    buttonState1 = digitalRead(buttonPin1);
    if (buttonState1 == LOW)
    {
        USART_Init();
        USART_Transmit(data1);
        USART_Transmit(data2);
        USART_Transmit(data3);
        USART_Transmit(data4);
        USART_Transmit(data5);
        USART_Transmit(data6);
    }
}

Link to the actuator data sheet, please.

http://www.zaber.com/wiki/Manuals/T-LA#Initial_Setup_and_Testing

sorry my bad...

It is not the main problem just a note,USART_init does not have to be called every time, it is enough if you call it in setup().

The comment /*Enable receiver and transmitter */ is incorrect: you are only enabling the transmitter.

The first thing I do when I have a transceiver that doesn't work is a loopback test. This rules out a lot of potential issues like the wrong pin being used or MAX 232 not being connected correctly.
Receiving your transmission on a PC using USB to RS232 adapter (if you have one) would also be a helpful test.

I would recommend you to use the arduino's built in UART library. Try this code:
int buttonPin1 = 4;
int buttonState1 = 0;

unsigned char data1 = 0;
unsigned char data2 = 20;
unsigned char data3 = 1;
unsigned char data4 = 1;
unsigned char data5 = 0;
unsigned char data6 = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);           // set up Serial library at 9600 bps
  while (!Serial);              // wait till UART initialized, for arduino UNO

  pinMode(buttonPin1, INPUT_PULLUP);
}

void loop() {
    // put your main code here, to run repeatedly:
    buttonState1 = digitalRead(buttonPin1);
    if (buttonState1 == LOW)
    {
        Serial.write(data1);
        Serial.write(data2);
        Serial.write(data3);
        Serial.write(data4);
        Serial.write(data5);
        Serial.write(data6);
    }
}

You should know that as long as the button is pressed data is being sent to the actuator. With that being said, with one button press you may have the commands sent 10 times. Thus, you have to deal with that in your code.

Thank you for your comment. I have tried to use your code but there was only a blink of yellow LED that indicates the existence of serial communication. The actuator did not move. One thing I am not clear, why I need to deal with the commands that may sent 10 times?

Since the code is executed in a loop void loop() and the if statement if (buttonState1 == LOW) is true, UART data is going to be sent as long as the button is pressed even though it is pressed for just 30ms or 40ms. The program scanning is much more faster than a couple of milliseconds.

The actuator should go to the absolute position 275 microsteps and stop there. Can you change the linear position of the actuator by hand and try again

I have changed the position of the actuator manually to original position and send the move absolute command once, but it does not move. I am wondering if the data sent is not in the right form.

To narrow down the problem did you try the Zaber Console it is free and open source. You can find a C lib as well in the same link.

I think you should try another baudrate as well e.g. 115200 . I have read the C  lib. The data structure is the same as above except that a reply from the actuator is expected.

I think that your BAUD rate setting is wrong. The UBRR0 register is a 16 bit wide one thus should be accessed in two 8 bit part, via UBRR0H and UBRR0L. You can check it in the datasheet.
If you further check the datasheet there is an example code in addition to the USART description which shows a correct way of initialization.

#define FOSC 1843200 // Clock Speed
#define BAUD 9600
#define MYUBRR FOSC/16/BAUD-1
void main( void )
{
    ...

    USART_Init(MYUBRR)
    ...
}

void USART_Init( unsigned int ubrr)
{
    /*Set baud rate */
    UBRR0H = (unsigned char)(ubrr>>8);
    UBRR0L = (unsigned char)ubrr;
    /* Enable receiver and transmitter */
    UCSR0B = (1<<RXEN0)|(1<<TXEN0);
    ...
}

As you can see the UBRR's value is calculated using the system clock speed FOSC, with MYUBRR macro which is an equation from the datasheet. Later this value is being set in two part upper 8 bit:
UBRR0H = (unsigned char)(ubrr>>8);

lower 8 bit:
UBRR0L = (unsigned char)ubrr;

(Your transmit function seems to be correct. And as I commented it is enough to call the USART init once in the setup().)

Splitting the write to UBRR0 may have been needed many years ago, but it is completely useless today: gcc knows very well how to write to a 16-bit I/O register.

Also, your formula (ok, Atmel's formula) for calculating MYUBRR is bad: it will systematically round down. You should instead use <util/setbaud.h> from avr-libc, which correctly rounds to the nearest integer. Or better yet, use Serial.begin().


text:
What is the phase of tone?
Is it garanteed (with some precision) that the phase of a PWM-signal generated by tone is the same on each pin? Can it be altered (by internal means of Arduino) so that it's different on different pins?
I'm looking for a way to adjust phases of signals from several pueso-buzzers by either adjusting distances (least preferrable) or programmaticaly (most preferrable) or by external components (if they're not very complicated).

an inverter should work. the NOT gate kind, not the AC making kind...

The arduino.cc description of tone() says “Only one tone can be generated at a time”, so presumably you are using some other software to generate tones on multiple pins.  For example, Brett Hagman's play() code, which Arduino tone() is derived from, uses multiple timers, one per tone.
When using play(), you probably can adjust phase by calling  delayMicroseconds() between the two  play() calls that start up the tone generation; for example:
play(11, 440);
delayMicroseconds(235); // Move 2nd tone 8 cm closer
play(9, 440);

Note, because tone() and play() use one timer per output (for example, timer 2 for first tone, timer 1 for next tone, timer 0 for third tone) there usually will be some timer prescale mismatches between 8-bit and 16-bit timers, which may result in slightly different frequencies, leading to some constant phase shift rate if you use that method.
With the speed of sound about 340.29 m/s in air at standard pressure, the wavelength of say 440 Hz would be under a meter, so I presume you would move speakers just a few tens of cm for phasing; hence a few hundred to a few thousand microseconds of phase offset.  If you want good programmatic control, and also want to have quite a few speakers, external hardware in the form of a delay line or a bucket brigade chip is an obvious approach.
You could simulate a program-controlled delay line fairly easily using a handful of 74HC595 SIPO shift registers, as follows:  Connect the DS of the first '595 to your tone() output pin.  Connect the Q7S output of each '595 except the last to the DS of the following '595.
Now use another timer to repeatedly clock your tone data into the shift register chain.  That is, connect all STCP and SHCP inputs in parallel to a timer output pin.  (Eg, OC1A, OC1B, OC2A, or OC2B, which might be pins like 9–12 on an Uno or Nano).  Run that timer at 10 to 100 KHz, ie, at some rate f that gives you the resolution and range of phase changing that you need.
Calling the shift register outputs o₀, o₁, o₂..., we have oⱼ delayed by (j-i)/f seconds relative to oᵢ.  That is, successive SR outputs represent different taps for different delays.

But is it garanteed that if I turn on two plays simultaneously than I get those PWMs with the same phase and if I turn those on with certain delay than I get phase difference = delay/period?

The main principle behind working with buzzers, in its simplest form, comes down to something along the lines of
digitalWrite(buzzerPin,HIGH);
delay(half_tone_frequency);
digitalWrite(buzzerPin,LOW);
delay(half_tone_frequency)

that, when repeated is enough to generate some tone on a single buzzer. However - to get desired tones (frequencies) right, you have to be mindful of the exact time that passes between each part of the code (the pin needs to oscillate in some frequency to produce a tone of that frequency)
So technically, its possible to create different sounds on different buzzers connected on different(!) pins at the same time, if you know exactly how much time each pin spends HIGH and LOW. This is naturally simpler when they do not need to be active concurrently.

But is it garanteed that if I turn on two tones simultaneously than I get those PWMs with the same phase and if I turn those on with certain delay than I get phase difference = delay/period?

No, this approach is to not use the tone API at all, rather control the "PWM" manually by manipulating the pin states at precise intervals

Ah, sorry, I wasn't attentive enough, very nice, I'll try suggested stuff, but your answer clarifies the issue in the simplest terms (at least theoretically).

If you want fine control over the phases, I assume you may also care
about having low phase noise. In this case your best bet is to avoid
toggling the pins in software and go for a hardware signal generation.
With an Arduino Uno or similar board, this can probably achieved by
programming a timer. I would try the following:
Configure Timer 1 in waveform generation mode 12, i.e. CTC
mode with TOP = ICR1. Set the compare output mode of both channels
to toggle on compare match. Set ICR1 so that the timer has half the
period of the signal you want. Now you can independently adjust the
phases of both outputs by writing to OCR1A and OCR1B.
Note that those registers are not double buffered in this mode, so you
have to be careful about when you write them.
The Arduino core library has no support for such timer configuration:
you will have to learn how to program it yourself. If you are not
familiar with the subject matter, I recommend you start by reading
Nick Gammon's tutorial on timers.

But is it garanteed that if I turn on two tones simultaneously than I get those PWMs with the same phase and if I turn those on with certain delay than I get phase difference = delay/period?

@YakovL: No, with this approach you do not turn the PWMs one after the other: you configure the timer to generate both signals, and when you start the timer you get both of them. The phase difference is not controlled by when you start the signals. It is controlled by the difference between the numbers you write to the OCR1A and OCR1B registers. And you can get single-cycle accuracy on the phase difference provided your frequency is lower than 122 Hz.