text:
H11L1 opto isolator does not pass signal to Arduino (correctly)
I have made a very basic test circuit for the opto coupler H11L1 ('similar'datasheet: http://www.datasheet4u.com/datasheet/H/1/1/H11L1_MotorolaInc.pdf.html))
I use the test circuit:

simulate this circuit – Schematic created using CircuitLab

The LED and 470 ohm resistor is only for testing.
U1 is the Arduino (software serial pin 9/11) and U2 is the H11L1.
The LED is flashing similar to the RX led on the Arduino.
Also I tested before in an even simpler circuit that the signals from the H11L1 pass through pin 4 (although inverted, which seems to be normal).
However, I don't receive any data in the Arduino (I tried different Arduinos, different speeds, different H11L1).
The data I receive from the (hardware) serial/debug terminal:
0
0
0
0

etc.
My sketch:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(9, 11); // RX, TX

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

void loop()
{
    mySerial.write('A');
    while (mySerial.available())
    {
        Serial.println(mySerial.read());
    }

    delay(100);
}

How can I get the correct signal? (meaning 'A' are printed instead of 0's?
Update
New sketch (not having the duplex problem):
#include <SoftwareSerial.h>

SoftwareSerial mySerial(12, 13); // RX, TX

void setup()
{

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

void loop()
{
  Serial.print("Write: A ");
  mySerial.write('A');

  while (mySerial.available())
  {
    Serial.print((int) mySerial.read());
  }

  Serial.println("");

  delay(100);
}

Output:
Write: A
Write: A
Write: A
Write: A

etc.
Update
Problem solved: I put it in an answer for clearity.

First, try looping back the Arduino's RX/TX lines to verify you do not have a full verses half duplex problem.

@st2000 I don't receive anything (guess I have that problem) ... what can I do about that (?), never heard of it (in Arduino context at least)

I'm still looking around.  When looping back, you are depending on the Atmel processor hardware to buffer up received data while your software is busy transmitting it.  Then you are depending on the Arduino serial libraries to get that buffered data (if there is any) after the it was already received.  It is like talking and listening at the same time.  Instead of the usual taking then listening in turn.

(ok in that case I need to change my sketch a bit) ... btw, for this test I put a wire directly between pin 9 and 11 (without any resistor) ... hope that is the correct way?

I am fairly sure the UART connected pins are similar or the same as GPIO.  Interestingly, I can't find an exact match to this problem (if in fact it is a problem).  Most use the UART to send messages followed by and EOL like an '\n".  So they write sketches which expect to talk in turn.  You, on the other hand, probably need to write a sketch which will work byte by byte.  This assumes the Atmel processor you are using can only buffer 1 UART byte.  Take a look at "Serial.readBytes()" to get some ideas.  This is a long way to go just to test the optical coupler.

Perhaps I should add.  In the real world, I would write an interrupt routine to handle the received data.  All it would do is maintain a buffer of received data that is long enough to contain any expected messages until I could get around to reading it.  So when I'm off sending data I will not miss any data being sent to me.  I am not sure how the Arduino serial libraries are written.  But they need to be simple so as to be small and compatible with as many other Arduino libraries as possible.

@st2000 I tried also to print a newline after the A, but it also does not make a change.
Using an interrupt routine for a test seems a bit overkill (in that case I rather wait for the Mega ... or use my old optocouplers which already work, but the H11L1 are a bit smaller.

R2 and R3 form a voltage divider that prevents a proper high voltage; you have to connect the LED to 5V as shown in Transistor's answer. And the real MIDI circuit has more than one 220 Ω resistor; you can increase R1 to 1 kΩ. Anyway, for loopback testing, a direct connection 11 → 9 is OK.

Try without SoftwareSerial: write 0/1 manually to pin 11, then wait a little, read the input from pin 9, and output that value to a LED connected to another pin. Use a delay of one second or so to be able to observe it. If this works, then the problem is not with the hardware.

@CL: That will probably work ... since I tested with putting the Anode to +5 or GND directly to see the LED and that is either on or off, but the problem is with 'faster' (Serial/MIDI) circuits.

@CL: Problem is solved ... see my answer (I had two use two H11L1's because of the inversion... you told me about it, but didn't think it was needed in this case, but it seems it is.

Isn't the problem that you need a second serial for debugging output? If might be a better idea to make that the software serial.

I already made a successful optocoupler test with Serial (using 2 Arduino Uno's, one for sending, one for receiving). But I still didn't get good MIDI information ... I think it has to do with the edge speed ... I can buy a better oscilloscope, but even that wouldn't 'fix' the problem.

@ForTheOneWhoDownvotedHundredOfMyQuestions: please mention why you downvoted, so I can improve it if needed.

simulate this circuit – Schematic created using CircuitLab
I'm not sure I can help much with the MIDI problem but I can help with the schematic. I've reorganised it for clarity. Since the opto-isolator has an open-collector output any loads it is driving should be connected to supply + rather than common.

With the LED only for testing, the actuall pull-up is missing.

Sure. He can put the actual pull-up back when finished testing.

I built the circuit and do not see a change ... also the LED is not burning/flashing, but that is related to the pull-up ... but how I should connect that (?)

I like how @Transistor cleaned up your circuit.  It should work.  CL is correct, you had a voltage divider before and your test LED may have caused problems.  Note, different Arduinos can use different processors with different internal hardware.  Not all processor UARTs are alike.   Some have more hardware buffering which off loads the burden of serial timing from the software.  There is a balance between cost, hardware features and software complexity.  Welcome to Firmware land.

R3 and D1 provide the pull-up. The open-collector output will pull it down when turned on giving almost 5 V across the R3 - D1 combination.

@Transistor ok (thought it was missing in the diagram, thought that R3 would be the pullup (but of course the LED itself also is taken into account)

@st2000 I tried two Arduinos, but none of them are 'official'... and maybe my experience as software engineer does not make it easier in this case (it either works or doesn't work)

Yes, you've discovered the difference between software and firmware :)!  It's the particular processor the board uses (Mega uses ATmega2560 while the Uno uses ATmega328P).  Most copies use the same Atmel chip.  But the bigger and more elaborate boards use complex chips. Some with ARM cores.  It will be these differences in chips which may turn out to make your (high level) code work differently (better) in some cases.  If you really need this (full duplex all the time?) to work, I would try that other serial library AltSoftSerial that @jot suggested if you can.

So far I'm not successful (thought it worked, but it seems not) ... not even with the other serial library (so far).

Although not really the solution ... somehow it works and your circuit made it easier ... now I'm going to add components so it looks more like the MIDI circuit, but I have at least a working version.

MIDI is a more time critical application.  You may want to search for a MIDI centric Arduino library instead of relying on a general serial port library.  In the end, you may find, to get the best performance, you will have to write your own Arduino C++ libraries & learn how to handle interrupts.  Again, welcome to firmware.

Rule of thumb: never use SoftwareSerial (unless you have to, and even then you should avoid it).
The SoftwareSerial works better with higher baudrates. The lower the baudrate, the more trouble you get. Unless you aim for a high baudrate of 115200, then SoftwareSerial can cause troubles again. Remember that using SoftwareSerial means that there is not much else you can do in your sketch.
When SoftwareSerial is used with a very low baudrate of 300, then it could even disturb the receiving of data of other hardware serial ports. Because SoftwareSerial disables interrupts during transmitting and receiving, the lower the baudrate, the longer the interrupts will be disabled.
The SoftwareSerial can not transmit and receive at the same time, and that is what you are doing.
A Arduino Leonardo, Micro, or Arduino Mega 2560 board have unused hardware serial port(s). Use one of those to do tests with a serial port.
As soon as you start using SoftwareSerial for a test, you are actually testing the SoftwareSerial itself.
There is an alternative, the AltSoftSerial Library. it can receive and transmit at the same time. Use a baudrate that is not too high, 9600 baud should be fine.

I will try with higher baudrates ... also I changed my sketch (but without much improvement).
To be honest, I have a Mega, but I don't 'dare' to use it, since that one is now on a breadboard circuit that I'm for sure knows it works (and by disassembling it, I'm afraid I don't have any working solution). I have ordered a new one, and will test it again when I receive it.

To the best of my knowledge, “Software Serial works better with higher baudrates. The lower the baudrate, the more trouble you get” is false.  In general, software serial is incapable of handling data rates like 115200 without high incidence of errors.  OTOH, it should handle 4800, 9600, etc ok

MichelKeijzers, The SoftwareSerial is useless for you, it can not transmit and receive at the same time. @JamesWaldby With lower baudrates, the interrupts are disabled for longer time. With a full sketch and lots of things going on, it will cause a lot of trouble for sure.

I tried with 300, 9600 and 115200 (no changes) ... probably the duplex is the main problem ... I will try this test again when I have the new Mega.

In the Arduino IDE, in the Library Manager, search for: altsoft. Install the "AltSoftSerial by Paul Stoffregen". Find which fixed pins are for RX and TX ( https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html ). Use 9600 baud, and it should work.

I'm afraid it doesn't work ... going to wait for my new Mega (should arrive any day).

Problem solved:
I created a setup with two Arduino Uno's, one which sends the information by a hardware UART, one that receives it. The reason to do this is not to use a software serial and having no problems with the duplex. I thought I need a Mega, but with two Uno's it is also possible.
However, this did NOT solve the problem.
What solved the problem was to use TWO opto-isolators. The H11L1 inverts the signal, and it seems I had to connect the output of the first H11L1 to the input of a second and now it works.

Or invert the connection of the optocoupler's LED (anode to power, cathode to TX), like in the MIDI circuit.

Oh of course (thought it was in sending, but if inverting that way is possible, than it's even better). Just doubting if the MIDI functionality will work (since it will be functionally similar as now) :-(

@CL: Thanks for your remark ... this was the solution .... now I can finally replace my 6N137s by H11L1's ... thanks for your remark and patience (same for all others who helped me).


text:
Unusualy high fail rate with Adafruit Circuit playgrounds
I am on my 4th failed Adafruit Circuit playground, I can usualy program them a few times, like less than 10, then they become unresponsive. no amount of reseting, rebooting, bootloader re-installations, etc seem to help.
I am using Arduino 1.8.1, on a linux platform, running on a Lenovo T510.
I have numerous other MCUs that have never failed... Im just curious why there is such a high failure rate with the circuit playgrounds I am getting.

Ask Adafruit?  idk

Overvoltage somehow? 3.3v Modules with a 5V TTL adapter?

source: Stack Exchange

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

sort: votes


text:
Servo only going one direction till it reach limit
I have a ATTiny85 with a standard servo motor attached to it. I would expect the following sketch to make the servo to oscillate between position 60 and 100 but instead it just to to it's limit (180) and grinds there...
Any ideas ?
#include <avr/power.h>
#include <Adafruit_SoftServo.h>

Adafruit_SoftServo servo;

#define MOTOR_PIN 0

bool flip = true;

void setup() {
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  // Set up the interrupt that will refresh the servo for us automagically
  OCR0A = 0xAF;            // any number is OK
  TIMSK |= _BV(OCIE0A);    // Turn on the compare interrupt (below!)

  servo.attach(MOTOR_PIN);
  servo.write(90);           // Tell servo to go to position per quirk
  delay(15);
}

void loop() {
  if(flip) {
    servo.write(60);
    delay(150);
    !flip;
  }
  else {
    servo.write(100);
    delay(150);
    !flip;
  }

  delay(500);

}

// We'll take advantage of the built in millis() timer that goes off
// to keep track of time, and refresh the servo every 20 milliseconds
volatile uint8_t counter = 0;
SIGNAL(TIMER0_COMPA_vect) {
  // this gets called every 2 milliseconds
  counter += 2;
  // every 20 milliseconds, refresh the servos!
  if (counter >= 20) {
    counter = 0;
    servo.refresh();
  }
}

Thanks.

!flip doesn't really do anything and will probably be optimized out by the compiler. You need to save the result: flip = !flip;
You can simplify the code a bit:
void loop() {
    if(flip) {
        servo.write(60);
    }
    else {
        servo.write(100);
    }
    flip = !flip;
    delay(650);
}

Or, get rid of the delay altogether:
uint32_t last_millis = 0;
void loop() {
    if (millis() - last_millis >= 650) {
        servo.write(flip ? 60 : 100);
        flip = !flip;
        last_millis = millis();
    }
}

That was part of it (must be doing too much Ruby these days).
The other part is that I was compiling with an outdated Arduino core library... Updated and all is good now. Thanks.

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


text:
Unable to upload code to Leonardo
I was using Arduino-Makefile to upload code to a Leonardo via its standard make upload. However, it became "stuck" and unresponsive, as Leonardo's sometimes do. I tried power cycling it, and unplugging the USB cable, but nothing worked. So I tried re-burning the bootloader via an AVRISP MkII programmer and the Arduino 1.8.2 IDE, but that only made things worse.
It somehow uploaded a simple "blink" program, but now the it's completely unable to be programmed via USB. When I run make upload, or use the Arduino IDE's "upload" button, the Leonoardo's status LED begins blinking rapidly and its /dev/ttyACM0 device disappears permanently. I have to power-cycle it to make the device reappear, but the upload still fails, with the error:
/usr/share/arduino/bin/ard-reset-arduino --caterina  /dev/ttyACM0
make[1]: Leaving directory '/usr/local/myproject/main'
make do_upload
make[1]: Entering directory '/usr/local/myproject/main'
/usr/share/arduino/hardware/tools/avr/bin/avrdude -v -p atmega32u4 -C /usr/share/arduino/hardware/tools/avr/etc/avrdude.conf -D -c avr109 -b 57600 -P /dev/ttyACM0 \
        -U flash:w:build-leonardo/main.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/usr/share/arduino/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/chris/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type =
    Software Version = .; Hardware Version = �.
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader

If I manually run:
/usr/share/arduino/bin/ard-reset-arduino --caterina  /dev/ttyACM0

or upload via the Arduino IDE, it makes the Leonardo disappear from USB, and blink rapidly. Pressing the reset button does nothing. I have to manually unplug its USB cable to fix it.
I can program it still using the AVRISP MkII programmer...but obviously that's a huge inconvenience since it takes about 5 minutes just to upload the sample blink sketch, and even then it requires that I first power off the Leonardo, disconnect the programmer, and then power on. For development, where I might need to make dozens of revisions, this turnout is far too slow.
Why am I unable to program the Leonardo via avrdude and USB?

I need to press the Leonardo's "RESET" button to get out of this state (it will always fail after the first flash failure). It works best pressing the "RESET" button when the Arduino log window shows the lines with "PORTS ..." (for example, "PORTS {/dev/ttyACM1, } / {/dev/ttyACM1, } => {}").

Using some examples and similar questions, such as this one and this one, I fixed udev rules for the AVRISP MkII programmer, then I manually reflashed the Leonardo's bootloader with with the MkII by running:
avrdude -c avrispmkii -p m32u4 -P usb -B 8 -u -e -U lock:w:0x3F:m -v
avrdude -c avrispmkii -p m32u4 -P usb -v
avrdude -c avrispmkii -p m32u4 -P usb -u -U efuse:w:0xcb:m -v
avrdude -c avrispmkii -p m32u4 -P usb -u -U hfuse:w:0xd8:m -v
avrdude -c avrispmkii -p m32u4 -P usb -u -U lfuse:w:0xFF:m -v
avrdude -c avrispmkii -p m32u4 -P usb -U flash:w:/usr/share/arduino/hardware/arduino/avr/bootloaders/caterina/Leonardo-prod-firmware-2012-12-10.hex -v
avrdude -c avrispmkii -p m32u4 -P usb -U lock:w:0x0F:m -v

I'm not sure if the first and last command to write the lock bytes were necessary, since they returned the verification error; content mismatch error, but they didn't seem to break anything either.
Oddly, this ran in seconds, whereas the Arduino IDE took almost 5 minutes to burn the bootloader. So I suspect there's a bug in the Arduino IDE that burns an incorrect or corrupted bootloader.
After running this, ard-reset-arduino works correctly, and make upload can successfully upload a sketch again.
On a side note, I'm not 100% sure if Leonardo-prod-firmware-2012-12-10.hex was the correct bootloader to use. Again, I just made an educated guess based on naming. I'd read that the Leonardo uses the "caterina" bootloader, and the directory /usr/share/arduino/hardware/arduino/avr/bootloaders/caterina contained several .hex files, only three of which contained "Leonardo" in the name:
Caterina-Leonardo.hex
Leonardo-prod-firmware-2012-04-26.hex
Leonardo-prod-firmware-2012-12-10.hex

It seemed logical to not use Leonardo-prod-firmware-2012-04-26.hex, since that was likely an old and obsolete bootloader based on the date. That left Caterina-Leonardo.hex or Leonardo-prod-firmware-2012-12-10.hex. Unfortunately, checking the commit logs shows they're exactly the same age. In my experience, prod tends to mean the final or production product, so I decided to try that one first and it worked. If anyone knows what Caterina-Leonardo.hex is for and how it differs from the others, please tell me. I don't want to risk breaking my Leonardo again experimenting with this.
The only issue I'm having now is that after I upload my sketch, with uses ROS and about 49% of the Arduino's memory, I again can no longer upload new sketches to it. I'm assuming the sketch's use of the Serial port is somehow stopping ard-reset-arduino from properly resetting it`. However, I the Arduino IDE is still able to upload sketches, so as a clumsy workaround, I can use that to upload the "blink" sketch, afterwhich then I can upload my own revised sketch.

If you believe this has fixed your issue please accept your own answer. Thanks!


text:
Neopixels with I/O expander
Because I have no pins available on my Wemos D1 mini, I want to drive my Neopixel ring from a MCP23008 I/O expander.
I'm trying to run the 'simple' example from the Adafruit_neopixel library. How do I declare the Neopixel pin number when using say pin 0 on the MCP23008 - or is this impossible?

I don't think that will be an option. The NeoPixel parts need very tight control of the timing in order to work, if the pin timing is wrong by 100 us the wrong data will get latched in.
Can you move some other functions / pins onto the IO expander and then drive the neopixels directly from the processor?

Thanks Andrew. I thought all chained rgb leds with processors were called neopixels. What I have is 10 x 'WS2812B WS2811 Mini board IC 10mm*3mm DC5V SMD 5050 RGB Leds'. My mistake. Not sure if that makes a difference. Appreciate your thoughts re moving other functions to expander though am using i2c, SPI and need RX/TX for nextion display

NeoPixel is the Adafruit marketing name for WS2812 LEDs. You only need 1 pin, exactly what you can move I can't answer without a lot more detail on your system but your best bet would be something slow, a chip select pin or something like that. If your SPI device has a select that would be the obvious choice (or if it's the only SPI device you may be able to wire the select low all the time and save a pin, some devices let you do that, some don't)

I think you will need to write your own library.  This isn't as bad as it seems.  If the library uses analog write then it won't work, because I don't think you can do PWM with that expander.
The library writes directly to pins.  You need to intercept this behaviour and tell the library to tell the MCP230008 to write to the pin.  I haven't seen the library I question, but this should be straight forward.
If you take the existing Adafruit library and find where it writes to a pin.  Rather than calling digitalWrite it needs to call expanderWrite(pin, state).  Every instance of pinMode() needs replacing with explanderPinMode(pin, mode) Then write yourself those two functions that use I2C/SPI to set the IOX's registers to implement what  you need.
The IO Expander is not going to be a good idea if the library requires critical accurate timing, because of the lag of telling the IOX to do things.  An alternative is to use another D1 as the IO expander.

look at the code for Neopixels: https://github.com/adafruit/Adafruit_NeoPixel/blob/master/Adafruit_NeoPixel.cpp Both the Adafruit Neopixel and the FASTled libraries are highly optimized for the timing specific RGB leds. Leds with a PWM signal would be no problem, there are many modules that can do PWM. Leds with a clock signal are no problem, they don't use specific timing. It's the timing specific protocol of Neopixels that is a problem.

Thanks Code Gorilla. I thought all chained rgb leds with processors were called neopixels. What I have is 10 x 'WS2812B WS2811 Mini board IC 10mm*3mm DC5V SMD 5050 RGB Leds'. My mistake. Not sure if that makes a difference re timing issue. ! don't have enough knowledge to amend the library - but many thanks for your suggestions

What library are you using to control the LEDs?

library is 'Adafruit_NeoPixel' - simple working ide sketch below:
#include <Adafruit_NeoPixel.h>
#define PIN 2       // pin used for Neopixel
#define NUMPIXELS 1 // No. of NeoPixels attached
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
void setup() {
pixels.begin(); // Initializes the NeoPixel library.
}
void loop() {
pixels.setPixelColor(0, pixels.Color(255,0,0)); pixels.show();delay(500);
pixels.setPixelColor(0, pixels.Color(0,255,0)); pixels.show();delay(500);
}

Ooops - ide looks a mess - can't see how to include file as an attachment. Can you read it?


text:
Uno - PCA9685 Servos are too shaky before stabilizing - when using two channels
I'm trying to control a Tilt pan with an Arduino Uno. And the Sunrounder servo driver is used to do this, which comes with it's own capacitor out of the box.
The pan has two Servo motors, that help it face any direction.
I have set this up and even calibrated, so that I can input numbers between -90 degrees to +90 degrees horizontally, and 0 to 90 vertically. And it is working...
But the problem is that, when it is idle for too long, or when I connect it in the beginning, The tilt pan shakes intensely for about 20 to 30 seconds and turns every other direction before stabilizing to the correct point. As if it had a seizure!
When I disconnect one of the Servos, this problem solves. Two servos are connected to the first and second channel of the servo driver. So it seems that these two channels have an effect on each other.
Besides, there is not much weight on the tilt pane. And removing the weight does not seem to help.
init code:
pwm = Adafruit_PWMServoDriver();
pwm.begin();
pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
yield();

turning horizontally:
void Platform::setHorizontal(int d){
  if(d > 90)
    d = 90;
  if(d < -90)
    d = -90;
  point->setHorizontal(d);
  d = (d * 2.555) + 70.0; // calibrating.
  pwm.setPWM(0, 0, 325 + d); // 325 = (150 + 600) / 2
}

How can I solve this?

Start by verifying the power supply is adequate, then go from there. If nothing else try a much bigger capacitor.

Changed the power supply with a more expensive one, Worked like a charm. I wish I could give you a Medal.


text:
Powering my Arduino Mega project
What power source should I use for my Arduino Mega project (involves 2 steppers, 2 servos and 2 dc motors)?
I tried to run two stepper motors with 9V battery. But the battery dried out. I am thinking of 8 AAA batteries. Is there a better option? How about powering through Arduino with the help of a DC adapter?

What is the voltage of the DC motors ? Do the stepper motors work at 5V ?

3.5v. yes,it works at 5v.

Low voltage steppers are usually very high current, and usually used with much higher voltage chopping drivers.  Your question is not presently answerable.  In general terms, AA's are a better choice than AAA's, but steppers are not efficient and are rarely used in battery powered gear.  Selecting DC power drives for steppers can itself involve complicated engineering, especially when you get beyond the re-purposed PC power supplies used in desktop 3d printers, "heavy iron" linear supplies are traditionally preferred.

To properly answer this, you first have to determine how long you want your application to be able to run on a full charge. Clearly, it'll run on a 9V battery, but not for very long.
To determine the appropriate power supply, you need to calculate the overall voltage and current requirements for the various components.
The Mega needs a pretty minimal power supply, just 5V @ 200mA.
You don't specify the ratings for your motors. Servos are typically 5-6V @ 500mA, but I'm only guessing. Steppers and DC motors vary quite a lot.
The first step would be to find the specifications for all your motors, and find the maximum values, specifically the operating voltage and stall current. Hypothetically, say the maximum voltage for all the motors is 5V, and the stall currents for the steppers, servos and DC motors are 1A, 1A, 500mA, 500mA, 3A, and 3A respectfully. (Again, this is just an example. Find the true values yourself). That means you'll need a supply that can safely deliver 1+1+0.5+0.5+3+3+0.1 = 9.1A @ 5V or 45.5 watts.
If you want to use a battery (instead of a stationary supply like a DC adapter), you'll need to chose a battery with adequate mAh rating, which is the total number of amps it can deliver in 1 hour.
Perfectly predicting battery life greatly depends on the battery chemistry and your application's average current draw, both of which great very complicated, so I won't go into that here. A battery is considered effectively "dead" when it's depleted to around 80% of it's fully charged voltage. You can lookup the formulas and do the math yourself, or you can use some online calculators to help you estimate discharge times for different battery and load configurations.
However, as a general rule of thumb, you want to select a battery with a voltage greater than the minimum voltage required by any of your components. For your application to run for 1 hour, it's mAh rating should also be greater than your application's total current consumption. To run longer, you'll need to find a battery with a higher mAh rating, or higher voltage that a switching regulator can use to convert that extra voltage into current.
The other important factor, which complicates these calculations, is the type of voltage regulators you use. If you want to power everything from a single battery, you'll definitely need some voltage regulators. Preferably, you should use high-efficiency switching regulators. For this purpose, you can find cheap UBECs used for RC applications on Amazon or Ebay. You should have one for the Arduino and each motor (or pair of motors if you want to save on cost or complexity). Just make sure the regulator's voltage and current requirements are greater than what's consumed by your components.
I find using 2 or 3 Lipo batteries in series, especially 18650 cells, are the cheapest and easiest way to provide power for mobile applications that have high spikes due to motors. For stationary applications, a 12V DC wall adapter with a high current rating would be simpler.
If you want to use akalines, I'd recommend using separate batteries for the Arduino and motors. Akalines aren't well known for being able to deliver high current. Motors can demand a lot of current, and if the battery can't deliver enough, it'll cause the voltage to drop, resulting in the Arduino browning-out. However, lipo batteries, or non-rechargeable lithium batteries are better suited for this.


text:
Which Arduinos have a true serial port?
After driving myself insane with an unreliable Leonardo, I narrowed down the problem to its serial port. Namely, it's not a true serial port, but some sort of simulated monstrosity that can't be reliably reset. This makes uploading sketches immensely difficult. I found that neither Arduino-Makefile nor the Arduino IDE can reliably upload sketches to a Leonardo, and succeed only 10% of the time.
It took me awhile to accept just how terrible the Leonardo was, because before this, I had only used the Uno and Mega, which are extremely reliable. They've always "just worked" for me, so I couldn't understand why Arduino would release a board as unusable as the Leonardo. I've since realized the Uno is so reliable, in part because it has a more complete serial port, and don't use the dreaded 32u4 chip and its fake serial port that doesn't support the DTR or RST pins.
That said, which Arduino's have a real serial port? Is it only the Uno and Mega? After months of banging my head against a Leonardo, I want to avoid anything else that uses the Atmega32u4 chip. Unfortunately, looking at all the various boards, it looks like many, especially most of the newer ones, use the 32u4.
Am I missing something here? Everything I Google an error uploading with avrdude or the IDE, the results always mention problems with boards like the Leonardo and their unstable serial ports. Why does Arduino keep using the 32u4 chip if it's that unreliable?

No Arduinos since the Arduino Serial have a real serial port. They all leave it to the USB-UART bridge (if any) to handle anything beyond RX and TX.

Strange, I (and many others) have never had such problems with the Leonardo not the other 32U4 based boards.

Most of your question is just a rant. And your definition of a "real" serial port seem to be no native USB support. There are Arduinos with native USB support that are not 32u4 based but ARM based.

Your problems are likely caused by loading bad sketches.  A more productive question would focus on the means of recovering from this, ie, identifying a reliable way reset the board and stay in the bootloader to erase the bad sketch.

@ChrisStratton, I doubt it's the problem with the sketch. I was able to upload the same sketch to an Uno and didn't experience any issues. I heavily researched ways reset the Leonardo, and the near universal answer was that were was no reliable method, short of using an ISP to reflash the bootloader, which is what I did, and why I dislike the Leonardo. I expected this question to get heavily downvoted, because I know you're very defensive of these terrible boards, but I'll leave it up because I stand by my experience. Please everyone, avoid the Leonardo like the plague. It's a bad product.

@Cerin, I hear you. In linux, with an old Leonardo bootloader or third party bootloader, and a wrong sketch, and something called 'modemmanager' in linux, it is a real problem. In Windows and with a recent bootloader, it is working 100% okay. Do you have a programmer, and did you burn the bootloader with the Arduino IDE ? In linux, remove the 'modemmanager'. Yes, the sketch can be a problem when sending too much to the usb serial port. It could block something, preventing a restart of the bootloader.

A flawed sketch will not prevent reprogramming of an Uno; the same code on a Leonardo will prevent the logic that can intercept programming requests after the start of a user program from doing so.  But it's still a badly written sketch.

@ChrisStratton, Why is documentation of these shortcomings in the Leonardo so difficult to come by? Where's the list of things not to do so you don't disable your Leonardo? The Arduino community prides itself on documentation, but I found few solutions Googling this problem. Had I known it was so fragile and incompatible with Uno sketches, I would never have bought it. And therein lies the reason why these flaws aren't advertised...

@Jot, These problems began when I flashed the most recent bootloader using the 1.8.2 IDE. That completely disabled sketch uploading via USB. I had to manually use avrdude to flash the bootloader, as I described here, to restore it. What problems does modemmanager cause? I have the modemmanager package installed, but it's a service that's not running.

@Cerin - Actually Arduino documentation is notoriously, and universally, horrible in comparison to that of actual engineering components, libraries, and APIs.  In any other context, the fact that a USB stack can be broken by uncareful use of interrupt disables, clock, or I/O setting changes, or general memory corruption or execution runaway is well known.

@Cerin, remove the modemmanager.

There seems to be quite a few Arduinos without a 32U4, like:

Uno (you mentioned it already)
Mega (same)
Lilypad Snap
MKR1000
Pro
Pro Mini
Zero
Due
Ethernet
Mini
Nano
MKR Zero

See the list at Comparison table.


text:
Measuring time between two photoresistors and printing time on lcd
I am working on a project that is supposed to record the time difference between two photoresistors that are 4in apart. The photoresistors are sensing the passing of water or other liquids on a chute/ramp.
The liquids range from water to milkshakes so the time difference shouldn't be more than 2 or 3 seconds at most (I would think). I'm okay with the accuracy being off by a a few tenths of a second.
I am using Photo cell (CdS photoresistor) for my project.
I have looked online and haven't seen a similar project. I want to be able to display the time difference on a lcd.
I have my lcd up and running but I'm not sure how to code the time difference. My photoresistors are connected to A0 and A1 and I am using digital pins 7-12 for the lcd. If anyone has any advice that would be very appreciated!
I'm sure I missed something so ask any clarifying questions

Please edit your question (click "edit") to answer the following:  Is the time difference a few tenths of seconds, milliseconds, or what?  How accurate does your measurement need to be?  What is your photoresistor part number?  Can you read it via a digital comparison, or does it need to be analog input for some reason?  How frequently do measurements need to be made?

You are asking about

the time difference between two photoresistors

This, to start with, makes little sense. Photoresistors are analog
devices. Their resistance, and thus the voltage you measure, is a
continuously varying quantity. The first thing you have to do is to turn
them into logic (i.e. either “off” or “on”) devices. The simplest
approach is to compare your analog reading to a threshold:

if the reading is above the threshold, you will say LDR is in the
HIGH state
if it is below the threshold, the LDR is in the LOW state.

There is a problem with this simple approach though: when the reading is
close to the threshold, the ambient noise can make many spurious
transitions between LOW and HIGH. The simplest solution is to have
not one, but two thresholds. This is called “hysteresis” and is
something you definitely should have whenever you are using thresholds
against analog readings. This can be coded as follows:
const int THRESHOLD_LOW  = 400;  // dummy value
const int THRESHOLD_HIGH = 600;  // dummy value

int HystereticRead(uint8_t pin, int previousState)
{
    int reading = analogRead(pin);
    if (previousState == LOW && reading >= THRESHOLD_HIGH) {
        return HIGH;
    } else if (previousState == HIGH && reading < THRESHOLD_LOW) {
        return LOW;
    } else {
        return previousState;
    }
}

Obviously, the thresholds you will use will not be these dummy values:
you will determine them from experiment.
Next thing is to record transitions. You do not want to look for a
particular state of the LDR, but for the moment it moves from one state
(say LOW) to the other. This is done by comparing the new state you
read to the previous one, as in:
static int state0;  // state of the LDR 0
int new_state = HystereticRead(A0, state0);
if (state0 == LOW && new_state == HIGH) {
    // LDR 0 went from LOW to HIGH.
}
state0 = new_state;  // save for next time

Last thing, and really the simplest, is to record times. You just have
to call millis() to get a timestamp, and compute a difference between
timestamps to get a duration in milliseconds. Here is how you could
write it:
void loop()
{
    static int state0, state1;  // states of the LDRs
    static uint32_t time0;      // last time LDR 0 went HIGH

    // Check for LDR 0 going HIGH.
    int new_state = HystereticRead(A0, state0);
    if (state0 == LOW && new_state == HIGH) {
        time0 = millis();
    }
    state0 = new_state;

    // Check for LDR 1 going HIGH.
    new_state = HystereticRead(A1, state1);
    if (state1 == LOW && new_state == HIGH) {
        uint32_t time1 = millis();
        Serial.print(time1 - time0);
        Serial.println(" ms");
    }
    state1 = new_state;
}

Thank you, Edgar! This was very comprehensive and, better yet, worked!

The most accurate approach is via In out capture on your timer.
Alternatively you can use an interrupt to start and stop the timer.
The worst approach is to poll
However, phtoresistors are slow and generally inconsistent. This can lead to errors in reading. S phototransistor or diode works better.
Edit: it is crazy to try to read the signal in analog. Instead design the circuitry so that it breaches the digital low or high thresholds so you can use digitalRead instead.
You can simply use millis or micros to time stamp the events and calculate the difference.
If you want more precise timing measurements, Google ticks implementation.
edit 2:
here is what I tried:
if (dtime_running==0) {             //event 1 has not arrived
    if (EVENT_ON(EVENT1_PIN)) {     //event 1 has arrived
        dtime = time_now();         //time stamp the event
        dtime_available = 0;        //data not yet available
        dtime_running = 1;          //time measurement running
    }
} else {                            //event 1 has arrived and now wait for event 2
    if (EVENT_ON(EVENT2_PIN)) {     //and event 2 has arrived
        dtime = time_now() - dtime; //calculate the timing difference
        dtime_available = 1;        //data now available
        dtime_running = 0;          //stop taking measurement
    }
}

On two pulses that are 500ms apart, here is the measurement:

Notice that in the box on the upper right, dtime has a value of 500, just as we expected.
the risk with this approach is that if the loop has other tasks, jitters to the measurement will show up. but for slow events, or long time measurements, it may not matter that much.

Polling is more than fine if you are after a resolution in the 100 ms range.

+1 for highly relevant point about CdS response times.

I assume you want to measure the difference in time between drops or a change in the resistance of the photo resistors?
Measure every x ms the values of the photo resistors. You can use a sleep for this (or maybe you can just continuously measure).
You have to store the measurements probably, to calculate, when a signal is changing. Also you have to store the times.
E.g.
      Resistor 1    Resistor 2
 0 ms          10            20
10 ms          10            20
20 ms          30           600     Drop at resistor 2
30 ms          30           620     Drop at resistor 2
40 ms          45            20     Drop passed resistor 2
50 ms         400            20     Drop arrived at resistor 1

So you know that the drop (delay) is 50 - 20 = 30 ms
You have to make an algorithm that will see this change, and also you might have to take into account multiple drops (so counting of drops/signal changes).


text:
Echo from device not matching input
I'm writing a char array to a device with an arduino mega that should be giving me an echo back, instead, I'm getting an array back with different chars that correspond to my sent function, but not in a way I can figure out. for example {1,6,250,0,91,233,252} returns the array {127,62,1,146,90,0,0}
As 1 is always returning 127, I'm guessing it has something to to with how I'm casting my received data, but after messing with it for a few hours, I can't seem to get it to cast correctly.
Main Function
gets destination address and data, echos back if requested
calls CRC(this works fine) and SkRead(the problem area)
void Create_Message(int Address, int Data, bool echo)
{
  lcd.setCursor(0,1);
  lcd.print(Address);
  lcd.print(" ");
  lcd.print(Data);
  Address--;
  byte SvAdd = 1;
  byte FuCode = 6;
  byte AddHi = Address>>8;
  byte AddLo = Address;
  byte DatHi = Data>>8;
  byte DatLo = Data;
  byte AdDa[] = {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo};
  uint16_t crc=CRC(AdDa,sizeof(AdDa)/sizeof(AdDa[0]));
  byte CrcHi = crc >> 8;
  byte CrcLo = crc & 0xFF;
  /*U8 Slave Address, U8, Function Code, U16 Address, U16 Data, U16 CRC
  * to
  *[U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
  */
  unsigned char cmd[8]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcLo,CrcHi};
  for (int i=0; i< 8; i++)
  {
  Serial1.write(cmd[i]);   // Send string
  if(echo){Serial.print(cmd[i]);Serial.print('.');}
  }
  if(echo){Serial.println();}
  if (SkRead(echo) == cmd)
  {
  Serial.print(Address);
  Serial.print('\t');
  Serial.println(Data);
  }
  //clear line
}

CRC
(works fine, just wanted to show full code)
/*---Create CRC Function---*/
uint16_t CRC(byte AdDa[], int Size )
{
  uint16_t crc16 = 0xFFFF;
  int pos = 0;
  int i = 0;
  /*Write CRC*/
  for (pos = 0; pos < Size; pos++)
  {
    crc16 ^= AdDa[pos];          // XOR byte into least sig. byte of crc
    for (i = 8; i!= 0; i--) // Loop over each bit
    {
      if ((crc16 & 0x0001) != 0)        // If the LSB is set
      {
        crc16 >>= 1;                      // Shift right and XOR 0xA001
        crc16 ^= 0xA001;
      }
      else
      {
        crc16 >>= 1;                      // Shift right
      }
    }
  }
  /*Note, this number has low and high bytes swapped,
  so use it accordingly (or swap bytes)*/
  return crc16;
}

SkRead
This is my problem area, I'm sure the data is being sent and read correctly, but one of my assignments is throwing it off so the received echo is not received in a way that matches what is sent.
unsigned char SkRead(bool echo)
{
  digitalWrite(Pin13LED, HIGH);  // Show activity
  outputstring = "";
  unsigned long bide=millis()+2000;
  byte inChar;
  while(Serial1.available()<8 && bide>millis()){}
  while(Serial1.available())
  {
    inChar = (byte)Serial1.read();
    outputstring += (char)inChar;
  }
  //Serial.println(outputstring);
  digitalWrite(Pin13LED, LOW);  // Show activity
  int charl = outputstring.length() + 1;
  unsigned char outputschar[charl];
  outputstring.toCharArray(outputschar,charl);
  if (echo)
  {
    for (int i=0; i< charl; i++)
    {
     Serial.print(outputschar[i]);
     Serial.print('.');
    }
    Serial.println();
  }
  return outputschar;
}

One thing I notice: You have CrcHi and CrcLo reversed in the array definition. Is it supposed to be?

Yes, low comes first.

I don't know where to start.

You did not provide a full sketch. There is, for example, no Serial.begin1() in sight.
You did not provide enough information about the device. If you don't want to tell us what it is, then give an indication of its age. In the 1980's it was common to have 7E1 format (7 data bits, even parity, 1 stop bit).
You have to be sure what the baudrate is. To detect a wrong baudrate, you need a oscilloscope or logic analyzer. When the device has a processor and the baudrate is derived from it's clock, the baudrate could be different from the specified baudrate by a few percentage. That is already a problem with the Arduino.
It could be a problem with inverse voltage levels. What does the device use as idle and as active level ? The Arduino Mega uses +5V at the TX pin when idle, and low is active. That means that the TX pin is normally high, and the first low pulse is the start bit.
The device could return an error code instead of an echo.
Your SkRead function can be improved:
Using a String object to collect the incoming data and after that converting the String object to a unsigned char array to use it, is not the most elegant solution. You could just use a unsigned char array to read the incoming data.
It is not okay to add something to the millis value. That is a problem when millis does a rollover (after 50 days or so).
Normally a character is read as soon as it is available. You wait until 8 characters are in a buffer. No one else does that.

To solve this puzzle you need more information. Try to capture the RX and TX signals with a oscilloscope or logic analyzer. Or else try to write a very small sketch that creates the problem.
My best guess is that it is not your sketch, but perhaps a combination of inverse levels, parity and baudrate.
[ADDED]
After writing down the bits over the serial bus, it might indeed be inverse voltage levels and maybe something with 7 bits or parity. That would also explain the last bytes to be 255. Those 255 are not valid data.


text:
Why is 8x8 matrix pins do not correspond to rows and columns order?
It would be easier to program led matrix if 1-8 pins corresponded to 1-8 rows and 9-16 pins corresponded to 1-8 columns.
Instead there is the following arrangement:

Why is it made like this?

It's probably easier to manufacture, other than that, I don't see why.
If this is a serious issue, you can contact your manufacturer, since he is most likely to know why.
You can:

Work around the issue, by wiring pin 1 to input 9, pin 2 to input 14 etc.
Make a software solution like:
#define ROW1 9
#define ROW2 14
Buy an LED-matrix that has the pins in the correct order (check the datasheet before purchase).


text:
ESP8266 UDP multicast doesn't receive packets
I am currently working on an ESP8266 with the Arduino IDE. I try to implement an ESP8266 in STA mode as multicast receiver. I was writing my code with the help of this documentation. Especially the following part:

The WiFiUDP class supports sending and receiving multicast packets on STA interface. When sending a multicast packet, replace udp.beginPacket(addr, port) with udp.beginPacketMulticast(addr, port, WiFi.localIP()). When listening to multicast packets, replace udp.begin(port) with udp.beginMulticast(WiFi.localIP(), multicast_ip_addr, port). You can use udp.destinationIP() to tell whether the packet received was sent to the multicast or unicast address.

Sending to the multicast group with udp.beginPacketMulticast(addr, port, WiFi.localIP()) and udp.write(message, messageLength)works flawlessly.
The receiving part of my code is as follows:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

#define BUFFER_LENGTH 256

const char* ssid = "xxxxxx";
const char* password = "xxxxxx";

WiFiUDP Udp;
IPAddress multicastAddress(226,1,1,1);
unsigned int multicastPort = 4096;

char incomingPacket[BUFFER_LENGTH];

void setup(){
    WiFi.mode(WIFI_STA); //station
    WiFi.setOutputPower(0);
    while (WiFi.status() != WL_CONNECTED)
    {
        WiFi.begin(ssid, password);
        delay(500);
    }
    Udp.beginMulticast(WiFi.localIP(), multicastAddress, multicastPort);
}

void loop(){
    int packetLength = Udp.parsePacket();
    if(packetLength){
        int len = Udp.read(incomingPacket, BUFFER_LENGTH);
        if (len > 0){
            incomingPacket[len] = 0;
            Serial.printf("%s\n", incomingPacket);
        }
    }
}

When sending a packet with a simple multicast sender (with matching IP and port), my multicast receiver on my linux laptop receives the packet, but the ESP8266 doesn't.
Maybe some of you have experienced a similar behavior and are able to give me some hints, where I might be wrong.
EDIT:
Since the time I asked this question I completely ruled out an error of the sender on the linux machine by using a verified, 100% working sender. The ESP8266 still doesn't receive any multicast datagramms.

Are the laptop and the ESP8266 on the same network? If not, you need to adjust TTL for the simple multicast sender. Default is 1.

yes they are both on my home WiFi

that still does not work and workaround above does not help. See also https://www.esp8266.com/viewtopic.php?f=8&t=15467

I recently had the same problem.
The unequivocal answer is that there is a power optimization (internal by Espressif) to save power, I guess, and it really creates havoc in the UDP Multicast receiving. Why? I have no idea. Same problem with the ESP32 and ESP8266.
Solution:
#include "user_interface.h"

and after:
WiFi.mode(WIFI_STA);
// the below instructions and now u will receive.
wifi_set_sleep_type(NONE_SLEEP_T); //LIGHT_SLEEP_T and MODE_SLEEP_T

Thank you very much for the answer. This is a really hard to find solution.

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


text:
Do all arducam need the "Arducam-F Shield"?
The information on this is so greatly lacking to the extent that no related youtube videos could be found, no internet material and the seller seems to be very important and not answer to my questions as he is supposed to.
Also he appears to be the only seller to offer such a variety of arduino cameras.

I want to choose colored arduino camera for my project, but I am unable to receive enough information so that I can choose the appropriate arduino camera.
The most important for me to know is does all arduino cameras need the arducam-f shield board in order to work properly (i.e be programmable, colored, with "decent" quality and be able to capture photos in less than 1~2 seconds)

This is "5MP Mega pixel OV5642 Sensor Camera Module w CS mount Lens" It costs US $29.99. The description doesn't mention the need of any other 3rd party hadware in order to work.

This bellow is "Arducam-F Shield V2 Camera module shield /w OV2640 for Arduino UNO MEGA2560 DUE" it costs US $29.99 and is a camera that evidently comes with this magical shield. We can see that the version is slightly older than that on the other cameras.

This is "2 Mega pixel Camera Module MT9D111 JPEG Out + HQ lens" for US $21.99 and also, like in any other description, the need of shields is not mentioned

And this is "2Megapixel MT9D111 Auto Focus lens camera flex module with Adpater board" that has autofocus, is 2MP like the one above, comes with .... ?Adapter board"? (nothing like that is shown in the pictures or described in the description) and costs only US $9.99. It looks ugly compared to other cameras.

These was the 4 example arduino cameras I would choose from and do all of them need arduino shields in order to do what a camera should do?
(Explaining differences, pros and cons will be very useful to everyone who are in the same boat as I am)

@CodeGorilla Any references/tutorials/examples or items I can buy?
I can surely not learn how to operate with it out of nowhere, I need to start from somewhere. Also how come only lo res images? Only with shields I can do hi res images?

@CodeGorilla Also do you imply that I should choose to buy the arducam-f shield module with its humble camera? Since buying the camera for 10$ won't give me good quality, resolution and speed and I would probably need to spend more money, time and efforts to get it work fine.

The only way to get high Res, good quality, and speed all together is to not use an Arduino with a camera.

@CodeGorilla So with the Arducam-shield I can not make photos every 2 seconds, that will be enough for proving the intruder's identity? (I thought the shield has its own processor and memory)

P.S I also thought arduino uno has 2KB of RAM and 16MHz processor.

@Edenia - I think it would be best if you experimented to see if the hardware works as you want it too.  I'm sorry that I am unable to explain the reasons why I believe you have chosen the wrong solution, again.

For a project I'm doing I added 128 KB SRAM, however, you have to 'manually'  program it (meaning you cannot use easy variables as heap/stack). But for a 1024x768x16 bit pic you need 1,5 MB (uncompressed). You probably can get bigger (S)RAM but that cost either more and uses many more pins, which the Arduino has not that many. And of course there is the speed of 'just 16 MHz' .

You have three requirements:

Good quality (colour)
High resolution
Fast operation

Those three requirements together mean you cannot use a normal Arduino.

The Arduino has nether the memory nor processing power to directly communicate with a camera module.
The ones you can communicate with have internal buffer memory and use a slow UART interface to transfer a frame. That is not fast.
The Arduino cannot deal with a large picture regardless of speed. All you can do is pass the image through to somewhere else for processing. Slowly.

So you can either have very low resolution or slow speed.
So use a Raspberry Pi or something similar which is more capable of using a camera (indeed, the Pi has a dedicated camera connection).

What about the variant with the arducam-f shield?

It doesn't magically make your Arduino more powerful. It's just convenience, but still slow/low resolution.

The "F" version contains a FIFO. You trigger a snapshot and the image is saved in the FIFO. You then download it (slowly) through the Arduino to somewhere else (SD card, etc). You can't process it in any way.

Let's say I don't want to process the photo, but to send it via gps module

How do you send through GPS...?

GPRS* The shield provides GPRS connectivity.

Then you don't care about speed that much anyway a nice the GPRS will slow you down. I do that very same thing in a project. Takes about 20 seconds to send a frame.

I will dig info about TTL Serial Camera.. see if it can make photos fast enough.
From what I saw it is possible to have camera make JPEG photos and save them to memory stick for 1 second with acceptable quality and not so good resolution.

Then I will use MMS or hard compression and I will buffer the images. See if I can make them uploaded for 10 seconds or so


text:
Problems with ACS758 Hall Effect Current Sensors - Calibration and no Signal
I purchased 3 ACS758 Hall Effect Current Sensors datasheet on ebay. A 50,100 and 200A, all three are bi-directional. They look like this.
With no current the 50A outputs 477 on the analogue input (2.33v), the 100A outputs 509 (2.48v) and the 200A outputs 512 (2.50v). At no current they should all be at exactly mid range i.e. 512 (2.50v). The datasheet says they're factory calibrated as such. I've tested them one after the other, both with 5v from the Audrino and with a separate 5v supply. As I've tested one after the other it's not likely to be stray magnetism or VCC.
I've then put them in a circuit drawing about 9amps. Accounting for the offset of zero amps the 50A and 100A measured the increased voltage correctly. The 200A doesn't change.
Is there any other tests I can do to see if I'm doing something dumb or are they all damaged?

Did you measure VIOUT with anything else than an Arduino? A precision digital voltmeter, for example? Are you aware that precision measurements require precautions such as insulation against noise? Also make sure that your reference voltage is extra stable. All AVR micro-controllers have a noise reduction mode that increases accuracy. The ADC accuracy of the ATmega328P is also highly dependent on the ADC clock: the slower the more accurate. Refer to the ATmega328P datasheet for more information.

Thanks for the reply Nasha. I will try measure VIOUT with my cheap multimeter, I don't have a precision one. I (think) I understand your point about noise. With zero load I'm getting quite a consistent reading, just a different one from each device. It should be 2.50v from each device and instead it's 2.33v and 2.48v (according to the arudino). Even if they're not the correct voltages they're different to each other. The chip is supposed to come factory calibrated to 2.50v for zero load. Do you think noise or ADC accuracy could be the cause of the calibration problem?

If you have an oscilloscope, you will see how noise does affect any measurement. And since calibration is one... Repetitive measurements, averaged will reduce the effect of noise, as if you filtered the signal through a RC low-pass filter, more or less. Anyway if you read different values (with your multimeter as the only load) then the accuracy of the current sense devices may be the reason. Doesn't mean they're faulty (check the datasheet). Means you may have to account for a certain offset in your software, which you measure through calibration; that's what it's for. Also check the 5V...

Also the 0.1µF bypass capacitor is key in stability. I don't know if the PCB you've shown includes one. Bypass capacitors shall be as close to the chip as possible. Certainly plays a role, too. Be sure to check that.

Thanks again! For the calibration measurement I did take hundreds of readings and they were very consistent (within 1/1024). I checked VIOUT with my cheap multimeter and I got the same 2.33v and 2.48v. VCC was 4.98v. The board has a 0.1µF capacitor right next to the chip, I bought the whole board but just looked and they are.

I contacted Allegro they were really helpful which was pleasantly surprising.
The 200A has almost certainly failed. The 2.48v is within tolerance and the 2.33v is probably out.
I've been able to better understand the datasheet sections on 0A calibration. "VIOUT(Q) may drift over the lifetime of the device by as much as ±25 mV." and there is an electrical offset voltage noted. @25C it's +/-5mv. It's +/-20mv between 0c and 50c. So still only 45mv. Even allowing for noise it's only 55mv.
About 2.445V at zero amps would be the limit.

Don't you mean the 50A did fail? Glad you sorted out this issue that said :-) .

Annoyingly the 200A was the one with the perfect calibration but ......"I've then put them in a circuit drawing about 9amps. Accounting for the offset of zero amps the 50A and 100A measured the increased voltage correctly. The 200A doesn't change." .... The 200A was perfect at zero amps and stayed at 2.50v regardless of current.... completely broken.

Ouch! Rest In Pieces...


text:
I2C device responding, but data is nacked
I'm working on a project where I have to communicate to several devices over I2C using a Genuino 101. Now I'm trying to get data off the bus but wire.available() stays at 0, even though my trace clearly shows there's data being sent.

with the following timings

Because the wire is never available my readbuf will always be empty.
Rdbuf[0] is: 0 Hex is: 0
Rdbuf[1] is: 0 Hex is: 0

I'm using the following code to read from the I2C bus.
void i2cRead(unsigned char device, unsigned char memory, int len, unsigned char * rdBuf) {
  ushort memstart = memory;
  bool available = true;;
  while (len > 0 && available) {
    available = false;
    ushort blockSize;
    /*If the number of bytes is smaller than the block size, read that size*/
    (len < RD_BLCK_SIZE) ? blockSize = len : blockSize = RD_BLCK_SIZE;
    Wire.beginTransmission(static_cast<int>(device));
    //send i2c START command
    Wire.write(memory);
    //Write memory address
    Wire.endTransmission();
    //send i2c STOP command
    Wire.requestFrom(static_cast<int>(device), blockSize,true);
    //Request blockSize bytes from the device
    /* for every byte in the response add that byte to the read buffer */
    while (Wire.available() && (len != 0)) {
      available = true;
      rdBuf[memory - memstart] = Wire.read();
      memory++;
      len--;
    }
  }
}

I'm not quite sure what I'm doing wrong, any help would be much appreciated.
Edit:
Below is an image of the current (minimal) setup. On the left there's the board with the ADC and multiplexer visible.

The third set of wires goes to my protocol analyzer.

It seems that a delay(1) between Wire.endTransmission and  Wire.requestFrom is necessary for ... reasons.

Since this has been reopened i figured i'd post what the problem was, in the end and what i did to fix it.
it turns out, that even though the documentation of the Curie tells us to apply a level shifter for i2c communications, this level shifter is already in-place on the genuino 101.
skimming over the documentation of the 101, i had overlooked this.
The fix, in the end was removing the level shifter.

You want to get the resulting code working, but you should do small minimal tests.
Start with the i2c scanner.
Connect only one sensor, and if it is detected, add more sensors.
How long are the wires, and what is the value of the pullup resistors ?
Perhaps you have too many modules with sensors, and the total pullup value it too low. The I2C bus is specified for maximum 3mA pull down current.
Do you have a more common 3.3V Arduino board ? For example the Arduino Due or the Arduino Zero ?

hey jot, i have the code working on a different sensor, i2c scanner gives me all the sensors, and i can sucessfully read these sensors. the only difference here is that i have this sensor connected via a logic-level converter, converting the 3.3v signals into 5v signals.
i have an arduino uno i could test with, but this is part of a bigger project, in which we're using the bluetooth component of the 101.
the wires are all 30cm DuPont wires,  they're pulled up to 5v with 10kOhm resistors

The I2C bus is 3.3V, with a level shifter is for a 5V sensor ? Did you connect the high side (sometimes called HV) to the sensor side, and did you apply the 3.3V and the 5V to the level shifter ? Use seperate wires, not a flat ribbon cable. When SDA and SCL are next to each other in a flat ribbon cable, then they cause crosstalk. The i2c scanner detect a sensor by a ACK to its I2C address. Then you should be able to get that same ACK in a small test sketch. Perhaps the sensor has to be woken to be able to return data ? Is that a normal sensor, or a microcontroller with clock puls stretching ?

The sensor i'm currently trying to reach is a 10-bit adc, so far it's always just worked when we try to get data from it, in the packet log you can see that it responds with valid data.
i'm currently using a adafruit level shifter on a breadboard. 3.3v peripherals and the 101 on one side, and my 5v peripherals(Io expander/adc)  on the other.
currently the sda and scl are next to eachother on the breadboard, ill try with a few pins in between to see if crosstalk is the issue, a raspberry pi connected on the 5v side can talk to all the periperals, so i believe the circuit ought to be fine

A Raspberry Pi is 3.3V and it must be connected to the 3.3V side of the I2C bus. And you did apply 3.3V and 5V to the level shifter ? You really should test the problem with the absolute minimum. Remove everything that is not needed from the I2C bus and make a very small test sketch. Perhaps the timing of the Arduino 101 Wire library is in conflict the with sensor. You could, for example, add a delay of 1ms after Wire.endTransmission.

thats what i find odd, the raspberry pi works on both sides, but the genuino works on neither.
i'll do a test with the bare minimum attached tomorrow and i'll see what's going wrong. thanks for your ideas so far


text:
Can I run arduino on Windows Embedded Compact 2013?
I'm actually working on a robotic project for which I'm planning to use arduino to drive the wheels.For this, I want to send signals from my Onboard embedded computer (which has Windows Embedded Compact 2013 OS) to arduino. Is this possible? If not possible, what are the other alternatives?

I think the title of the question is misleading. When you say "Can I run arduino" it would lead people believe you're asking whether you can run the Arduino IDE (which I don't know). But later you explain that you actually only want to send signals to the Arduino. This doesn't require the Arduino and is certainly possible. If you wanted a better answer you would need to explain what sort of communication you plan to use for these signals (serial, SPI, I2C, etc.).

What OS is running on two different devices exchanging messages/signals, does not matter. What matters is the protocol.
You can use a lot of different ones:

Wireless:

IR (infrared)
RF (radio), like 433 MHz, 2.4 GHz
WIFI (internet)
Bluetooth

Wired

SPI
'simple wires' / Wire library
Serial
USB (not on most Arduinos)

This list is not complete, just some examples.
Arduino supports all above (except USB fully), I don't know what Windows Embedded Compact OS supports.

Actually, the only thing an ordinary Arduino easily supports for interaction with a typical modern PC is USB.  That will present on both ends as a serial port, but in terms of what you connect with a cable, it is USB.

strictly speaking the answer is correct, but would be clearer if it was changed to say Serial + USB Serial as the 3rd option and Native USB (not on most arduinos) as the 4th


text:
Arduino Uno SD card fails to initialize
I'm not sure why my SD card fails to initialize when I run my code (below) but works when I just check to see if it is being read by the Arduino with the CardInfo code in the Arduino library.
The data logger is from Adafruit and the sensor that I'm connecting to it is a MaxBotix one. I've tried reseting the SD card and the Arduino and switching out the SD card. When I verify the code in Arduino there are no issues, so I'm not entirely sure why this isn't working. Any help is greatly appreciated.
UPDATES:
I was able to get it to initalize the SD card by moving
if (!SD.begin(chipSelect)) {
  error("Card failed, or not present");
}

after the
Serial.println().

but now it's not saving data or even creating a new document and it's not printing data as a new line. Things went south when I added the averaging portion of the code because before then it was printing data as a new line and the SD card initializing.
My time is extremely wrong I'm getting a date like 2165/165/165 165:165:85.
1
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include "RTClib.h"
/*
The goal of this code is to collect 10 data points a minute, average them, and store them to an SD card
*/
#define LOG_INTERVAL 6000 // mills between entries (reduce to take more/faster data)
// how many milliseconds before writing the logged data permanently to disk
// set it to the LOG_INTERVAL to write each time (safest)
// set it to 10*LOG_INTERVAL to write all data every 10 datareads, you could lose up to
// the last 10 reads if power is lost but it uses less power and is much faster!
#define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
uint32_t syncTime = 0; // time of last sync()

#define ECHO_TO_SERIAL   1 // echo data to serial port
#define WAIT_TO_START    0// Wait for serial input in setup()
RTC_DS1307 RTC; // define the Real Time Clock object
// The analog pin that connect to the sensor
const int ultrasonicPin = A0; // declare the input pin for the ultrasonic sensor
unsigned long time;
// for the data logging shield, we use digital pin 10 for the SD cs line
const int chipSelect = 10;
const int numReadings = 10; //define number of samples to keep track of
int readings[numReadings]; //the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average
// the logging file
File logfile;

void error(char *str) {
  Serial.print("error: ");
  Serial.println(str);
  // red LED indicates error
  //digitalWrite(redLEDpin, HIGH);
  while(1);
}

void setup() {
  Serial.begin(9600);
  Serial.println();
  //initialize all the readings to 0:
  for(int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
    #if WAIT_TO_START
      Serial.println("Type any character to start");
      while (!Serial.available());
    #endif //WAIT_TO_START
    // initialize the SD card
    Serial.print("Initializing SD card...");
    // make sure that the default chip select pin is set to
    // output, even if you don't use it:
    pinMode(10, OUTPUT);
    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
      error("Card failed, or not present");
    }
    Serial.println("card initialized.");
    // create a new file
    char filename[] = "LOGGER00.CSV";
    for (uint8_t i = 0; i < 100; i++) {
      filename[6] = i/10 + '0';
      filename[7] = i%10 + '0';
      if (! SD.exists(filename)) {
        // only open a new file if it doesn't exist
        logfile = SD.open(filename, FILE_WRITE);
        break;  // leave the loop!
      }
    }
    if (!logfile) {
      error("couldnt create file");
    }
    Serial.print("Logging to: ");
    Serial.println(filename);
    // connect to RTC
    Wire.begin();
    if (!RTC.begin()) {
      logfile.println("RTC failed");
      #if ECHO_TO_SERIAL
        Serial.println("RTC failed");
      #endif  //ECHO_TO_SERIAL
    }
    logfile.println("millis,stamp,datetime,depth");
    #if ECHO_TO_SERIAL
      Serial.println("millis,stamp,datetime,depth");
    #endif //ECHO_TO_SERIAL
    // If you want to set the aref to something other than 5v
    analogReference(EXTERNAL);
  }
}

void loop() {
  DateTime now;
  // delay for the amount of time we want between readings
  delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL));
  // log milliseconds since starting
  uint32_t m = millis();
  logfile.print(m); // milliseconds since start
  logfile.print(", ");
  #if ECHO_TO_SERIAL
    Serial.print(m); // milliseconds since start
    Serial.print(", ");
  #endif
  // fetch the time
  now = RTC.now();
  // log time
  logfile.print(now.unixtime()); // seconds since 1/1/1970
  logfile.print(", ");
  logfile.print('"');
  logfile.print(now.year(), DEC);
  logfile.print("/");
  logfile.print(now.month(), DEC);
  logfile.print("/");
  logfile.print(now.day(), DEC);
  logfile.print(" ");
  logfile.print(now.hour(), DEC);
  logfile.print(":");
  logfile.print(now.minute(), DEC);
  logfile.print(":");
  logfile.print(now.second(), DEC);
  logfile.print('"');
  #if ECHO_TO_SERIAL
    Serial.print(now.unixtime()); // seconds since 1/1/1970
    Serial.print(", ");
    Serial.print('"');
    Serial.print(now.year(), DEC);
    Serial.print("/");
    Serial.print(now.month(), DEC);
    Serial.print("/");
    Serial.print(now.day(), DEC);
    Serial.print(" ");
    Serial.print(now.hour(), DEC);
    Serial.print(":");
    Serial.print(now.minute(), DEC);
    Serial.print(":");
    Serial.print(now.second(), DEC);
    Serial.print('"');
  #endif //ECHO_TO_SERIAL
  analogRead(ultrasonicPin);
  delay(10);
  int value = analogRead(ultrasonicPin);
  for (int i=0; i < 50; i++) {
    if (millis() < 60000*(++i)) {
      // subtract the last reading:
      total = total - readings[readIndex];
      //read from the sensor:
      readings[readIndex] = analogRead(ultrasonicPin);
      // add the reading to the total:
      total = total + readings[readIndex];
      //advance to the next position in the array:
      readIndex = readIndex + 1;
      //if we're at the end of the array
      if (readIndex >= numReadings) {
        //wrap around to the beginning:
        readIndex = 0;
      }
      //calculate the average:
      average = total / numReadings;
      delay(6000);
    } else if (millis() == 60000*(++i)) {
      logfile.print(",");
      logfile.print(average);
      Serial.print("Ultrasonic Reading = ");
      Serial.println(average);
      //Serial.print("Time: ");
      //time = millis();
      //prints time since program started
      //Serial.println(time);
      //wait a second so as not to send massive amounts of data
      // Now we write data to disk! Don't sync too often - requires 2048 bytes of I/O to SD card
      // which uses a bunch of power and takes time
      if ((millis() - syncTime) < SYNC_INTERVAL) return;
      syncTime = millis();
      delay(100);
    }
  }
}
// this reads in cm

You cannot initialize the SD card more than once.  Pull this code out of the for loop:
if (!SD.begin(chipSelect)) {
  error("Card failed, or not present");
}

Put it after the Serial.println().

Make a new sketch that initialize the SD Card and write data to it, without loop.
If this doesn't works,maybe the sdcard is damage.
So, as shash-dev says,initialize the SD card before you start the for cicle and after the Serial.printl().


text:
Arduino with HC 08 bluetooth module
I am connecting Arduino Uno R3 with HC 08 module lie following
Arduino 5v -> HC 08 Vcc
Arduino gnd -> HC 08 gnd
Arduino Pin 5 -> HC 08 RXD
Arduino Pin 6 -> HC 08 TXD

Then I connected two LEDs to 9 and 10 pins
Then loading following sketch.
#include <SoftwareSerial.h>

int availableLEDpin = 9;
int notAvailableLEDpin = 10;
SoftwareSerial hc_08(5, 6); // RX-5, TX-6
void setup() {
  pinMode(availableLEDpin, OUTPUT);
  pinMode(notAvailableLEDpin, OUTPUT);
  Serial.begin(9600);
  hc_08.begin(9600);

}

void loop() {
  hc_08.listen();
  if (hc_08.available()) {
    Serial.println(hc_08.read());
    digitalWrite(availableLEDpin, HIGH);
    digitalWrite(notAvailableLEDpin, LOW);

  }
  else {
    digitalWrite(availableLEDpin, LOW);
    digitalWrite(notAvailableLEDpin, HIGH);
  }
  delay(100);
}

I am trying to connect to bluetooth from y iOS application. The application is searching and connecting to the HC 08 correctly. And sending data successfully - Swift code log showing sent successfully.
But back in Arduino, always led connected to pin notAvailableLEDpin is glowing and nothing is printing in serial monitor. What is wrong with my implementation?

You have the receive port on your arduino connected to the receive port on your bluetooth module. Connect pin 5 to the Tx on your module and connect pin 6 to the Rx on your module.

it's better to use digital pin 8/10 as RX, digital pin 9/11 and TX as your softwareserial pins since these pins are dedicated for softwareserial knowing you use the generic softwareserial library and mind your supply to only use 3v3 volts as much as possible, specially for the TX softwareserial pin of your arduino going to RX pin of HC08, you need to lessen the voltage output of that arduino pin into 3v3 volt also, using voltage divider. It will harm your HC08 module and might not work properly.


text:
Sending Analog Input Data from Serial Port to Google Sheets
So I'm trying to make use of my Arduino Uno while I purchase the components for my next project.
I've made use of the Digital Hourglass project from the Starter Kit to make sure I get up and move around every 20 minutes while I'm at home. A temperature sensor was included in the Starter Kit as well, so I figured I might as well make use of it since I have extra I/O pins.
I wrote the code for in the Arduino IDE to display the temperature and the current time. I'm using: #include (Time.h) to also show the current time. I have two questions.
End Goal:
A Google spreadsheet (Cloud) that I can access anywhere that can show me the temperature of my apartment throughout the day. I can track how the trend changes over time through the day, week, or month.

What is the best way to output the current time; as seconds since 1970 (Unix time) or date and time format? I guess it's a preference.
How do I output the data from the Arduino serial port directly to Google Sheets? That may be difficult, so the other option is to energize the Arduino in the morning and remove power at the end of the day, output the Serial port to a .txt file, and then import into Google sheets. How do I do this?

Really interesting question. Try this website out for starters.

Use Google's time stamp format: MM-dd-yyyy hh:mm:ss, see Google Sheets API v4 - Date and Number Formats.
There are a few ways. For example:

A PC connected to the Internet with software on it that listens for data form the Arduino. It would get the Arduino data over serial then send that via the Internet to Google.
A Wi-Fi, or network, shield connected to the Internet. You could then use Google's API to send the data directly from the Arduino, see Google Sheets API v4 - Writing.
Or - as you mentioned - physically get the SD card and manually upload.

The first one is the idea. I'm leaving the Arduino connected to my laptop throughout the day while I'm gone. It shouldn't be that hard to edit the script to at least send that data from being transmitted from the Arduino to a .txt document. Maybe I haven't done enough digging into the Arduino Playground. This should be able to work with any analog sensor.

I'd use an ESP8266 and IFTTT.
https://ifttt.com/maker_webhooks
https://ifttt.com/google_drive
You could write something on your PC that took the serial output from the Aurdino and posts a REST message to IFTTT.

Yes, I recently ordered the Sparkfun Photon kit for a lot of IoT training. This project that I posted about in particular is not meant to be an IoT project. It's meant to learn how to simply document data for later processing using the serial connection. Thank you though!

Wouldn't it be great if the data from Arduino obtained via serial port could be inserted directly at a local google spreadsheet url, without using any api nor post requests?
As far as I know, Google Spreadsheets can be updated (by a human) in the local machine even without internet.
What would be the benefit?
If eventually internet goes offline for several hours, no arduino data would be lost.
In the good working solutions provided, internet is always mandatory, if I see correct. No internet? Lost data. It seems to me.
But I really don't know if a script can get serial data from Arduino and then update an existing google spreadsheet url, as a human would do (typing a new row).
An autoit or autohotkey script would do on Windows machines by simulating mouse clicks and typing, but it must exist more beautiful solutions.
A solution like this would accumulate data with or without internet and, as soon as internet returns, all data would be updated to the cloud. If I see correct. (I am sorry if I made any mistake).

I guess I have a not so bad solution: save all data to a txt file. Then, periodically, try to update all data to a google spreadsheet using Sheets API or any internet-dependent way (Web App, etc).
In this case, if there's no internet, data still accumulates at a txt file. When internet returns, no data would had been lost.


text:
Understanding bitwise operations
I am wondering what the second line of code does:
int16_t GyX;
GyX=Wire.read()<<8|Wire.read();

Also, how can I write the GyX value to EEPROM?
From what I understand, int16_t is a two-bytes value. The Wire.read() returns a single byte. The <<8 shifts the bits by one byte to the left in order to read the higher order bits, and the last part writes the next wire read (lower order bits). Basically, reads wire twice and stores those values in the int. Is that correct?
For the writing, would
EEPROM.write(addr, GyX >> 8);
EEPROM.write(addr, GyX & 0xff);

do the trick? (First line records the higher order bits, while second records the lower order ones)

@PetioPetrov, Arduino has macros to make it easier: highByte, lowByte, and word.
You don't have to split and combine bytes and words. The EEPROM.put and EEPROM.get can write and read two bytes if you want to. It's all documented in the reference of EEPROM.
There is a lot going on in this piece of code:
int16_t GyX;
GyX=Wire.read()<<8|Wire.read();

Shifting a single byte 8 bits to the left would be wrong. However, the Wire.read returns an integer and the GyX is an integer. Therefor the compiler uses integers for everything and shifting 8 bits to the left is valid.
At this moment with the current Arduino and avr-gcc compiler version, it will call the Wire.read for the high byte first and then the Wire.read for the low byte. That is pure luck as @EdgarBonet has corrected me below. In the c++ language there is no specified order of calling functions.
The bitwise 'OR' with the '|' could be a problem when there was no data and -1 was returned by Wire.read.

“Even with the most extreme optimizations, the order is in this situation still from left to right”. No. The order is unspecified. See Order of evaluation in C++.

@EdgarBonet, Thanks for the correction. I thought that when a call was made to the same function, it would always work. But the C++ language explicitly has defined that there is no specified order. I will try to remember that.

GyX=Wire.read()<<8|Wire.read();

This is a bug. It reads two bytes from the I2C bus and builds a 16-bit
number from them. One of the bytes (we don't know which one) will be the
most significant byte of the result. The other byte will be the least
significant byte.
This instruction is likely to work just fine on some particular version
of some particular compiler with some particular compiler options.
Presumably it did work for the author. But you should not expect it to
work consistently across compilers, or even across different versions of
the same compiler.
The proper way to do this is to perform the two reads in different
instructions:
GyX = (uint16_t) Wire.read() << 8;
GyX |= Wire.read();

assuming the bytes come most-significant first.
Edit: added (uint16_t) cast. C.f. this answer.


text:
Confusion receiving I2C data from magnetic sensor
So, I've found the address of my device using a I2C device scanner. I then looked up the datasheet for a magnetic sensor I am trying to grab data from.
I'm now trying to communicate with the device by following the 'Example Measurement' section in the data sheet.
Here is my code so far...
#include <Wire.h>
#define address 0b110000 // find the actual address, it is at 0x30, which is 0b00110000

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

void loop() {
  int x, y, z;

  Wire.requestFrom(0b00110000, 1); // START condition?, starts with a 0 to indicate a WRITE request
  if(Wire.available() > 0) {
    Serial.println("1");
    Wire.read();
  }
  Serial.println(Wire.read());
  Wire.write(0b00000111);
  if(Wire.available() > 0) {
    Serial.println("2");
    Wire.read();
  }
  Wire.write(0b00000001);
  if(Wire.available() > 0) {
    Serial.println("3");
    Wire.read();
  }
  Wire.requestFrom(0b00110000, 1); // write request
  if(Wire.available() > 0) {
    Serial.println("4");
    Wire.read();
  }
  Wire.write(0b00000110);
  if(Wire.available() > 0) {
    Serial.println("5");
    Wire.read();
  }
  Wire.requestFrom(0b10110000, 1); // READ request
  if(Wire.available() > 0) {
    Serial.println("6");
    Wire.read();
  }
  // not sure what to do for the 7th cycle???
  // am I even doing the previous correct?
  Wire.endTransmission(address);
  delay(1000);
}

The numbers in each of the if statements represent the cycle within the 'Example Measurement' section of the datasheet, I'm never able to read data from the device and I am sure that I am doing something wrong.
I appreciate any help! This is my first time ever trying to understand I2C, and I've just been staring at this datasheet for too long without getting anywhere.

The Wire.request does not need beginTransmission or endTransmission. Only the Wire.request is needed when data needs to be read. You can use one or more Wire.read or Wire.available if you like. To write data, you need Wire.beginTransmission, Wire.write (none, one, or more) and Wire.endTransmission. You request data from different i2c addresses. Please use: const int mmc3416Address = 0x30;

What is the difference between reading data and requesting data? It seems to me that the Wire.read() depends on which address was called to Wire.begin() whereas Wire.request() takes in an address of the device? Is this correct?

No, sorry, that is not correct. You need to learn about using the Wire library. Start here: https://www.arduino.cc/en/Reference/Wire I think you are confused with a serial port. The I2C functions are similar to the functions of a serial port, but it is not the same, since the I2C uses packets of data, and not a stream of data. The I2C can not read and write at the same time. Either a packet of data is transmitted to a sensor or a packet of data is requested from a sensor.

I have read the datasheet, and it is very confusing, even for me. The Wire library does all the start and stop and handles the acknowledge and set the read/write bit if needed. You don't have to worry about that. When communicating with the sensor, sometimes a delay is needed. The delay is the only odd thing, the sensor is just like any other I2C sensor.

I've never messed with any I2C protocols before, so if the Wire library takes care of all the start and stop and handling acknowledge for me, what exactly do I need to do? It seems like I would be in charge of writing particular bits, as described in the example measurement section. Also, which functions in the Wire library take care of the start and stop stuff for me? Thanks for your responses!

As I wrote before, start here: https://www.arduino.cc/en/Reference/Wire Read on the right what the functions do, and then have a look at a few examples.

@dchin2. I2C is one-device-a-time type of bus. requestFrom means that the master end transmitting and now slave must send its data.

This is how you send a byte to your slave:
  Wire.beginTransmission(SLAVE_ADDRESS);
  Wire.write(someByteValue);
  Wire.endTransmission();

You must sandwich the writes between a beginTransmission/endTransmission. Output buffer is 32 bytes long, so keep things short.
Wire.write() doesn't write; just put thing in an output buffer, waiting for your endTransmission().
If you need an answer (said, a byte), first you said how many bytes you want and then read them:
  byte pin;
  Wire.requestFrom(SLAVE_ADDRESS, 1);
  if (Wire.available() == 1) {
    pin = Wire.read();
  }

Your are Wire.read()ing, but you are not capturing the return value!
Disclaimer: after requestFrom, you have to be prepared to wait for the data (it may be not inmediatly available). Also, data may arrive in chunks.

After Wire.requestFrom, the received data is in a buffer in the Wire library. The Wire.available returns the number of bytes in the buffer. The Wire.read reads a byte from that buffer. There is never any need to wait for data after Wire.requestFrom.

@Jot. The slave can take a while to send the answer; it's not always immediatly available. According to docs, requestFrom is "Used by the master to request bytes from a slave device. The bytes may then be retrieved with the available() and read() functions."

could you look into that, or ask anyone who knows the Wire library. It is a common made mistake. The documentation is confusing, it should read: "The bytes may be retrieved from the receive buffer with available() and read()". The Wire.requestFrom does a START, puts the address with read bit, can do clock pulse stretching if requested by the Slave, reads bytes, stores bytes in a buffer, gives ACK after each byte, with a NAK at the last byte, and finally a STOP. Only then the Wire.requestFrom returns. There is really no other way. When Wire.requestFrom returns, all the data is ready.

@jot. It is not clear to me that requestFrom is blocking. It seems to be blocking. I don't think it is a good idea, because blocking calls means a frozen program under Murphy's Law. Sad!

Sadly it is blocking. The Wire library is interrupt driven, but because it is blocking it is not faster than it would be with polling for the Master mode. It is even worse, when SDA or SCL is shortcut to GND, some Wire library functions never return and the sketch stops working. The Teensy has a Wire library with extra non-blocking functions.

For most Arduino users, the blocking interface is best, however, they really should provide a timeout and error condition.  Without that, one solitary single glitch can leave the sketch hung until reset.  That said, horrible documentation of APIs has been a persistent problem with the Arduino website; they try to simplify things so much that to find an actual answer to a critical detail that any serious library would put in the documentation, you often have to dig into the source code.