message:
Could you tell me what is wrong with this Arduino code?

void fn( int pin, int pos)
    {
        Servo temp;
        temp.attach(pin);
        temp.write(pos);
        delay(15);
        temp.detach();
    }

    void loop()
    {
        int pos = 0 ;
        for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
            // in steps of 1 degree
            //tmp2.write(pos);
            //delay(15);
            fn(41,pos);
            fn(2,180 - pos);
        }
        for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
            fn(41,pos);
            fn(2,180 - pos);
        }
    }

But when I run the code in mega , the servo does not move when attached to pin 2 or 41.
The reason I am creating a function fn , is so that the servo does not stay attached. I want the servo to rotate freely when I am not giving it a pwm signal.

body:
Arrange your code like this:

    Servo servo1, servo2;

    void setup() {
        servo1.attach(41);
        servo2.attach(2);
    }

    void loop()
    {
        int pos;

        for (pos = 0; pos <= 180; pos++) {
            servo1.write(pos);
            delay(15);
            servo2.write(180 - pos);
            delay(15);
        }

        // 2nd loop here

    }

It's rather inefficient to detach a servo after each write and then attach it again for the next write. Simply keep it up all the time.


sender: user

message:
How to wire an analog IR sensor for digital input?

How do you wire a phototransistor so that it outputs a clean digital signal in response to certain light levels?

I've wired a [QRD1114][1] to an Arduino analog pin to detect a white or black surface. However, I want to use this sensor to detect fast movement of a black/white color strip, and since `analogRead()` can [take up to 100µs][2] and I'd rather use the ADC pin for other sensors, I want to rewire this so I can read the same signal with `digitalRead()`.

In order to do this, the sensor needs to output less than 2.3V for white and more than 2.5V for black. I'm pretty close, but I'm having trouble with black. For white, the voltage drops to 0.7V, so that reads perfectly, but black still reflects a lot of IR, so it typically reads 2.3V, which still translates as a LOW value.

My sensor's circuit is a pretty basic voltage divider:

[![enter image description here][3]][3]

R1 is the Arduino's built-in 20k pullup. R2 is a variable resistor I've tried using to "shift" the voltage level up for the black case. Unfortunately, I've found this very difficult to calibrate. The larger I make R2, the higher the black-case voltage gets...but so does the white-case voltage. By the time I make R2 large enough so that black registers as HIGH, white also registers as high. Through trial and error, I found 25.7k ohms is the sweet spot, but the difference in voltage between the two is about 0.5V, which makes me nervous about getting false readings.

I've measured the phototransistor's resistance in each case, and for black it reads as 12.5k ohms while for white it reads as 9.7k ohms.

Given my 25.7k calibration resistance, the voltage divider should output for black:

    Vout = Vin * R2/(R1 + R2)

    5 * (12500+25700)/(20000 + 12500+25700) = 3.2V

and for white:

    5 * (9700+25700)/(20000 + 9700+25700) = 3.1V

However, for black, my meter reads 2.3V for black and 2.0V for white.

Why do my meter measurements not match the voltage divider formula? Am I wiring this voltage divider correctly?

What can I do to get a cleaner digital output without complicating the circuit too much?

  [1]: https://www.fairchildsemi.com/datasheets/QR/QRD1114.pdf
  [2]: https://www.arduino.cc/en/Reference/AnalogRead
  [3]: https://i.stack.imgur.com/0f3nN.png

sender: assistant

body: First if you just want a faster analog read look at this article(http://www.microsmart.co.za/technical/2014/03/01/advanced-arduino-adc/). Second is that your approach to determining resistor values is incorrect. The sensor acts as a phototransistor so it passes different amount of current, upto 1 mA. so you only need a single resistor and the sensor to make an analog output. If you really want to digital read you can use an op amp as a voltage comparator.


body:
Near the bottom of:

https://learn.sparkfun.com/tutorials/qrd1114-optical-detector-hookup-guide

shows a graph of the voltage for a white surface and a black surface. If I understand your question correctly, I think you can get your desired results by controlling the distance between the sensor and the surface. For example, at 0.5mm white reads about 0.1V while black reads about 3.2V

A 330Ω current-limiting resistor and a 10kΩ pull-up resistor were used in their circuit.

Hope this helps.


message:
embedXcode: Link Error using an Arduino library (Servo.h) within a header file

For [various reasons][1], I am moving from the Arduino IDE to Xcode using the embedXcode plugin. The code in question compiles and uploads fine from the Arduino IDE, so I think the issue is related to library definitions in embedXcode. The board I am using is an Arduino Mega 2560 (actually it is a [Freetronics EtherMega][2]).

The error thrown is:

    Command /Applications/Xcode.app/Contents/Developer/usr/bin/make failed with exit code 2

More specifically:

        5.3-LINK                 Builds/embeddedcomputing.elf

    /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++ -o Builds/embeddedcomputing.elf Builds/main.cpp.o Builds/embeddedcomputing.a -Os -w -mmcu=atmega2560 -Wl,--gc-sections  -LBuilds -lm
    Builds/main.cpp.o: In function `Robot::Robot()':
    main.cpp:(.text._ZN5RobotC2Ev[Robot::Robot()]+0x5e): undefined reference to `Servo::Servo()'
    Builds/main.cpp.o: In function `Robot::begin()':
    main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0x5a): undefined reference to `Servo::attach(int)'
    main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0x64): undefined reference to `Servo::write(int)'
    main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0xea): undefined reference to `Servo::write(int)'
    main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0x112): undefined reference to `Servo::write(int)'
    main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0x132): undefined reference to `Servo::write(int)'
    Builds/embeddedcomputing.a(HB25MotorControl.cpp.o): In function `HB25MotorControl::HB25MotorControl(unsigned char)':
    HB25MotorControl.cpp:(.text._ZN16HB25MotorControlC2Eh+0x14): undefined reference to `Servo::Servo()'
    Builds/embeddedcomputing.a(HB25MotorControl.cpp.o): In function `HB25MotorControl::begin()':
    HB25MotorControl.cpp:(.text._ZN16HB25MotorControl5beginEv+0x42): undefined reference to `Servo::attach(int, int, int)'
    HB25MotorControl.cpp:(.text._ZN16HB25MotorControl5beginEv+0x58): undefined reference to `Servo::writeMicroseconds(int)'
    Builds/embeddedcomputing.a(HB25MotorControl.cpp.o): In function `HB25MotorControl::stop()':
    HB25MotorControl.cpp:(.text._ZN16HB25MotorControl4stopEv+0x12): undefined reference to `Servo::writeMicroseconds(int)'
    Builds/embeddedcomputing.a(HB25MotorControl.cpp.o): In function `HB25MotorControl::moveAtSpeed(int)':
    HB25MotorControl.cpp:(.text._ZN16HB25MotorControl11moveAtSpeedEi+0x44): undefined reference to `Servo::writeMicroseconds(int)'
    collect2: error: ld returned 1 exit status
    make: *** [Builds/embeddedcomputing.elf] Error 1
    Command /Applications/Xcode.app/Contents/Developer/usr/bin/make failed with exit code 2

Robot.h contains a robot class which defines a Servo (for a turret) and two HB-25 MotorControl objects (which control the drive motors). The [HB25MotorControl is a custom library][3] that I have written for the Parallax HB-25 Motor Controller. It also uses the Servo library.

To answer the obvious questions:

 1. Yes I have `#include <Servo.h>` in my HB25MotorControl library. You
    can see the library code by following the link above. It is also
    included in the main sketch.
 2. I have compiled, linked and uploaded other sketches which use Arduino and custom libraries in Xcode using the embedXcode plugin.
 3. My embedXcode Makefile definitions include
        the Servo library and the HB25MotorControl library. See extract
        below.

APP_LIBS_LIST = Wire Servo SoftwareSerial

USER_LIBS_LIST = NewPing Time DS3232RTC HB25MotorControl

Any suggestions on how to fix this error and get my code to build in Xcode would be greatly appreciated.

  [1]: http://reefwingrobotics.blogspot.com.au/2015/12/moving-to-embedxcode.html
  [2]: http://www.freetronics.com.au/products/ethermega-arduino-mega-2560-compatible-with-onboard-ethernet#.VnzZ7pN95Zo
  [3]: http://reefwingrobotics.blogspot.com.au/2015/12/parallax-hb-25-motor-control-library.html

body:
I ended up contacting the developer of the embedXcode plugin. He was very helpful and provided the fix within a day. The cause of the issue is apparently the Arduino IDE has changed its library structure in the latest release.

The next version of embedXcode (release 4.1.4.) will include a fix for this, however if you can't wait until then you need to open ArduinoAVR_165.mk (located in the Makefiles group in Xcode) in your project and add the following line:

    avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/$(BUILD_CORE),$(APP_LIBS_LIST)))

After you add this line, the file should look like this:

    # Two locations for Arduino libraries
    #
    APP_LIB_PATH = $(APPLICATION_PATH)/libraries
    APP_LIB_PATH += $(APPLICATION_PATH)/hardware/arduino/$(BUILD_CORE)/libraries

    avr165_20 = $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%,$(APP_LIBS_LIST)))
    avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/utility,$(APP_LIBS_LIST)))
    avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src,$(APP_LIBS_LIST)))
    avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/utility,$(APP_LIBS_LIST)))
    avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/$(BUILD_CORE),$(APP_LIBS_LIST)))
    avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/arch/$(BUILD_CORE),$(APP_LIBS_LIST)))

Note that each project has its own ArduinoAVR_165.mk file, so you will have to make this change in each project until you update to the new release.


message:
Class is not tracking changes to a private field

I have a program where a device registers itself with a command object. The command object is losing track of the registrations. The following program repeats "0 devices registered" even though when it initializes it displays "Devices registered 1". My guess is that I am accidentally creating 2 copies of the command object.
This is the main sketch

    #include "command.h"
    #include "widget.h"

    Command command;
    Widget widget;
    void setup() {
      command.init();
      widget.init(command);
    }

    void loop() {
      command.update();
    }

command.h

    #include "Arduino.h"

    #ifndef Command_h
    #define Command_h

    typedef struct  {
      char id;
      char name[20];
    } Device;

    class Command
    {
      public:
        Command();
        void init();
        void registerDevice(Device _cmd);
        void update();
      private:
        Device Devices[20];
        byte DevicesPtr = 0;
    };

    #endif

command.cpp

    #include <Arduino.h>
    #include "command.h"

    #define DEVICES_MAX 9

    Command::Command() {
      DevicesPtr = 0;
      Device Devices[DEVICES_MAX];
    }

    void Command::init() {
      Serial.begin(9600);
    }

    void Command::update(){
      Serial.print( DevicesPtr );
      Serial.println( " devices registered" );
      delay(500);
    }
    void Command::registerDevice(Device _cmd) {
      _cmd.id = '0' + (++DevicesPtr);
      Devices[DevicesPtr] = _cmd;
      Serial.print("Devices registered ");
      Serial.println(DevicesPtr);
    }

widget.h

    #include "Arduino.h"
    #include "command.h"

    class Widget
    {
      public:
        static void init(Command _command);

      private:
    };

widget.cpp

    #include "widget.h"
    #include "command.h"

    void Widget::init(Command _command) {
      Device device;
      strcpy(device.name, "Widget #1");
      _command.registerDevice(device);
    }

body:
It is all about calling conventions and argument binding. The code is using call-by-value when it should be call-by-reference.

This is call-by-value (the incoming command is not updated, a copy is passed as parameter):

    void Widget::init(Command _command)
    ...
    widget.init(command);

This is call-by-reference (a pointer to command is passed as parameter):

    void Widget::init(Command* _command)
    {
       __command->registerDevice(...);
    }
    ...
    widget.init(&command);

Alternative syntax is:

    void Widget::init(Command& _command)
    {
       _command.registerDevice(...);
    }
    ...
    widget.init(command)

Cheers!


message:
avrdude: stk500_recv(): programmer is not responding + avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x47

So I'm following a beginners arduino book and I made a blinking program and now I've coded another program but when I try to upload it, avrdude(whatever that is) gives me the errors in the title and repeats them 10 times.
I have tried this so far:

 - Restarting my windows 8
 - Pressing the reset button on my arduino uno R3

My guess is that since it worked the first time, my blinking program must be clogging up the space in my arduino.How can I fix this problem. Or if my guess is right, how can I get the blinking program out of arduino and go home to my bots folder?

My IDE is arduino 1.6.7 and my port is CPU1. and lots of people mention tools>serial port but there isn't a "serial port" button on my IDE.

body:
Just search a little bit around Google.

A simple solution is pressing the restart button after the program is compiled, then, upload it.

Or restart the Arduino while the Arduino is uploading the program.

If the problem remains, try to **[burn again the bootloader of your arduino.][1]**

  [1]: https://www.arduino.cc/en/Hacking/Bootloaderhttps://www.arduino.cc/en/Hacking/Bootloader?from=Tutorial.Bootloader


body:
I had the same exact problem and fixed it, just by molding the two reset pins on the arduino together. Just check if they are properly connected as the error probably is caused by that.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/jF6TI.png

If that doesn't work, check the LEDs on the board. When you are uploading a sketch both RX and TX should be lightning up.


body:
You're probably trying to connect through the wrong port.

I had this problem due to the mac suddenly making the /dev/cu.USB port option unavailable for selection through the arduino software interface under tools/port, and then not knowing what I was doing I just tried to connect through the wrong port and got this error.

After rebooted the mac, voila the /dev/cu.USB port option was suddenly available again under tools/port, we selected it and were able to successfully upload again.

I don't know why the mac or arduino software does this, my sense is that  something must get confused during upload sometimes, especially if you disconnect and reconnect the usb for some reasons, or turn on the 9v power on the arduino board while uploading.


message:
Arduino not working / not uploading

Could anybody please help me with my problem? My Arduino doesn't work correctly. I was between a project, and suddenly it started acting weird. First, it started taking about 4 minutes to compile and a minute to upload, I do not know why!

Second, now it doesn't accept any code at all. I will paste the error message below.

Also, could anything be damaged as I inserted the USB cable of the Arduino to my power bank, rated 5V 2A, for about 30 seconds as power source and then again inserted it to the computer itself.

Please help me. I have already tried searching on various forums, reinstalling the software and driver on my PC, pressing the reset button... No help so far.

> ERROR MESSAGE:
Arduino: 1.6.7 (Windows 10), Board: "Arduino/Genuino Uno"

>avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

>System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

    Using Port                    : COM6
    Using Programmer              : arduino
    Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x49
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x49
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x49
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x49
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x49
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x49
    Error opening serial port 'COM6'. (Port busy)
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x49
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x49
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x49
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x49

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

body:
Connecting to the 5v/2A power supply would cause no trouble at all. Taking 4 minutes to compile is strange but unlikely to be related to the Arduino board. "programmer is not responding" errors are communication errors.

 - Did the program compile without errors?
 - Are any LEDs lit or blinking on your board?
 - Is the correct board selected in the Tools | Boards menu?
 - Is the correct port selected in the Tools | Ports menu?
 - Is the correct programmer selected in the Tools | Programmer menu?
 - Try another USB cable.
 - Try pressing/releasing the board's reset button right after you click the upload button.


body: I am getting the same exact errors.  Tried different boards, cables, upgrade to 1.6.7, etc.  Maybe will go back to pre1.6 and try.  Will also try via tinyisp when I get a chance.  FYI - having no issues with studio 6/tinyusb/avrdude combination, just on arduino.  Wonder if it is a USB driver or arduino version of avrdude problem?


message:
Where am I supposed to get an I2C BUFFER_LENGTH defined?

I am using a BLE nano - as soon as I try to include I2Cdev.h and compile, I get this error:

    Arduino\libraries\I2Cdev\I2Cdev.cpp:276:62: error: 'BUFFER_LENGTH' was not declared in this scope

How should I fix this? I imagine I can hard-code it in and guess around as to the value (32 seems common), but I think I am missing something else as far as it using the right libraries for the hardware, so how can I check/fix that if it is indeed the case?

body:
BUFFER_LENGTH is set in [I2Cdev.h][1] depending on the target. BLE nano is not directly supported (what I can see).

Cheers!

  [1]: https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/I2Cdev/I2Cdev.h


message:
Capacitive "keys" press event registration issues

Seeing as this is my first post I would like to thank everyone ahead who take their time to delve into my whimsical code, whoever you may be, be merciful ;)

For one of my uni projects, I would like to make a physical interface that can be operated via touch "keys" that rely on the human capacitance effect. I have relentlessly researched it (as much as feasible in my time as a student for this project) and even created a working prototype with 4 unique keys.

As you will see in my code below, I am using the capacitiveSensor.h library, which I could unfortunately not find much documentation about other than a few videos and tutorials that build upon it.

I tried deciphering the workings of it by looking at its code to see if I can manipulate it for my own biddings but quickly realized it is beyond my skill to understand.

The problem I am facing right now is that while the touch keys work, they trigger each other because of the capacitance build up when one of the keys is being pressed or when the hand is close to other keys while pressing a key.

Essentially, I am looking for an algorithm that will reduce processing time & effort for the Arduino as the one I have implemented below slows it down way too much to be of any use for my project.

Sorry for the long post, here is my current code:

    #include < CapacitiveSensor.h >
    #include < pitches.h >

    CapacitiveSensor cs_4_2 = CapacitiveSensor(4, 2); // 10M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
    CapacitiveSensor cs_4_3 = CapacitiveSensor(4, 3); // 10M resistor between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil
    CapacitiveSensor cs_4_5 = CapacitiveSensor(4, 5); // 10M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
    CapacitiveSensor cs_4_6 = CapacitiveSensor(4, 6);

    # define COMMON_PIN 4 // send pin
    # define CAP_THRESHOLD 450 // overall threshold
    # define NUM_OF_KEYS 4 // Number of keys that are on the keyboard
    # define noteDur 50 // duration of note
    # define BUZZER_PIN 12 // The output pin for the piezo buzzer
    # define noMulti 0.9 // incremental factor per key
    # define overkill 5 // register no touch after this cap factor is exceeded

    // This macro creates a capacitance "key" sensor object for each key on the piano keyboard:
    # define CS(Y) CapacitiveSensor(COMMON_PIN, Y)

    CapacitiveSensor keys[] = {
    CS(2), CS(3), CS(5), CS(6)
    };

    void setup() {

    Serial.begin(57600);

    // Turn off autocalibrate on all channels:
    for (int i = 0; i < NUM_OF_KEYS; ++i) {
    keys[i].set_CS_AutocaL_Millis(0xFFFFFFFF);
    }

    }

    void loop() {

    // needs to be repeated here to work in THIS scope
    long sensor01 = cs_4_2.capacitiveSensor(30); // pin 2 is cap sensor, pin 4 is "common send"
    long sensor02 = cs_4_3.capacitiveSensor(30);
    long sensor03 = cs_4_5.capacitiveSensor(30);
    long sensor04 = cs_4_6.capacitiveSensor(30);

    Serial.println("");
    Serial.print("key1");
    Serial.print("\t");
    Serial.print("key2");
    Serial.print("\t");
    Serial.print("key3");
    Serial.print("\t");
    Serial.print("key4");
    Serial.println("");
    Serial.print(keys[0].capacitiveSensor(CAP_THRESHOLD));
    Serial.print("\t");
    Serial.print(keys[1].capacitiveSensor(CAP_THRESHOLD));
    Serial.print("\t");
    Serial.print(keys[2].capacitiveSensor(CAP_THRESHOLD));
    Serial.print("\t");
    Serial.print(keys[3].capacitiveSensor(CAP_THRESHOLD));

    // algo for key 1
    if (keys[0].capacitiveSensor(CAP_THRESHOLD) > CAP_THRESHOLD &&
    keys[1].capacitiveSensor(CAP_THRESHOLD) < keys[0].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
    keys[2].capacitiveSensor(CAP_THRESHOLD) < keys[0].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
    keys[3].capacitiveSensor(CAP_THRESHOLD) < keys[0].capacitiveSensor(CAP_THRESHOLD) * noMulti) {
    Serial.print("key pressed on sense1");
    Serial.println("");
    tone(BUZZER_PIN, NOTE_A7, noteDur);

    }

    // algo for key 2
    else if (keys[1].capacitiveSensor(CAP_THRESHOLD) > CAP_THRESHOLD &&
    keys[0].capacitiveSensor(CAP_THRESHOLD) < keys[1].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
    keys[2].capacitiveSensor(CAP_THRESHOLD) < keys[1].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
    keys[3].capacitiveSensor(CAP_THRESHOLD) < keys[1].capacitiveSensor(CAP_THRESHOLD) * noMulti) {
    Serial.print("key pressed on sense2");
    Serial.println("");
    tone(BUZZER_PIN, NOTE_B7, noteDur);

    }
    // algo for key 3
    else if (keys[2].capacitiveSensor(CAP_THRESHOLD) > CAP_THRESHOLD &&
    keys[1].capacitiveSensor(CAP_THRESHOLD) < keys[2].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
    keys[0].capacitiveSensor(CAP_THRESHOLD) < keys[2].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
    keys[3].capacitiveSensor(CAP_THRESHOLD) < keys[2].capacitiveSensor(CAP_THRESHOLD) * noMulti) {
    Serial.print("key pressed on sense3");
    Serial.println("");
    tone(BUZZER_PIN, NOTE_C7, noteDur);

    }
    // algo for key 4
    else if (keys[3].capacitiveSensor(CAP_THRESHOLD) > CAP_THRESHOLD &&
    keys[1].capacitiveSensor(CAP_THRESHOLD) < keys[3].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
    keys[2].capacitiveSensor(CAP_THRESHOLD) < keys[3].capacitiveSensor(CAP_THRESHOLD) * noMulti &&
    keys[0].capacitiveSensor(CAP_THRESHOLD) < keys[3].capacitiveSensor(CAP_THRESHOLD) * noMulti) {
    Serial.print("key pressed on sense4");
    Serial.println("");
    tone(BUZZER_PIN, NOTE_D7, noteDur);

    }

    }

body:
You might experiment with the code shown at the end of this answer.  It is fairly responsive, in the sense that readings are taken reasonably quickly (several per millisecond), which should leave a good deal of time available for other processing.

In this code, all of the pins that are on the same port are sampled at the same time.  For example, pins 2,3,5,6  on an Uno are all on port D so their four pads can be tested all at the same time.  But if the pins list includes pins from `k` different ports, sampling will take up to `k` times as long as when sampling from a single port.  For example, on a Mega2560, pins 2, 3, 5 are on port E and pin 6 is on port H, so this code's execution time when processing buttons on pins 2,3,5,6 is about twice as long on a Mega as on an Uno.

[*Edit:*  For Uno port-to-pin assignments, see an [Arduino Uno Pinout Diagram](https://www.google.com/search?hl=en&site=imghp&tbm=isch&source=hp&biw=1095&bih=625&q=uno+pinout&oq=uno+pin&gs_l=img.1.0.0l3j0i30j0i5i30l6.2233.4374.0.6513.7.7.0.0.0.0.70.453.7.7.0....0...1ac.1.64.img..0.7.451.lq4psgGuNr0).  On such diagrams, labels like `ADC0 PCINT8 14 A0 23 PC0` show the Arduino digital pin reference number (eg, 14), analog pin label (eg, A0), its various functional designations (ADC0, PCINT8, and PC0, meaning analog input pin 0, pin-change-interrupt pin 8, and bit 0 of port C), and the physical pin number (23).   For hardware level information about Uno ports, see [Atmel's document #8271](http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf).  Use Google images similarly to find other-model diagrams, eg [Mega 2560 pinouts](https://www.google.com/search?hl=en&site=imghp&tbm=isch&source=hp&biw=1095&bih=625&q=uno+pinout&oq=uno+pin&gs_l=img.1.0.0l3j0i30j0i5i30l6.2233.4374.0.6513.7.7.0.0.0.0.70.453.7.7.0....0...1ac.1.64.img..0.7.451.lq4psgGuNr0#hl=en&tbm=isch&q=mega+2560+pinout).]

You may need to tune some of the constants to fit your own circuitry or switch-function requirements.  I'm not able to tell from the question what resistor sizes you are using or what your circuit is.  For preliminary tuning, enable the `secondly()` function and disable `testChange()` functions.  If your circuit is similar to that shown below but uses higher resistances, you may need to increase `nsamp`, `IsHighCount`, and `preSamp`.

Here is the general idea of circuitry I used:
[![enter image description here][1]][1]

In the above, "Drive" refers to pin 4.  "Sense 1" ... "Sense j" (with j=4) refer to pins 2, 3, 5, 6, as in your example code.  The capacitors illustrated are tape-covered aluminum-foil pads, eg 22 x 44 mm and the resistors are 440 KΩ each (two 220 KΩ's in series).  Those resistor values produce an RC time constant of a few dozen microseconds when a button isn't touched, and a couple hundred microseconds when a button is touched.

Here is some example output:

    2 on  199 7587
    2 off 179 7702
    1 on  196 10798
    1 off 154 10802
    1 on  253 10900
    1 off 180 10924
    2 on  219 18097
    2 off 166 18134
    3 on  214 21105
    3 off 155 21385
    3 on  227 24312
    3 off 72 24535

In that output, the first column is switch number.  The last column is the current reading of `millis()` at time of printing.  The third column is total counts accrued from 12 sets of contact readings.  The simple-minded on/off algorithm used in the `testChangeA()` function is that a contact is on when its 12-sample count exceeds 180.  One could also add calibrations, adaptive threshholds, debouncing, etc to the code.

Here is the code (which was run on an Uno, but I tested most of it on a Mega also, and it should run ok on other Arduinos as well since the direct port accesses are computed via functions like `portInputRegister`, `portModeRegister`, etc in `countPins7()` setup before it calls `portSampler7()` to run the test.

<!-- language: c -->

    /* Via serial port, tell the current time when capacitive readings on
     various digital pins show a button has been "pressed" or "released".
     JW - 25 Dec 2015

     See eg refs at http://playground.arduino.cc/Code/CapacitiveSensor and
     http://www.arduino.cc/en/Reference/PortManipulation and
     http://garretlab.web.fc2.com/en/arduino/inside/arduino/Arduino.h/digitalPinToPort.html

     */
    #include <Streaming.h>  // provides nicer syntax for printing
    // Set upper size on pins count per sample; #samples saved per reading;
    //  #samples tossed; threshold for Button-is-on; #samples per set; etc
    enum { nbits=8, nsamp=40, preSamp=1, SettleDown=90 };
    enum { IsHighCount=15, SampleSets=12, IsHighTotal=IsHighCount*SampleSets };
    void setup() {
      Serial.begin(115200);  // initialize serial port
    }
    //-----------------------------------------------------------
    // portSampler7(): Sample a port nsamp times and return the results.
    // Inputs:  drivePin, portCode, pinsMask, preWait.  Constant nsamp.
    // Output:  array of nsamp samples.
    // This version takes 8 cycles per sample, and as inputs switch
    // on after about one RC time constant, on a 16MHz Arduino an
    // m-count result (that is, a bit clear in m of the nsamp readings)
    // suggests RC is about m/2 + preWait/2 us.
    void portSampler7(uint8_t drivePin, uint8_t portCode, uint8_t pinsMask,
        uint8_t preWait, uint8_t *samples) {
      volatile uint8_t *pin, *port, *ddr;
      // pin, port, and ddr are pointers to registers with volatile
      // contents: input port, output port, direction register.
      pinMode(drivePin, OUTPUT);
      digitalWrite(drivePin,LOW);
      pin =  portInputRegister (portCode); // eg points to PIND
      port = portOutputRegister(portCode); // eg points to PORTD
      ddr =  portModeRegister  (portCode); // eg points to DDRD
      *port &= ~pinsMask;      // Turn off our pins
      *ddr  |= pinsMask;      // Make our pins be outputs, briefly
      for (uint8_t i=0; i<SettleDown; ++i) *pin;  // Delay to let pins settle low
      *ddr &= ~pinsMask;      // Make our pins be high-impedance inputs
      digitalWrite(drivePin,HIGH); // Turn on driver pin
      for (uint8_t i=0; i<preWait; ++i) *pin;  // Baseline Delay
      for (uint8_t i=0; i<nsamp; ++i) // Take and store nsamp readings
        samples[i] = *pin;
    }
    //-----------------------------------------------------------
    /* Sample a pins-list and report results in counts array.  Eg,
       pinsList can look like "2,3,4,5,6" or "2,4,5,12,9,23,17,7"
       etc.  A list may contain digits and commas only.  Pins may be
       listed in any desired order.  Elements of counts will be in
       list-order.  Eg, in the "2,3,4,5,6" example, counts[0] is the
       count for pin 2, counts[1] is the count for pin 3, etc.  A
       larger count implies longer rise time and larger capacitance.
       Use preWait to suppress baseline-level counts (and to reduce
       sample array size) by waiting a while before beginning to sample.
     */
    uint8_t countPins7(uint8_t drivePin, char *pinsList,
         uint8_t *counts, uint8_t preWait) {
      uint8_t pnum, pomask, pocode, potem, i, j, mul;
      uint8_t sampl[nsamp], pim[nbits], pat[nbits], bout=0, nat=0, pcon;
      char *c, cc;
      int usedPorts=0; // To track which ports are done
      for (c=pinsList, counts[0]=pcon=0; *c; ++c) // Zero the counts array
        if (*c < '0' || *c > '9') counts[++pcon] = 0;
      // In each pass, group bit numbers by port and sample the port
      while (nat<pcon) { // Each loop pass sets one bit in usedPorts
        pnum = pocode = pomask = bout = pcon = 0;
        c = pinsList;
        while ((cc=*c++)) {  // Loop until c is at end of string
          if ('0' <= cc && '9' >= cc) {
     pnum = 10*pnum + cc - '0';
     if ( *c < '0' || *c > '9') { // See if pin # is complete
       potem = digitalPinToPort(pnum);  // Get port #, in range 1 to 12
       if (!(usedPorts & (1<<potem))) { // Is potem's port already done?
         if (!pocode)     // If pocode not set, set it
           pocode = digitalPinToPort(pnum);
         if (pocode == potem) {  // Process pin if it's in current port
           pomask |= (pim[bout] = digitalPinToBitMask(pnum));
           pat[bout++] = pcon; // Save location of pin's bit in results
         }
       }
       pnum = 0; // Clear # accumulator
       ++pcon;   // Count pin numbers
     }
          }
        }
        // Now pomask is a mask for all bits to be read from port pocode
        // and we are ready to sample current port
        portSampler7(drivePin, pocode, pomask, preWait, sampl);
        usedPorts |= 1<<pocode;    // Mark the port finished
        // Count up # of zeroes (ie rise times) in sampled bits
        for (j=0; j<bout; ++j) {
          int count;
          uint8_t m=pim[j];
          for (count=i=0; i<nsamp; ++i)
     count += sampl[i] & m;
          counts[pat[j]] += nsamp - count/m;
        }
        nat += bout;  // Count number of pins done so far
      }
      return pcon;   // Return # of pins processed
    }
    //-----------------------------------------------------------
    // secondly() will report counts at start-of-second
    void secondly() {
      uint8_t counts[nbits], j, nc;
      if (millis()00) return; // Wait for start-of-second
      nc = countPins7(4, "2,3,5,6", counts, preSamp);
      Serial << "Counts: ";
      for (j=0; j<nc; ++j)  // Marshal output
          Serial << counts[j] << " ";
      Serial << " t=" << millis() << endl;
      while ((millis()00)==0) {}; // Await end-of-millisecond
    }
    //-----------------------------------------------------------
    uint8_t ostate[nbits] = {0};
    void testChange1() {
      uint8_t counts[nbits], j, nc, s;
      nc = countPins7(4, "2,3,5,6", counts, preSamp);
      for (j=0; j<nc; ++j) {
        s = counts[j] > IsHighCount;
        if (s ^ ostate[j]) {
          Serial << j << (s? " on  " : " off ") << counts[j] << " " << millis() << endl;
          ostate[j] = s;
        }
      }
    }
    //-----------------------------------------------------------
    void testChangeA() {
      uint8_t counts[nbits], j, k, nc, s;
      int sumcount[nbits]={0};
      for (k=0; k<SampleSets; ++k) {
        nc = countPins7(4, "2,3,5,6", counts, preSamp);
        for (j=0; j<nc; ++j) {
          sumcount[j] += counts[j];
        }
      }
      for (j=0; j<nc; ++j) {
        s = sumcount[j] > IsHighTotal;
        if (s ^ ostate[j]) {
          Serial << j << (s? " on  " : " off ") << sumcount[j] << " " << millis() << endl;
          ostate[j] = s;
        }
      }
    }
    //-----------------------------------------------------------
    // Take samples of rise times at  designated pins.  When a pin's
    // time changes from small to large, report rising edge; or
    // when it changes from large to small, report falling edge.
    void loop() {
      //secondly();
      //testChange1();
      testChangeA();
    }

  [1]: https://i.stack.imgur.com/tpwfx.jpg


message:
How can I attach I2C sensors on the small board of Intel Edison?

Sensors like Skin conductance, Body temperature and Heart Rate. Please imagine to talk to a child and keep the answer very simple so I can understand you and you don't lose time to write explanations for your answer.

body: If you're using the mini-breakout board (https://www.sparkfun.com/products/13025), then you can get the I2C connections from the board (connections available through holes under the Edison; you can see them from the backside; see: https://cdn.sparkfun.com//assets/parts/1/0/0/1/1/13025-02.jpg). You can solder headers on or can solder wires directly to the required pins. You can find the pin mapping here: http://iotdk.intel.com/docs/master/mraa/edison.html


body:
Use the [I2C breakout board][1]. This will also handle voltage shift from 1.8 V to the sensor voltage level.

  [1]: https://www.sparkfun.com/products/13034


message:
Problem Uploading to arduino uno board

I have an arduino uno. Whenever I try to upload code to the arduino I get this error.

    avrdude: ser_open(): can't open device "/dev/cu.usbserial-AL01EI7I": Device not configured

    ioctl("TIOCMGET"): Inappropriate ioctl for device Problem uploading to board.
    See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

body:
The error message is telling you that avrdude failed to open the device and read the modem status (basically the information about whether a device is present and ready on a serial line). The most likely causes of this are:

1. Using the wrong serial port (Tools > Port in the Arduino IDE).
1. The IDE not recognizing the board.
1. Using a power only USB cable.

The Arduino IDE seems to remember the device that your board was last connected through, but on some Unix flavored OSes the device name depends, in part, on method of connection – which port, hub or no hub, etc. So if you change the board or the port you plug it into, the name changes.

So, the very first thing to do is to look under  Tools > Port in the Arduino IDE to see if there is another device present. Also confirm that you're using a USB cable with data wires. There are "power only" USB cables…

Failing that, check to see if the OS sees the board. On OS X you would go to the Apple menu and choose About this Mac and then look at at the System Report to see what devices have been detected on your USB busses. I'd be surprised if there wasn't something similar on Linux (and Windows too for that matter). If you're comfortable on the command line you could look in `/dev` for devices with similar names.

If the board is present, but not seen by the Arduino IDE, try restarting the IDE and/or plugging and unplugging the USB cable. Sometimes it helps to plug the cable into a different port.


message:
Use Unix terminal instead of the Monitor on Arduino IDE

I want to make a shell or C script that interprets the Arduino serial input to run commands. For that, I will need to make that script be the Serial monitor for my arduino. Another reason I want to use scripts or the command line as a Serial I/O is because the Arduino monitor function freezes the IDE.

My arduino's serial port is `/dev/tty.usbmodem1d112`

This is what I have tried so far:

1. `cat /dev/tty.usbmodem1d112` < This returns absolutely nothing

2. `screen /dev/tty.usbmodem1d112` < This Prints output, but has problems with input.

3. `cat < /dev/tty.usbmodem1d112` < Same result as cat without the `<` symbol.

Sometimes, I also get annoying **Resource Busy** messages. This makes me re-plug the Arduino board.

---
OS X (10.9.5) Arduino IDE latest version. Arduino M0 pro board.

body:
You'll need to condition the serial line with the `stty` command to get this to work. One of the easier ways to do it is to start by using the Serial Monitor and running the command:

`stty -g < /dev/tty.usbmodem1d112`

That will show you all of the settings that the Serial Monitor used to conditions the line. The `-g` flag to stty tells it to give you the results in a form that can be used as the arguments to another stty command. You could do this like this:

`echo -n 'stty ' > stty.arduino ; sudo stty -g -f /dev/tty.usbmodem1d112 >> stty.arduino`

`chmod +x stty.arduino`

The first line creates a shell script to condition the serial line. The second line makes it executable so that you can run it as a shell command – `./stty.arduino`. The `sudo` runs the command as root (with elevated privilege) which allows you to open the port even though the Serial Monitor will already have it open.

If you want you could move the command into a directory on your `$PATH` (for example ~/bin) so that it can be found regardless of where your current directory is.

After getting set up you can see the output from `Serial.println()` on the Arduino by doing:

`./stty.arduino`

`cat < /dev/tty.usbmodem1d112`

Depending on what you are trying to do, you might find the [expect][1] or [script][2] commands helpful. Expect ([man page][3]) lets you automate interactions with a text based application or process. Script ([man page][4]) creates a transcript of your interactions on the command line with another program or process.

[1]: http://www.admin-magazine.com/Articles/Automating-with-Expect-Scripts
[2]: http://www-users.cs.umn.edu/~gini/1901-07s/files/script.html
[3]: http://www.tcl.tk/man/expect5.31/expect.1.html
[4]: https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/script.1.html


message:
Nokia 5110 Screen Pixel by Pixel

I have got this LCD screen
[![enter image description here][1]][1]

I'd like to be able to decide every pixel status of the screen. Do I need to work directly with the buffer or is there another method?

  [1]: https://i.stack.imgur.com/FC87O.jpg

body:
The 5110 Nokia LCD display is based on [PCD8544][1]. It is not possible to read the device display memory. The controller has only serial data input.

Typically a graphical device driver for that display will use an offscreen bitmap (buffer). To check the pixel status you would need to check the status in the offscreen bitmap.

Some device drivers use only text and copy font bitmap directly to the display memory. In that case you cannot check the status of the pixel (if the text is not buffered).

  [1]: https://www.sparkfun.com/datasheets/LCD/Monochrome/Nokia5110.pdf


message:
RobotLinking 18B20 pinout and circuit board weirdness

I have a Dallas Semiconductors 18B20 temperature sensor on a RobotLinking board. It's part of the [RobotLinking 37 Sensors Kit][1]. The board has a LED to indicate activity. It resembles this:
[![sensor that is similar to mine][2]][2]

Here's what's weird. All the guides I can find for the 18B20 say that the pin order is GND, DQ, VDD. That should mean pin 1 goes to GND, pin 2 goes to a GPIO, and pin 3 goes to 3.3V or 5V (this one can take either). Yes, I am looking at the sensor's pins from its bottom.

If I do this, the board's LED is lit solidly. I get 0 degree readings, the same as if no device was connected. (Infinite resistance?)

To make this work, and get valid temperature readings, I have to hook it up this way: sensor GND to the GPIO, sensor DQ to GND, and sensor VDD to 5V or 3.3V. The LED only flashes when the temperature is actually read.

Here's a twist: if you look at the circuit traces on the RobotLinking board, it looks like the paths between the male breadboard connectors and the sensor's pins 2 and 3 are reversed. This means if you think you are connecting to pin 3 via the male connectors, you are in fact connecting to pin 2, and vice versa. The path from pin 1 on the sensor to the male pin 1 where it plugs into the breadboard is straight, so pin 1 probably means pin 1.

When I described the above connections I made, I accounted for this apparent circuit pathing weirdness.

Another twist is in the manual, the sensor is soldered to the middle leads. My sensor is instead on the furthest leads from the pins, like in the attached image.

The manual with this kit didn't explain any of this. I'm at a loss to understand my observations. For a generic sensor kit for n00bs, why would one want the pins on the bottom of the circuit board not correspond to the pinout of the sensor?

  [1]: http://www.amazon.com/gp/product/B009OVGKTQ
  [2]: https://i.stack.imgur.com/hg7mY.jpg

body:
From the look of the board, it is designed to support multiple devices. I'd suspect that the three sets of holes give different mappings of the device pins to the board pins. Could it be that the sensor is soldered into the wrong set of holes?

If you have a meter or can see the traces you could look to see if the middle set of holes is wired the way you would expect. If that is a photo of your board, it looks like you have enough length in the leads on the sensor to move it to the middle holes.


message:
What causes a "blip" in LED brightness with sequence of 254, 255, 0, 1 brightness values?

I am seeing a "blip" in LED brightness when trying to fade a red LED on an Arduino UNO.

This code demonstrates the "blip" seen in brightness right after a 254, 255, 0 sequence.  When the brightness is then set to 1, the actual brightness is much higher for a short period of time.  The blip is not seen during the entire delay interval, just at the beginning.

I see the blip every time except for the very first cycle, before the 255 to 0 transition has ever happened.

My best guess is that there is a PWM "accumulation" that is not seen when the brightness is set to zero, but it is used when the brightness is set to a non-zero value.

    /*
     FadeBlip
     Derived from Fade.ino.
     */

    int led = 9;
    int brightness = 0;
    int fadeAmount = 1;
    int skipBegin = 5;
    int skipEnd = 254;

    // If you try a shorter delay, you must make the skip range smaller
    // to pick out the blip.  If you try a longer delay, the blip is not
    // as bright.
    int delayms = 1000;

    void setup()  {
      pinMode(led, OUTPUT);
      Serial.begin(9600);
      delay(1000);  // give us time to bring up serial monitor
    }

    void loop()  {
      Serial.println(brightness);
      analogWrite(led, brightness);

      brightness = brightness + fadeAmount;

      // skip the boring middle values
      if (skipBegin < brightness && brightness < skipEnd)
        brightness = skipEnd;

      if (brightness > 255)
        brightness = 0;

      delay(delayms);
    }

body:
The [Why does an LED sometimes flash when increasing brightness?](https://arduino.stackexchange.com/q/17946) question does exactly describe my problem (except for the substitution of pin 11 for pin 9).  That question refers to [this post at forum.arduino.cc](http://forum.arduino.cc/index.php?topic=360468.msg2486781#msg2486781) which gives the beginnings of an answer.

The problem is caused by the fact that `analogWrite(led, 0)` does not use PWM, it just sets the pin to LOW.  So when you call `analogWrite(led, 0)`, the value in the Output Compare Register (OCR) is left at 255.  When you call `analogWrite(led, 1)`, the OCR value is changed to 1, but due to double-buffering this doesn't take effect until the next timer cycle begins.  So for a fraction of the current timer cycle the output pin is left at HIGH.

The solution is to either avoid calling `analogWrite(led, 0)` or to explicitly set the OCR value to 0 when `analogWrite(led, 0)` is called.  This will only work if another call to `analogWrite()` is not made in the current timer cycle.  Given that the default timer cycle takes 32 microseconds, this is unlikely to happen.  32 microseconds = 256 (ticks per timer cycle) / 16MHz (clock ticks per second) * 2 (default timer prescale factor).

For pin 9, the solution was to add these lines immediately after the `analogWrite()` call:

    if (brightness == 0) {
        OCR1A = 0;
    }

For other pins, use the correct Output Compare Register.  For the Arduino UNO they are:

    +-------------+----------+-------+
    | Arduino Pin | Chip Pin | OCR   |
    +-------------+----------+-------+
    |           3 |        5 | OCR2B |
    |           5 |       11 | OCR0B |
    |           6 |       12 | OCR0A |
    |           9 |       15 | OCR1A |
    |          10 |       16 | OCR1B |
    |          11 |       17 | OCR2A |
    +-------------+----------+-------+

Of course this solution will need to be modified if you have changed anything related to timers such as the PWM mode.

The solution given by the forum.arduino.cc post indicated that the Timer/Counter Control Register (TCCR) needed to be modified in addition to setting the OCR value.  This modification was to configure the PWM mode, but the PWM mode would have already been correctly configured by any previous call to `analogWrite()` for that pin.

Others have suggested that calling `analogWrite(led, 1)` before `analogWrite(led, 0)` would be a simpler solution, but that still results in a flash, albeit shorter.

Resources:

- LED fade malfunction (random flash) (forum.arduino.cc/index.php?topic=360468.msg2486781)
- hardware/arduino/cores/avr/arduino/wiring_analog.c
-  Secrets of Arduino PWM (www.righto.com/2009/07/secrets-of-arduino-pwm.html).  There is a more recent copy of this article at arduino.cc (www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM), but that copy has the useful graphics stripped out.
- Arduino Timers and Interrupts (arduino-info.wikispaces.com/Timers-Arduino)


message:
arduino beginner documentation help

I plan to buy these 2 products to begin to play with arduino to learn.

 1. [Board with LCD touch][1]
 2. [Yun board expansion][2]

I have a mega 2560 which i bought with a starter kit and i love to play with. I have not played with the shield yet. I understand some shields can be used together, some not. and some with modification on the board and in the code.

I can't find pins specification for the touch screen and the support on the website doesn't respond.

If some one can help me find specifications for the touch screen, or help me choose some shields that will allow me to use a USB host, wifi, and a touchscreen it will be nice.

Thanks all.

  [1]: http://www.banggood.com/UNO-R3-ATmega328P-Board-2_4-Inch-TFT-LCD-Screen-Module-For-Arduino-p-945755.html
  [2]: http://www.banggood.com/Iduino-Yun-Shield-Expansion-Module-Board-Compatible-Arduino-p-979882.html

body:
The [link you posted][1] describes a TFT LCD Touch screen unit with the SPFD5408 controller, referenced in [this Instructable][2] for use with the Mega. You might start there and migrate to the Yun once you get the screen working.

  [1]: http://m.banggood.com/UNO-R3-ATmega328P-Board-2_4-Inch-TFT-LCD-Screen-Module-For-Arduino-p-945755.html
  [2]: http://m.instructables.com/id/How-to-use-24-inch-TFT-LCD-SPFD5408-with-Arduino-U/


message:
Re-use smartphone/tablets parts like a camera

For learning and hacking purposes, I plan to study and use parts from smartphones and tablets like Galaxy or iPhone. They are really efficient and pretty cheap...

Did anybody do this before? If yes, can anybody tell me what kind of connector is this one on the galaxy camera, [Galaxy Tab S 10.5 Front Facing Camera (Wi-Fi)][1], and whether it can be found for attaching it to an Arduino project?

Edit: Someone else asked a similar question here, [How to reuse quality camera from old / broken phone][2].

  [1]: https://www.ifixit.com/Store/Parts/Galaxy-Tab-S-10-5-Front-Facing-Camera-Wi-Fi/IF252-001-1
  [2]: http://forum.arduino.cc/index.php?topic=269272.0

body:
The connector on the flex circuit from that camera was made by Hirose (it has an HRS logo on it), and might be in the BM10, BM14, or BM20 series.  You can measure the pin spacing, stacking height, etc. to check which series it's in.  For example, the [Hirose BM14 series](http://www.mouser.com/new/hiroseconnector/hirose-BM14-b2b-b2fpc-connectors/) of FPC to board connectors has pins at 0.4 mm Pitch and 0.8 stacking height.

[Mouser.com](http://www.mouser.com/ProductDetail/Hirose-Connector/BM14B08-24DS-04V53/?qs=sGAEpiMZZMvffgRu4KC1R8YV3BvcJQGKbUaU25rr%2bdwhFlq/l3Wjjw==) carries a 24-pin BM14 connector that might mate or match with the pictured connector.  For other photos of Hirose FPC connectors, see [google images for **hirose fpc**](https://www.google.com/search?hl=en&site=imghp&tbm=isch&source=hp&biw=1095&bih=609&q=hirose+fpc&oq=hirose+fpc&gs_l=img.3..0i24l2.2328.4678.0.5124.10.9.0.1.1.0.102.604.8j1.9.0....0...1ac.1.64.img..0.10.604.S8xAzOt5A_8).

While you probably can find a matching connector (via careful measurement and perhaps some trial and error) and build an interface, it may be difficult to use the camera once it's hooked up.  Most Arduino models have too little RAM to support image processing.  A Yun might do it, a Tre, or some other micro entirely, eg Beagle or Raspberry.


body:
*(summary of comment thread)*

I **strongly recommend** against trying to use any of these smartphone camera replacement parts. While they are cheap, this is because the signal they output is nigh impossible for you to use, even if you knew its specifications, which is unlikely given proprietary parts often have proprietary, non-public protocols. Even if you did have it, you'd likely have to implement a linux kernel extension for Raspberry Pi yourself to support it. Far more work than it's worth.

If you actually want to do image processing, there is a clear recommendation: **the Raspberry Pi camera interface**. RasPis have a special flex socket on the board for a camera, and you can buy cameras which work with the `raspivid` etc. commands included in raspbian with no extra setup. This allows you to use OpenCV or similar image processing libraries, or write your own, without having to worry about bitbanging obscure camera protocols.

No-name camera boards can be bought from eBay or similar sites for less than US$20, and they support 30fps 5 MP image/video capture to the Raspberry Pi natively and easily. Just search for "Raspberry Pi camera".

### *However...*

If you're *really* sure you're up to the challenge of hacking a proprietary camera module, you'll want to do thorough research finding the exact protocol specifications for these camera chips first, and try to find ones that are the most common, for the highest chance of compatibility, and likelihood of others having made progress on using them. Good luck!


message:
What phone carriers are available in the USA that are compatible with a sim900 breakout board

I was wondering what carriers are compatible with a sim900 breakout board. I know it needs a GSM network (AT&T,T-mobile,?) but what networks can I use?

It needs a 850/ 900/ 1800/ 1900 MHz frequency to work but who offers that frequency? I personally could not find what frequency cell phone companies offered. From how I understand it is that T-Mobile definitely will work.I have heard several different answers about companies like AT&T and I have seen discussion about sprint (which I don't understand because they are a CDMA carrier).

I have also heard that there are other carriers (Vondafone, nextel,Ting) that might be more cost effective for people like me who are only going to be using the text messaging.

Can someone please set me straight on who I can use.

body:
SIM900 should be compatible with both AT&T and T-Mobile. T-Mobile uses 1900Mhz for 2G and AT&T uses 850Mhz and 1900Mhz. Although both carriers are upgrading to 4G, they still support 2G devices. My personal experience is that most quadband 2G devices still work with AT&T and T-Mobile and there is no technical reason why SIM900 shouldn't work. However, there can be issues with incompatible data plans that are compatible only with their own devices. You need to be careful when selecting the contract and buying the sim card.

Nextel and Ting uses Sprint's network which is CDMA and thus wouldn't work. However Vodafone seems to be using T-Mobile's network and may work.


message:
Hardware Interrupt Triggered Randomly

So there is this pretty generic part of my project that involves triggering an ISR that will flip a boolean value. I have set up the software side like so:

<!-- language: c -->

    void setup() {
      attachInterrupt(digitalPinToInterrupt(2), displayConvergence, FALLING);
    }

    void loop() {
      if(flashConvergence) {
        //Do stuff that takes several seconds
        delay(3000);
        flashConvergence = false;
      }
    }

    void displayConvergence() {
      if (!flashConvergence) {
        flashConvergence = true;
      }
    }

The schematic is as follows:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/ZE3pg.png)

<!-- End schematic -->

But the behavior of my circuit surprised me as the pin interrupt would get triggered randomly at a frequency at (guessing here) 3 times a second.

Weird, I thought. I fiddled around and found that when the boost converter's 180V is not connected to any load, the interrupt service triggers as expected, as in it starts working correctly. So I thought perhaps the issue was some noise introduced by the boost converter.

I modified the circuit by adding a capacitor across the switch:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/adfpO.png)

<!-- End schematic -->

I tried 1 uF at first, but that didn't help and neither did 10 uF. However, when I tried 100 uF (I thought decoupling capacitors are usually 0.1uF to 1 uF, is the value I am using too big?), things seem to be working as expected with the exception that when I hold the switch in the closed position for a long time, then let it go back in the open position, the interrupt service can be triggered randomly for a short period right after I let go of the switch.

Is my initial assumption that the ISR is triggering randomly due to EMI from the boost converter correct? Perhaps there are other causes I am not looking at? Is there a way to make this work 100% (as in solve the issue right after the switch is put in the open position)?

Thanks for the help!

body:
If you don't have any bulk capacitance (100uF or so) on your logic supply you will have noise problems.  You should also use some smaller (1uF and 0.1uF) to provide bypass for higher frequency noise in the power supply system.

Glenn


body:
It has come to my attention I never posted a followup to this but I was actually able to solve this problem by shielding the wire going from the switch to the arduino. The switch's wire was about 2 to 3 inches long and I wrapped aluminum foil around it, which shielded the signal from what I suspected was EMI induced by the switching converters.

[![Poor Man's EMI Shielding][1]][1]

  [1]: https://i.stack.imgur.com/MWI5S.png


message:
How to Send Live Sensor Data to iOS Custom Apps with BLE

I am looking for a Bluetooth Low Energy (BLE) device that could send live sensor data from Arduino to iOS custom apps, not the app that is already in the app store. I would like to create my own apps to receive the sensor data. Or are there any other ways to achieve it?

body:
I would expect this to be pretty straight forward. Off hand, I can't think of anything that would be a major roadblock to creating your iOS apps. It seems like there are two problems you'll need to solve:

1. Finding a BLE chip that is relatively easy to integrate with an Arduino, and
1. Selecting the tools that you'll use on the iOS side to develop your app.

Since I haven't done this my self, I started off looking on the Arduino side – mostly because it seemed like the problems there would be larger. I searched on Google using the terms:

`aruduino ble`

I found quite a few candidates that look promising, here are some of the better ones:

* [Bluefruit LE - Bluetooth Low Energy (BLE 4.0) - nRF8001 Breakout - v1.0][1] – I put this one on the top of my list because the price is pretty reasonable (< $20 US) and Adafruit tends to do a good job of supporting their products with tutorials and at least a basic library that demonstrates the functionality of the device.

* [Redbear Labs][2] - I don't know anything about Redbear, but they do well in Google searches and appear to have several products, including a BLE shield, that might do what you want.

* [BLEduino][3] - this is a Kickstarter, and while it looks interesting, a *very* quick investigation didn't reveal a source where you can buy one.

The choice of devices will partly depend on what your ultimate goal is. Something like the BLEduino will give you an all-in-one package to build your project around. The downside of this is that you may be spending money on functionality that you don't need/want to duplicate. A breakout board like the Bluefruit LE gives you a smaller device and possibly more flexibility at the expense a bit more work to get up and running.

Next you'll need to select development tools. I started by searching with the terms:

`ble swift ios`

I got a number of promising results, including:

* [Arduino Tutorial: Integrating Bluetooth LE and iOS with Swift][4]
* [Apple: Bluetooth for Developers][5]
* [Adafruit - Introduction to Bluetooth Low Energy][6]

These first three look like good starting points for "getting your bearings," the following two are specific to actual boards.

* [Getting Started with the nRF8001 Bluefruit LE Breakout][7]
* [RedBearLab/iOS][8]

[1]: https://www.adafruit.com/product/1697
[2]: http://redbearlab.com/bleshield/
[3]: http://bleduino.cc
[4]: http://www.raywenderlich.com/85900/arduino-tutorial-integrating-bluetooth-le-ios-swift
[5]: https://developer.apple.com/bluetooth/
[6]: https://learn.adafruit.com/introduction-to-bluetooth-low-energy
[7]: https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout
[8]: https://github.com/RedBearLab/iOS


message:
Reading SPI between an MCU and NRF24L01

I have a remote control that has an STM32 MCU and sends data via NRF24L01. What I would like to do is clone the data sent when buttons are pressed by reading what is being sent to the RF24 and then replicating these messages with my own "remote".<br>

I have tried sniffing the data wirelessly with my Pro Mini and NRF24L01. I have everything plugged in correctly, the BasicExample seems to be running fine, but when I run a promiscuous channel activity sniffer, I don't get any wireless data, not even running wifi and bluetooth near the NRF. Pro Mini is 5V and NRF sniffer is powered by an external 3.5V battery with cap on VCC-GND, ground is common to Pro Mini. I have also tried the WireShark approach, but with 0 packets found.

Therefore I want to try it directly wired to the remote. I don't have a logic analyzer handy. How would I read the data? By just connecting MISO and CS to an arduino and running an SPI reader? What would be the best way to do this? I have the Pro Mini and many Teensy boards ready.

body:
That was an interesting challenge. There are some obstacles to consider when trying to use RF sniffing:

1. What channel is used? (128)
2. What bit-rate is used? (250K-1M-2M)
3. How many address bytes? (3-5 byte)
4. How many bits in CRC? (1-2 byte)
5. Auto-Acknowledgement? (1 bit)
6. etc.

Without any info on the remote NRF [configuration][1] this is tedious to break. Probing the hardware signals (MISO, MOSI, SCK, SS) on the remote NRF chip with a logic analyzer seems (much) easier.

Cheers!

  [1]: http://www.nordicsemi.com/eng/content/download/2730/34105/file/nRF24L01_Product_Specification_v2_0.pdf


message:
How can I make Arduino IDE use Atmel's provided toolchain? (Linux/Ubuntu)

I have an Arduino based board using ATmega168PB, but so far only Atmel's provided toolchain supports this microcontroller. I can download the toolchain from Atmel's website, but I am not sure how to make the Arduino environment use it.

body:
In the directory for the new core create a new `platform.txt` and give the entry for `compiler.path` the location of the `bin/` directory containing the Atmel toolchain.

    compiler.path=/path/to/bin/


message:
Measuring voltage on an analog pin - What do I need to know about amperage?

I'd like to measure the voltage at a test point on a stepper motor driver chip with an arduino. The voltage at this point controls the amperages to the phase coils and is adjusted to trim the driver.

I have a common ground with the driver already, I'd like to wire the drivers v-ref point to an analog input to drive an LCD showing the output amp number so I can adjust the driver.

The issue I am worried about is that with the hardware I have to test with a properly trimmed driver is pushing 0.84A.

Is this safe to do without killing the arduino board?

body:
Yes. The only thing you need to be concerned about is the voltage. It needs to be less than the Arduino Vcc.

The voltage sense circuit (analog inputs) typically have a high impedance and should draw a negligible current from the circuit being sensed. I didn't have much luck finding the actual spec for any of the AVR chips, but I did find [this answer to the question][1] on Electronics.StackExchange – where they say "hard to tell, the specs are incomplete, but 10 KΩ seems like a reasonable guesstimate/assumption" (I paraphrase). The reasoning is interesting and worth a read.

[1]: https://electronics.stackexchange.com/questions/67171/input-impedance-of-arduino-uno-analog-pins


message:
Read a String from serial to debug the AT commands sent to my GPS shield

I want to extract an AT command's response (via serial port) to find out if the GPS shield is working as it should be.

I used:

<!-- language: c -->

      if(Serial.available()>1){
         String response = Serial.read();
         Serial.println(response);
      }

Normally the response to AT is OK but it keeps telling me that it cannot convert `int` to `String` .... can someone help?

body:
Serial.read() returns a byte (a single character), you've told the compiler that response is a string. It doesn't know how to deal with the difference…

What you want to do it to read the response in a loop until you've got it all.

Here's an [example](https://www.arduino.cc/en/Serial/Read).


body:
`if (Serial.available() > 1)` is wrong. Always use `if (Serial.available())` in such cases. Also it seems you are communicating with the GPS shield using Hardware Serial. However, the Arduino also uses the same serial port for communicating with the PC via the USB connection. So what you have basically is:

 - Arduino TX, PC RX and GPS RX are all connected
 - Arduino RX, PC TX and GPS TX are all connected

So anything the Arduino writes to the Serial port using `Serial.println()` is received by both the PC and the GPS shield. And the other hand, responses from the GPS shield and commands sent from the serial monitor all arrive at the same Arduino pin. So when you use `Serial.read()`, assuming you used the serial monitor to send the command, you will end up receiving your own command (like some sort of echo), and according to your program, you use `Serial.println()` to send the command again which is received by both PC and GPS shield, with the GPS shield responding to the same command again. All undesirable.

TLDR; use SoftwareSerial instead for the GPS shield. Connect the GPS shield TX to pin 2 and its RX to pin 3 and use this code:

        #include <SoftwareSerial.h>

        SoftwareSerial gps(2,3);   // pin 2 = RX, pin 3 = TX

        void setup(){
            Serial.begin(57600);
            gps.begin(57600);    // change to your baud rate, if not auto-baud
        }

        void loop(){
            while (Serial.available())     //used to send commands from PC
                gps.write(Serial.read());   // to gps
            while (gps.available())        // used to read responses from gps
                Serial.write(gps.read());  // to PC
        }

So the Arduino forwards everything it receives from the PC monitor (commands) to the shield and sends everything it receives from the shield (responses) to the PC to be displayed in the serial monitor.


message:
Link to an project for remotely turning off light switch?

I want to build a contraption using an arduino that allows me to turn off my light from across the room. I plan to use a solenoid to move the lights switch up and down. I'm sure I'll have some specific questions later on but to start with, has anybody made or seen a similar project? All I'm really looking for is a link to a project (unless you're willing to give advice/suggestions). Thanks!

body:
Various types of light switch actuators. Which is it?

[![enter image description here][1]][1]

[![enter image description here][2]][2]

[![enter image description here][3]][3]

[![enter image description here][4]][4]

[![enter image description here][5]][5]

[![enter image description here][6]][6]

[![enter image description here][7]][7]

[![enter image description here][8]][8]

  [1]: https://i.stack.imgur.com/Ktgaq.png
  [2]: https://i.stack.imgur.com/MXlcq.png
  [3]: https://i.stack.imgur.com/5LTJu.png
  [4]: https://i.stack.imgur.com/RpkjO.png
  [5]: https://i.stack.imgur.com/CBpja.png
  [6]: https://i.stack.imgur.com/CcyUO.png
  [7]: https://i.stack.imgur.com/GLrAY.png
  [8]: https://i.stack.imgur.com/XhUn2.png


body:
This isn't exactly what you asked for, but may be a better idea.

Light switches are electrically just switches.  Either two points are connected or they are not.  In this case they are meant to be mechanically actuated by humans.

Instead of making a electrically controlled contraption that mechanically activates the existing switch, you could more easily use a electrically-activated switch directly.  Such things are called <i>relays</i>, and are quite common and readily available.  You can easily get a relay that can be actuated from 5 V that can switch 120 or 240 Vac at a few amps.

Put the relay in parallel across the switch if you want the switch to be able to override the light on, and in series if you want the switch to be able to override the light off.

To allow both the relay and the switch to toggle the light on/off independently, each needs to be a SPDT (single pole double throw) switch or relay.  Actually, you'll have a hard time finding a relay that isn't at least SPDT.  Ordinary wall switches aren't, but ones meant for multiple switches to control the same light are, like you often find at the top and bottom of the same set of stairs.


body:
### MicroBot Push: a robotic finger for your buttons...

[![enter image description here][1]][1]

https://www.indiegogo.com/projects/microbot-push-a-robotic-finger-for-your-buttons#/

### The Robotoic Light Switch

[![enter image description here][2]][2]

http://hackaday.com/2015/11/06/the-robot-light-switch/

### Wifi controlled light switch

[![enter image description here][3]][3]

https://hackaday.io/project/5141-wifi-controlled-light-switch

  [1]: https://i.stack.imgur.com/64zRC.png
  [2]: https://i.stack.imgur.com/k7xM7.jpg
  [3]: https://i.stack.imgur.com/20BQY.png


message:
Options for measuring position of garage door

I'd like to be able to measure the position of my garage door. Determining if the garage door is fully open or fully closed should be fairly simple with some magnetic reed switches but I'd like to know the position of the door when it's partially open/closed.

body:
A couple of possibilities occur to me. One would be to mount a rotary encoder on a rotating part of the door. Another would be to attach a reed switch to the track and a series of magnets to the door. I suppose you could do something with a proximity sensor as well.

How much precision do you need in the position of the door? What do you know that is deterministic? For example is the door transit time predictable? Is it a positive drive? Do you get to know when the door starts moving? That might be enough right there.

If you can say more about what you're trying to do it would make it easier to provide suggestions and insight.


body: I would suggest an Ultrasonic Range Finder. There is an example in the Arduino Tutorials and they are available cheaply on ebay.


body:
A linear encoder (usually comprising an LED, a photodetector, and an encoder strip with black lines on it) would work, but a long encoder strip is expensive and probably not reliable a garage environment.  You could use a radial encoder attached to the motor, but that is probably too expensive too and overkill for your application.

Ranging devices are often difficult to use with something narrow and dirty like the bottom edge of a garage door.  Placing devices on the door itself is probably not the most reliable and inexpensive way to do this either.

**A Solution for Any Large Spring Loaded Position Sensing**

One way that can be very reliable and is inexpensive is to use two strain gauges.  In spite of the low cost, this approach is used in many industrial and laboratory arrangements.  You could use an IN114 or a similar 8-pin dip instrument amplifier to convert the differential strain gauge resistance to a Voltage within the range of the Arduino analog input.

I'd guess a cost around $100 with shipping for the IN114, the rest of the circuit, strain gauges, emery cloth, bonding cement, temperature sensor (optional), power supply, jacks, solder, circuit housing, PCB breadboard, and cabling.

You will need to use a Wheatstone bridge at the + and - input of the instrument amp. There are plenty of example circuits.  Search for, "instrument amp wheatstone bridge strain gauges," to get some schematic diagrams.

An adjacent two of the four legs of the Wheatstone bridge are the two strain gauges.  One of the other two legs would be a potentiometer in series with a fixed resistor to give you offset adjustment.  Another potentiometer adjusts gain.  The IN114 spec sheet shows how to set the gain and how to power the chip.

Mechanically, the strain gauges would go on opposite sides of the exact same point on the spring, near where it attaches to the stationary frame to which the tracks are mounted.  One strain gauge must be bonded to the inside of the spring.  The other to the outside, directly opposite the inside one through the thickness of the spring wire.  This will allow the Voltage you measure to indicate the strain on the spring which is related to the position of the door.

(The image at http://recordtek.com/sites/default/files/Gauge-spring.png shows a strain gauge bonded to the outside of the spring.  The inside complement would go directly underneath it on the inside.)

I'd recommend an Arduino Due to read the output voltage of the IN114, setting the gain and offset to stay within the 1.55 to 2.75 V range of the analog inputs of the Due for all garage door positions.  That will take some trial and error with a Voltmeter before you connect the Due.

To calibrate the system, the analogRead() values for ten somewhat equally spaced garage door positions are placed in an array of integers.  Another same size array of doubles receives the corresponding door positions in whatever units you want.  These can be static arrays that are initialized in your Arduino code.

You would get the position from the analogRead() at any point in time by interpolating the data in the table represented by the two corresponding arrays.  That is easier than it sounds.  There are articles explaining how and libraries providing linear interpolation in C, some of which may be usable without modification in an Arduino sketch.

**Bonding the Strain Gauges**

There are many articles available on using strain gauges and how to rigorously clean the surface and position and orient the gauges before bonding them to the metal of the spring.  That's critical.  They have to point in a particular direction, and the bond will come apart if you don't clean the metal well enough, which would not be good.

**Going High End**

If you wanted high accuracy, you could enhance your design to possibly get three or more significant figures as you reach expert level.

 - Read and factor in temperature when doing the interpolation
 - Take more than 10 calibration samples and use larger arrays to match
 - Use a quadratic or cubic interpolation instead of linear
 - Write a calibration algorithm to fill the two arrays with new values
   automatically every time the door goes from one extreme position to
   the other


message:
Arduino Uno ADC behavior in free running mode

I'm using my ATmega328P to sample an analog signal in free running mode. The ADC clock frequency is set to ÷128. I've read that a single analog conversion lasts 13 clock cycles. I would like to know if the number of clock cycles changes if I make the ADC trigger an interrupt after every conversion (ADIE bit set to one). Or will the ADC still use 13 clock cycles and start again on the 14th?

If ADIE is set to zero (no interrupts) will the result of the conversion still be written to ADCL and ADCH? And at what time of the 13 clock cycles is this result written to those registers? This is important to me so I can calculate how much time I have to read those registers.

Would it be possible to set ADIE to zero and instead use a timer interrupt to read ADCL and ADCH every ~1 millisecond. Or am I missing something important?

body:
You may want to take a look at Amanda Ghassaei's [tutorials on Arduino DSP techniques][1] or the [FFT/FHT][2] code at the Open Music Labs. Both use the Arduino ADC in free running mode. Amanda's code uses interrupts, the Open Music Lab code sits in a tight loop waiting for the conversion to complete.

Based on the Open Music Lab code I can say, yes, the conversion is still written to ADCL and ADCH regardless of the interrupt setting in ADIE. I can't tell from your question how concerned you are about cycle counts, but I don't think you'd see a significant change using interrupts (I'd expect it to be zero). But using interrupts you'll take a hit as you enter and return from the ISR.

As I mentioned in the comment, take a look at Amanda Ghassaei's code. She toggles pin 12 which creates a spike in the trace if you have a scope attached to pin 12 (or a logic analyzer). That will give you a very easy way to determine the actual time to handle the conversion.

[1]: http://www.amandaghassaei.com/projects/arduinodsp/
[2]: http://wiki.openmusiclabs.com/wiki/ArduinoFHT


message:
Problem with serial driver for CH340G board

I bought a `USB Nano V3.0 ATmega328 16M 5V Micro-controller CH340G board For Arduino` and tried it with Arduino 1.6.6 on my MacBook Pro running OS X 10.11.1

The USB serial could not be seen. I searched on the web and found a few posts about this board, and downloaded http://www.wch.cn/download/CH341SER_MAC_ZIP.html

Most of the instructions were in Chinese, but the driver `CH341SER_MAC.ZIP 资料类型：应用资料 资料大小：250KB 资料版本：1.1 更新时间：2013-12-25` seemed to install, but I cannot seem to find any `/dev/tty` and Arduino can't see any serial ports.

Has anyone had any success with this. (The seller has sold 18000 of these so someone may have got it working.)

body:
Using different search criteria I found http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

This indicated a newer driver for OSX 10.9 and above at:-
http://kiguino.moos.io/downloads/CH34x_Install.zip

It is now working OK.

PS This was probably a Mac question, but I will answer as it is mainly of interest to Arduino users.

PPS The board worked on my Raspberry Pi which had the driver installed.

WARNING
The driver worked on `OS X 10.11` but after upgrading to `OS X 10.11.2` when I plug the USB cable into the Mac it causes a crash. This may or may not be related to the upgrade but after this happened twice I gave up.
-------


body:
The CH340 is a chip with notoriously iffy driver support, definitely for OS X, and reportedly also for Windows. Some driver authors are not very fond of it, as evidenced by this [affectionate comment][1]

    /*
     * driver for WinChipHead CH341/340, the worst USB-serial chip in the world.
     */

On the upside, the chip costs an order of magnitude less than the commonly used FTDI chips.

I've seen drivers from 3 sources:

 1. The manufacturer drivers work off and on. The ones on the official site are not signed, and at some point, they started causing kernel panics for me.
 2. The [Codebender][2] team is including free CH340 drivers in their installer, and I've had some success running those, although I'm having some difficulties with the latest version. YMMV.
 3. So far, the drivers developed by [Repleo][3] have been rock solid for me. These are commercial, but, at less than $10, a pretty good deal in my opinion.

  [1]: http://cvsweb.netbsd.org/bsdweb.cgi/src/sys/dev/usb/uchcom.c?rev=1.13&content-type=text/x-cvsweb-markup&only_with_tag=MAIN
  [2]: https://codebender.cc
  [3]: https://www.mac-usb-serial.com


body:
On MacOS Sierra it kept crashing the OS,  but version 1.3 works on MacOS Sierra.

Found here:  https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver


message:
detecting presence inside - PIR or ultrasound?

<sup>(I am professionally a software guy working in the [GCC](http://gcc.gnu.org) compiler with [MELT](http://gcc-melt.org/), so I am fluent in software, but much less in hardware - I did use a solder for a 74LS00 nand gate based stuff in the 1990s. This is my first Arduino project)</sup>

My first Arduino project would be to automate the lights and the fan in my inhouse WC toilet in Paris (France) suburb. I bought several Arduino Nano v3 boards. I'm thinking of driving with a relay a low voltage 12v LED lightbubble. I want to detect human presence in the toilets. I'm thinking of some PIR sensor, but I am afraid that PIR won't detect anything if the temperature is above 37°C (or about 100F), which is unusual in Paris (France) but may happen a few days per year (I've got no air conditioning). Is my worry correct, or can a PIR still work with very warm outside temperature? Should I use an ultrasound detector instead?

body:
PIR sensors work fine and are probably easier to program for than ultrasonic sensors. For example, this tutorial on a PIR sensor sold by [Adafruit][1] has a [datasheet][2] at the bottom that says:

> Operating Conditions Operating Temperature -20 ˚C to +70 ˚C
>
> Storage Temperature -30 ˚C to +80 ˚C
>
> Operating Voltage 3 to 10 V at Rs = 47 kΩ

You can try to find and check the datasheet for the sensor you intend to purchase to determine if it will work.

  [1]: https://learn.adafruit.com/pir-passive-infrared-proximity-motion-sensor/
  [2]: https://learn.adafruit.com/system/assets/assets/000/010/134/original/RE200B.pdf


body:
One thing to be wary of with PIR sensors is that they only detect *moving* heat.  That means that your light would turn on as you enter the toilet, but would turn off again when the sensor fails to detect movement.  That will be once you're sat on the toilet and reading the newspaper.  To keep the light on you would need to flail your arms around to keep the sensor on, and thus the light on.

So from that perspective alone the ultrasound would possibly be a better option since it can detect the presence of anything within its cone of sound - as long as that something is big enough, like a human body.

A third option that you haven't mentioned is infra-red beams.  Depending on how big the toilet is you may be able to just have one IR beam passing through the room, and when someone is in the room that beam will be broken.  Only works in small cubicles though.  For larger rooms you may need either a mesh of beams to cover the whole room, or a dual-beam in-out counting arrangement on the entrance (two beams, one before the other. If beam A breaks before beam B then someone has entered - if beam B breaks before beam A then someone has left. When there are 0 people in the room then turn the light off).


message:
Use of additional i/o ports in Arduino Mega

I'm a newbie in Arduino and I bought an Arduino Mega instead of the Uno. I want to know what the so-called additional i/o pins do. Are they the same with PWM and SPI? What can they do?

body: Additional I/O pins means more inputs and outputs. Therefore, you can have more signals. There are also some more specialized pins. For example, there are more PWM pins, more TX and RX pins for serial communication and more analog read pins.


body:
**Firstly some background info on the Arduino Mega:**

I haven't used the Mega, but I've used the Uno, and have worked with a variety of ATmega microcontrollers.

First thing you need to know is that the Arduino Mega (or any other Arduino) is a board that uses the Atmel ATmega microcontrollers. The specific microcontroller used on the Mega is the ATmega1280 ATmega2560.

So if you are keen to learn more about your Arduino, a good place would be to look at the datasheet of the microcontroller itself. Just google ATmega1280 ATmega2560 datasheet.

However this might be a fair bit complicated, since you are new to the Arduino and microcontroller world.

A good place to start would be the Arduino website itself (but I suppose you've already looked at it).

**Now, regarding your question:**

I'm not sure what you are referring to as "additional i/o pins", but here's a quick rundown on what I/O pins are and used for.

As you may know I/O pins are used by the microcontroller to talk to the outside world. On the ATmega chips, most of these are GPIOs (General Purpose I/Os) that can be programmed to receive or send digital signals. Of these GPIOs some are used for PWM, and some may be used for some communication protocol. And of course there are analog input & reference pins, voltage supply, ground etc.

You can find all this information in the datasheet I linked above.

If you are curious how Arduino has routed the pins, you can have a look at the [schematic of the Arduino Mega](https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf) here.

If you also have a look at the Arduino website, they have a very good description on what each pin does: [Arduino Mega][1].

Look at "Inputs and Outputs".

  [1]: https://www.arduino.cc/en/Main/arduinoBoardMega


message:
Python PySerial with Arduino fails byte check

I'm struggling with my first steps with Python and PySerial. I have one Arduino which reads impulses from an electricity power meter, passes the counts over to another Arduino over an RF link and then sends the data over to an Raspberry Pi. The Arduino to Arduino communication works well. However the last step of passing this to the RPi fails.

The MeterValue from the Arduino side is an unsigned Long (32 bits) and therefore split in 4 pieces of 8-bit transmissions plus a frame start and frame end:

    [0x01] Frame start
    [0xMeterValueByte0]
    [0xMeterValueByte1]
    [0xMeterValueByte2]
    [0xMeterValueByte3]
    [0x04] Frame end

This is my Arduino code continuously sent to the RPi in debug purpose :

    void loop() {
    //static test loop
    Serial.write(0x01); //start frame
    Serial.write(0x00);
    Serial.write(0x00);
    Serial.write(0x02);
    Serial.write(0x04); //end frame
    delay(3000);

    }

This is my Python code:

    Import serial
    ser = serial.Serial('/dev/ttyACM0',9600)
    print("Connected to: " + ser.portstr)

    inputbuffer=[]
    inputbuffer = [0 for i in range(10)]

    while True:
        if ser.inWaiting() > 0:
            inputbuffer = ser.read(1)
            print "Byte received"
            print "Inputbuffer[0]: " + hex(ord(inputbuffer[0]))

            j = inputbuffer[0]
            print "j= " + hex(ord(j))

This check of the "j" parameter somehow fails:

            if (j == 0x1): #look for start of frame
                print "Start found\n"
                print "Filling buffer\n"
                while ser.inWaiting() < 5: #hold here until 5 bytes arrived
                    pass #proceed here
                inputbuffer +=ser.read(5) #read 5 bytes

                if inputbuffer[5] == 4: #check that the message has frame end
                    RXval = inputbuffer[1]
                    RXval |= (inputbuffer[2] << 8)
                    RXval |= (inputbuffer[3] << 16)
                    RXval |= (inputbuffer[4] << 24)
                    print "RXval: ", RXval
                else:
                    print "RX error, no frame end\n"
            inputbuffer = []

This is the Python output:

    Connected to: /dev/ttyACM0
    Byte received
    Inputbuffer[0]: 0x1
    j= 0x1
    Byte received
    Inputbuffer[0]: 0x0
    j= 0x0
    Byte received
    Inputbuffer[0]: 0x0
    j= 0x0
    Byte received
    Inputbuffer[0]: 0x2
    j= 0x2
    Byte received
    Inputbuffer[0]: 0x4
    j= 0x4
And then it repeats. Obviously the Python code doesn't realize j == 1. How should I handle the checking of the received bytes?

body:
I think the problem is that you can't count ;)

Spot the difference:

    0: [0x01] Frame start
    1: [0xMeterValueByte0]
    2: [0xMeterValueByte1]
    3: [0xMeterValueByte2]
    4: [0xMeterValueByte3]
    5: [0x04] Frame end

and:

    0: Serial.write(0x01); //start frame
    1: Serial.write(0x00);
    2: Serial.write(0x00);
    3: Serial.write(0x02);
    4: Serial.write(0x04); //end frame

Your receiver is looking for a pattern of 6 bytes, but your Arduino sketch is only sending a pattern of 5 bytes.

Your check for the start character is simple enough - you solved it fine a few lines above:

    print "j= " + hex(ord(j))

But you forgot to do something similar for the check:

    if (j == 0x1):

That should really be:

    if (ord(j) == 0x1):


message:
How much power can the Teensy 3.2 deliver to external components?

Can a teensy 3.2 deliver enough power to properly activate multiple servos by chance?

body:
No.  You should provide your own regulator or supply for the servos specified voltage.

This might be an original design, or an off-the-shelf "battery eliminator" intended for an R/C vehicle of similar needs.

Note that the teensy regulator's maximum input voltage is fairly low, and may be in the range of what more powerful servos expect, ie, you might be able to run the teensy regulator off of the servo supply.

Be sure to consider the possibility of brownouts - multiple active or stalled servos can consume a lot of power, and if your upstream supply is not "stiff" enough this can result in the voltage dropping low enough that control electronics misoperate or reset - granted that is less likely with the teensy than with a 5v MCU using a regulator with a higher voltage dropout.


message:
SIM800 or SIM900 library for Arduino

I have a SIM 800L module which I am using to send /receive SMS calls.

I just wanted to know whether there is any library suitable for the SIM800 for arduino. I don't need GPRS functionality . I see mostly the arduino shield library but not sure whether it works with the SIM800 module bought from aliexpress.

Can someone help me in get me a library which can be used for the SIM800 .I have tried a lot but not getting a simple library for the same.

Actual Issue :

I am able to make it work with the AT commands using the Serial3 in the arduino MEGA. But when i started integrating with the existing project of ESP8266 and DS3231 somehow the Serial3 read() is not working properly. I tested with Serial3.readString()/ Serial3.read() and all. The CNMI for the SIM800 is 2,3,0,0 which is to direct the incoming message to the Terminal.
If my project is having a simple loop with only Serial3.read, then all messages contents are read properly. If I include the other Serial2 readings which is for the ESP8266, then I am not able to read the full messages from Serial3.I have tried with timer to read serial from the Serial3 for 3-5 secs but now way it is working.

body:
Most likely, the Serial3 buffer is being overrun because you are not reading fast enough. That is why when you use a simple loop, everything works and you get the whole message; very little time passes between reads. The simplest solution to this is to increase the size of the Serial buffer to, maybe, 256 bytes. Search for `HardwareSerial.h` in your Arduino installation and look for the `#define`d variable `SERIAL_RX_BUFFER_SIZE` in the file near the top. Change its value to 256 and save. This should provide enough buffer space to store the entire SMS until you read it.
Alternatively you could change your CNMI settings to push only SMS notifications, which are a lot smaller in size, to the Arduino. Then you can parse the notifications, extract the SMS index and then request the SMS from the SIM800 using the index whenever you wish, making sure to read quickly (you will need to craft a `while` loop to do this efficiently, with timeouts and all).


message:
How to setup Uno + xbee shield 1.1 + wee wifi chip?

I am an absolute beginner with electronics and Arduino.
I have this hardware:

- arduino uno
- xbee shield 1.1
- wee wifi chip

I've tried to make them work (to connect my Uno to the Internet) but I can't find the right tutorial.

Are there good resources I should look at, or do you know how set this up?

body:
As far as the Wi-Fi and Uno is concerned, it's not too difficult. You should download its library for Arduino, which is available on Github and then try its example named *Wifi Client*.

In this example, change your SSID and password, and run serial terminal. It will show you that your Arduino is connected to Wi-Fi and it will also display your IP Address.

Now enter this IP address in your browser and it's like you are pinging your Wi-Fi shield.  Soon it will display your analog values. Just make sure your computer and your Wi-Fi chip are connected to the same Wi-Fi connections.


body:
I'd suggest taking this in small hunks. If you haven't done it already, your first step should be to get your development environment together. Use it to create and upload a simple test. The Blink sketch is a common place to start. There are excellent tutorials at the Adafruit site, the have a whole series for [getting started with the Arduino][1].

After you've gotten far enough with the basics to start feeling confident. Try searching for a tutorial for your project. You can often find them by searching on Google – try something like "arduino xbee shield tutorial" – look for descriptions that sound like what you want to do and try reading them. Another good place to look for tutorials is on sites that sell the hardware you're interested in using. For example Adafruit has [this tutorial][2] on getting started with the Xbee.

As you work through the tutorials, come back with more questions. As you get more experience it will be easier to ask specific questions and those are easier to answer :-)

[1]: https://learn.adafruit.com/lesson-0-getting-started/overview
[2]: https://learn.adafruit.com/xbee-radios/overview


message:
Declare for loop as an array of variables

My goal is to store the variable in the for loop as an array rather than as a single 'ultrasoundValue'. Can some one help me structure the code?

I have this code:

    int ultraSoundSignalPins[] = {5,7};
    int tx = 4;
    char *pingString[] = {"Ping1 ","Ping2 "}; // just something to print to             indicate direction

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

    void loop()
    {

     unsigned long ultrasoundValue;
     for(int i=0; i < 2; i++)
     {
       ultrasoundValue = ping(i);
       Serial.print(pingString[i]);
       Serial.print(ultrasoundValue);
       Serial.print("cm, ");
       delay(500);

     }
    }

    //Ping function
    unsigned long ping(int i)
    {
     unsigned long echo;

     pinMode(ultraSoundSignalPins[i], OUTPUT); // Switch signalpin to output
     pinMode(tx, OUTPUT);
     digitalWrite(ultraSoundSignalPins[i], LOW); // Send low pulse
     digitalWrite(tx, LOW);
     delayMicroseconds(2); // Wait for 2 microseconds
     digitalWrite(ultraSoundSignalPins[i], HIGH); // Send high pulse
     digitalWrite(tx, HIGH);
     delayMicroseconds(5); // Wait for 5 microseconds
     digitalWrite(ultraSoundSignalPins[i], LOW); // Holdoff
     pinMode(ultraSoundSignalPins[i], INPUT); // Switch signalpin to input
     digitalWrite(ultraSoundSignalPins[i], HIGH); // Turn on 0pullup resistor
     echo = pulseIn(ultraSoundSignalPins[i], HIGH); //Listen for echo
     return (echo / 29.1); //convert to CM then to inches
    }

body:
Make `ultrasoundValue` an array and use `i` as the index to it? Just like you have with all your other arrays?

You obviously know how to use arrays, since you have already been using them throughout your code.


body:
You don't even have to add any lines, just modify a couple!

    unsigned long ultrasoundValue [2]; //creates an array of unsigned longs of size 2

...and inside your for loop:

    ultrasoundValue[i] = ping(i);

It appears you are acquiring 2 separate ultrasound values. If you'd like to store multiple sets of these 2 values, you could use a two-dimensional array:

    unsigned long ultrasoundValue [10][2]; //an array of 10 pairs of long unsigned values

...and you could modify your for loop to have a pair of nested for loops:

     for (int i = 0; i < 10; i++)
     {
       for (int j = 0; j < 2; j++)
       {
          ultrasoundValue[i][j] = ping(j);
          //do whatever else
       }
     }