message:
Arduino PWM malfunctioning

I am controlling 4 motors using the PWM ports on an Arduino Uno (3,9,10,11). For some reason, the motor hooked up to port 11 doesn't move with my current code. I know it's a code issue because I can create a new basic code that just moves the motor and it works fine, but for some reason it doesn't in this code.

    #include <SPI.h>
    #include <Pixy.h>

    Pixy pixy;

    int personX = 0;
    int offCount = 0;

    void setup()
    {
      pinMode(3, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(11, OUTPUT);
      Serial.begin(9600);
      while (! Serial);
      pixy.init();
    }

    void loop()
    {
      static int i = 0;
      int j;
      uint16_t blocks;
      char buf[32];

      blocks = pixy.getBlocks();

      if (blocks)
      {
        personX = pixy.blocks[0].x;
      }

      if (blocks){
        Serial.println(personX);
        if (personX < 110){
          analogWrite(11, 130);
          analogWrite(3, 130);
          analogWrite(9, 250);
          analogWrite(10, 250);
        } else if (personX > 190){
          analogWrite(11, 250);
          analogWrite(3, 250);
          analogWrite(9, 130);
          analogWrite(10, 130);
        } else {
          analogWrite(11, 190);
          analogWrite(3, 190);
          analogWrite(9, 190);
          analogWrite(10, 190);
        }
        offCount = 0;
      } else {
        if (offCount < 1000){
          offCount = offCount + 1;
        } else {
          analogWrite(11, 190);
          analogWrite(3, 190);
          analogWrite(9, 190);
          analogWrite(10, 190);
        }
      }
    }

Also, when I take the motor and swap it with another, the old one works in the new PWM port, but the new one stops working once I put it in port 11.

body: Pin 11 is shared between both PWM and SPI. By activating SPI you've disabled PWM from working on that pin. Either use another PWM pin instead, or switch to software SPI on different pins.


sender: user

message:
Why is this spitting giberish instead of serial numbers?

#include <TrueRandom.h>

    void setup() {
      char* ss= (char*)TrueRandom.random(111111111,999999999);
      char* finalss;
      Serial.begin(9600);
      finalss[0] = ss[0];
      finalss[1] = ss[1];
      finalss[2] = ss[2];
      finalss[3] = '-';
      finalss[4] = ss[3];
      finalss[5] = ss[4];
      finalss[6] = '-';
      finalss[7] = ss[5];
      finalss[8] = ss[6];
      finalss[9] = ss[7];
      finalss[10] = ss[8];
      Serial.println (finalss);
    }

    void loop() {
      ; // Do nothing
    }
This is supposed to output a randomly generated number in this format nnn-nn-nnnn.
Updated Code (Doesn't seem to output anything):

    #include <TrueRandom.h>

    void setup() {
      String ss;
      ss = (String)TrueRandom.random(111111111,999999999);
      String finalss;
      Serial.begin(9600);
      finalss[0] = ss[0];
      finalss[1] = ss[1];
      finalss[2] = ss[2];
      finalss[3] = '-';
      finalss[4] = ss[3];
      finalss[5] = ss[4];
      finalss[6] = '-';
      finalss[7] = ss[5];
      finalss[8] = ss[6];
      finalss[9] = ss[7];
      finalss[10] = ss[8];
      Serial.println (finalss);
    }

    void loop() {
      ; // Do nothing
    }

sender: assistant

body:
Casting a number to a `char*` doesn't convert the number to a string. Instead it converts the number to a pointer and starts reading `char`s from that location.

Either pass the number to a `String` constructor, or pass it through `ltoa()`.

**EDIT:**

    String ss(...);

or

    char ss[11];
    ltoa(..., ss, 10);

Also, don't forget to allocate memory for `finalss` and NUL-terminate it.

    char finalss[12];
     ...
    finalss[11] = 0;


body:
I am really assuming you are doing this on a arduino, do you have the serial terminal switched on, you are putting that entire code in setup, means it executes only once and that maybe before you can get your serial terminal on.

So if you are putting it on setup, you need to push the reset button to get a number.

check the code at -
https://code.google.com/p/tinkerit/wiki/TrueRandom and see if that works

A better way to write your code may be -

    #include <TrueRandom.h>

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

      Serial.print(TrueRandom.random(111,999));
      Serial.print('-');
      Serial.print(TrueRandom.random(11,99));
      Serial.print('-');
      Serial.println(TrueRandom.random(1111,9999));

    }

    void loop() {
      ; // Do nothing
    }


body:
    void setup() {
      long longrand = TrueRandom.random(111111111,999999999);
      char ss[9+1], finalss[13+1];

      Serial.begin(9600);
      (void)ltoa(longrand, ss, 10);

      finalss[0] = ss[0];
      finalss[1] = ss[1];
      finalss[2] = ss[2];
      finalss[3] = '-';
      finalss[4] = ss[3];
      finalss[5] = ss[4];
      finalss[6] = '-';
      finalss[7] = ss[5];
      finalss[8] = ss[6];
      finalss[9] = ss[7];
      finalss[10] = ss[8];
      finalss[10] = '\0';

      Serial.println (finalss);
    }

    void loop() {
      ; // Do nothing
    }

- `TrueRandom.random()` returns a long, not a string, so you need to assign the value to a long variable while you translate it.
- Your code didn't allocate any memory for the arrays you tried to use, so the third statement does that. I made them larger than the number of characters you used because the range you gave to `TrueRandom.random()` is a set of 9-digit numbers. I don't know how you need to punctuate your numbers so I allocated `finalss[]` larger yet. You should confirm that the array sizes will be sufficient for your needs.
- The fifth statement, ltoa() converts a long to an ascii string in the `ss[]` array.
- I left your `finalss[x] = ss[x];' statements alone except to add the necessary NUL terminator at the end of `finalss[]`.

I haven't tested this but it compiled with no errors other than my not having `TrueRandom.h`. But it should get you a lot closer to (what it looks to me as if) you intended.


message:
Is this set up appropriate?

Hello Internet Arduino enthusiasts!

I'm totally new to Arduino and as my first project, I'd like to make a controller connected to computer A (the master) and computers B and C as 'slaves'.

The master would simply send commands as USB mouse and USB keyboard inputs to slave computers through an Arduino controller. Think of it as a hardware KVM switch (without the V(ideo)).

Now, I'm planning to work on that during the Christmas vacations, so I need to order the parts now to receive them in time.

I was thinking I could use these parts:

 1. Arduino Due (because it has the capability to send keyboard and mouse input)
 2. 2 SparkFun FTDI Basic Breakout - 5V, one for the mouse, one for the keyboard (per target computer) (https://www.sparkfun.com/products/9716) (because I can convert it to a 3.3v, what the Due is using)

Please consider:

 - The price is not really an issue for now.
 - I'm not worried to much about the programming.
 - I'll figure out how to make it work once I have the time and the items.
 - I know someone who has a starter kit from SparkFun, and there is an electronic store closeby, so I'm not worried about the wires.

Will I be able to make what I'd like with those basic parts, or am I missing something?

Thanks!

body:
You need:

- two MCUs that can act as USB devices (one per slave),

- some way of getting the commands from the master to the MCUs

That means two Arduino Dues (or Arduino Leonardos, or SparkFun ATmega32U4 breakout boards, etc.) and one USB device of some sort that you can talk to and have send commands to the MCUs.

And perhaps something to transport the commands from the master to the slaves, but you need to think about the programming for that first since the transport and the programming will be very closely connected.


message:
Where do serialport names come from?

I'm currently writing a tool that automatically detects connected arduinos and provides a one-button solution for flashing new firmware.
I've got a couple of arduinos at home (Diecimilla, Uno R3 SMD and some nanos from china) and each type presents with a different serial port name.

**Questions**

- Can someone explain where these port names come from?
- Can I assume that `/dev/cu.usbserial-A9UPDRZB` is, atleast in most cases, an arduino nano?
- Are there other ways to identify the type of the board?
- Is the name of the serial port some kind of hash generated from informations retrieved from the device?

body:
You cannot assume anything about serial port names. It's a choice of the operating system, and even if you find the algorithm, there's no guarantee it won't change in the future.

As a reference implementation, the [Arduino IDE 1.5.x][1] uses VID (Vendor ID) and PID (Product ID) to identify a board.

Because accessing such information depends on the underlying operating system, the IDE uses three strategies: on windows, it runs a program called ListComPorts.exe, on macosx it uses CLI tool `/usr/sbin/system_profiler`, on linux CLI tool `udevadm`

  [1]: http://arduino.cc/en/Main/Software#toc3


message:
Checking connection/ communication

Can I ping or “hello world” an Arduino.
Background:  My son and I bought a 3-D printer kit.
[(EZ-3D)][1]

We are having some issues talking with it.  (Well we can't talk at all.)  So we thought to upload the [firmware][2],

It’s an Arduino Mega 2560, and when we upload the Arduino times out… but it takes a minute or two.  Can I try some simpler program just to try and talk to the Arduino?

I’m almost a “virgin” Arduino user so be gentle.

  [1]: https://www.phoenix3dprinter.com/
  [2]: https://ez3d.freshdesk.com/support/solutions/articles/1000080546-uploading-firmware

body:
Adafruit has a good set of guides to getting started with arduino:
https://learn.adafruit.com/series/learn-arduino

The "[Blink](https://learn.adafruit.com/adafruit-arduino-lesson-1-blink)" program is the equivalent of "hello world".

When testing you probably should disconnect the Arduino from the 3D printer.


message:
Creating arduino library linking question

I know how to create my own arduino library and use it. I am using Xcode to create a c++ project. I have the arduino library files(Servo, Wire, Keypad, etc). If I want to include the Servo.h library file in my created library, how do I go about linking that? For some reason, I can't just add the Servo.h/.cpp files in my project because then I get other linking file problems that Servo.h references and are not linked in my project. Has anyone done this before?

body:
I can't speak for Xcode, but in general with Arduino IDEs (UECIDE excepting) if you use a library within another library, that library also has to be #included in the main sketch.  That is the only way most IDEs determine which libraries need to be compiled into the finished program.

That's one of the first targets I had for UECIDE - to enable fully recursive library compilation.  Any libraries found within the master header of a library will also be included for compilation - and any found in those libraries, etc.  It took a lot of work (and it's by no means 100% perfect), which is why so few others do it and leave it up to the programmer to ensure the inclusion of the right sub-libraries in their sketch.


message:
What are the fundemental differences of different Bluetooth modules for beginners?

I'm a beginner to microcontrollers and electronics, albeit not really to computers and programming.

Starting out with the Arduino, I came to a point whereby I'm really interested in getting my prototype to talk to a mobile device or a computer to send and receive data (for example, send sensor data or receive commands).

Looking out, I've found out that there are different bluetooth modules with varying pricing points. Further research into differences did not reveal much to me as being a beginner, I am struggling to understand what to look out for or how to choose.

**My question here is:**

What are the fundemental differences of different Bluetooth modules for beginners, such as:

 - HC-05
 - HC-06
 - HC-07

And what should one look for when buying a simple Bluetooth module for Arduino?

body: I don't really know the differences but I've used the HC-06 modules. They are slave-mode only but that is what you need to replace a hard-wired terminal to your Arduino, such as your PC and and a USB cable, with a Bluetooth terminal. That probably covers 99% of cases where an Arduino or other MCU-based device needs to communicate to a PC or tablet that already has Bluetooth built in. For device to device communication, one of them would have to be a master, and I think that requires an HC-05.


body:
As far as simplicity is concerned, HC05 would be the way to go. It is by far the most popular and there are a tonne of tutorials on using it (just a quick google search).
As for the differences:

- The HC-05 module can build a connection to other modules. E.g. a Robot being a master and connecting to slave bluetooth module. Or in slave mode to make a wireless bridge to a notebook.

- The HC-06 module only can be a slave. This makes it only useful for say connecting a notebook as a master to a robot with a slave module e.g. for a wireless serial bridge.

- As for the HC07, support seems low so I would recommend sticking with HC05 or HC06

At the end of the day it comes down to your requirements. If you are only wanting to talk between the phone and your arduino than the HC06 would work fine, however if at some point in time you want to talk to another arduino, than hc05 would be the way to go.


message:
Arduino DUE and optocoupler 4N25

I'm using an Arduino Due board with an optocoupler 4N25 to simulate a button pressed.
I have to open and close a circuit that drive an actuator. In that circuit, when connected, with the tester I'm measuring 6V.

I connect the anode to the pin 12 and the cathode in series with a 150-ohm resistor to ground, and Collector and Emitter from optocopupler to the circuit (and a normal Blink example with the pin 12).

When optocoupler is fired on and off respectively with a tester I measure 0V and 1.7V in the arduino part, and 4V and 6V.

This is not enough and the actuator is always run. I'd like to read 0-6V instad of 4V-6V. Does this depends on how much current goes to the anode/cathode of the optocoupler? Do I have to change the resistor in the arduino part? Any kind of advice? What can I do?

I don't want to use relay because I have read that in respect to a relay they are faster, smaller, longer-lived and quieter.

![enter image description here][1]

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

body:
It sounds like the 4N25 opto-coupler on its own can't do what you need because it's not designed to directly make/break a connection between a power source and its load (i.e. it isn't functionally equivalent to a relay).

Internally, the switching functionality is provided by an NPN photo-transistor. A typical open collector usage would be something like this:

![Example of an opto-coupler circuit][1]

<sub>*(Image copyright Lewis Loflin: http://www.bristolwatch.com/ele/opto_isolated.htm)*</sub>

The switch (`S1`) and the power source (`Vi`) on the left would be your Arduino. All the connections on the right would be part of your device (the actuator).

As you can see, you need 3 connections on the right: voltage source (`Vcc`), ground, and the output (`Vo`, which goes to your device). The circuit basically works by pulling the output (`Vo`) either up to `Vcc` to turn it on, or down to ground to turn it off.

It looks like all you have is `Vcc` and `Vo`, so this kind of configuration won't work. (Don't try to use the ground from your Arduino instead. That could cause various other problems.)

It should be possible to setup additional circuitry to act more like a Solid State Relay, but without a ground reference point it can be harder than it sounds. A mechanical relay might be the easiest option.

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


message:
How to choose between AM230x and DHT22 temperature and humidity sensors?

I'm looking forward to getting an accurate humidity and temperature sensor.

Right when I decided to go with a DHT22 module, I saw AM230x (AM2301, for example).

 - How do I choose between DHT22 and AM2301?

body:
The AM2301 and the DHT22(AM2303) are similar in a number of ways, both in price, specs, ranges and power consumption. They are usually cased a bit of a differently, with the DHT22/AM2303 being packaged with four pins (only three are in use), and the AM2301 (formerly called DHT21) is packaged with three cables and a small plug inside of the case.

I would choose based on the usage, if I'm going to use the sensor on a breadboard or a socket (going for the DHT22 pinned version), or if I'm going to have it standalone (the cabled one).

Here are links to the datasheets:

https://kropochev.com/downloads/humidity/AM2301.pdf

https://www.adafruit.com/datasheets/DHT22.pdf


body: The AM2302 has a built-in pull-up resistor, whereas the DHT22 does not. Apart of that and de different housing they should be technically identical.


message:
What is differences in usage between a HC-05 bluetooth module and a Zigbee HC-05 module?

I have seen commercial Xbee / Zigbee clones using HC-05 integrated inside.
Are they any different than regular HC-05 bluetooth modules?

 - What is differences in usage between a HC-05 bluetooth module and a Zigbee HC-05 module?

body:
Bluetooth and Zigbee are two different communication protocols. The Xbee clones you are talking about a called [BTbee][1].

As far as im aware the BTbee modules are the same hardware/firmware wise as the hc05/hc06 modules. The only difference being the BTbee modules are in the Xbee footprint, allowing you to plug them into Xbee/Zigbee sockets.

  [1]: http://www.elecfreaks.com/store/bluetooth-bee-hc05-btbeehc05-p-171.html


message:
Did I accidentally short something? My Arduino UNO board does not communicate with the computer anymore

I had my sketch uplaoded and everything was working fine when I tried connecting one of the input pins(pre-configured as digital INPUT) to 12V, just to see if this was being read as a HIGH as well.
It seems to have done something and the board stopped working. Moreover, all pins seem to be stuck at HIGH!

So far Ive tried the following:

* reset button: doesnt help
* re-upload: doesn't work - it says not in sync

Physically nothing seems to be burnt/blown. What am I missing? Have I fried my board? I hope not. PS: It was connected to a 12V external power source

Any thoughts?

body:
Unfortunately, the arduino's input pins are not tolerant of 12 volts, You have likely caused permanent damage to the chip =(. There is a regulator that makes it capable of being *powered* by 12 volts, but the input pins are different.

If you look at table 30-1 on the datasheet for the Uno's controller [here][1] you can see the input characteristics. The arduino is powered at 5v, so the max digital input voltage is 5.5v

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf


message:
Which Arduino board to buy?

I need an Arduino Mega 2560 (that is the one that has more pins). I went to eBay and there are a lot of different boards. I'm thinking of buying an [ATmega2560-16AU CH340G MEGA 2560 R3 Board + Free USB Cable for Arduino
][1]. Is this one good? I mean, does it do the work? Is it compatible with the Arduino IDE? Anything I need to know?

  [1]: http://www.ebay.com/itm/201197139954

body:
It's a counterfeit, and counterfeits are never a good choice. [Scroll this down][1] to the Pricing paragraph to see where your money goes when you buy an [official board][2].

  [1]: http://arduino.cc/en/Products/Counterfeit
  [2]: http://arduino.cc/en/Main/Buy


body:
There is no way to know the quality of the Arduino clones on eBay. They may be fine but you never know.

I recommend buying an official Arduino from one of the [official distributors](http://arduino.cc/en/Main/Buy).

There are good quality Arduino compatible boards like the SparkFun Redboard or the Adafruit Trinket. But these are not made to look like official Arduino boards. (Neither of these would work for you since they don't have as many pins as the Mega)


body:
The Chinese boards generally work just fine with the official Arduino IDE. One thing to be careful for though is the bootloader. Most the time the Chinese vendor had written a custom bootloader, which may make certain pins behave funny. e.g. a common thing is for pin 13 (the default LED) is permanently high.

I would be very cautious ordering these boards though. Most if not all of these breech the terms of the open source license which Arduino is released under. Besides that, ordering these boards you are supporting the Chinese slave labour gone into manufacturing this board for extremely low prices.

Why not purchase the official Arduino boards? Not only do you get quality boards, but you are also supporting the open source community, and ethically manufactured electronics.


body:
The Arduino creators have spelled out their position on clones in a fairly lucid [blog post](http://blog.arduino.cc/2013/07/10/send-in-the-clones/) a few years ago.

Your board comes pretty close to being a legitimate clone, but the claims about being manufactured in Italy are almost certainly false and possibly illegal.

I bought a CH340G based board myself, and apart from needing to install a different driver, it's pretty close to the original (There are a few projects that reprogram the 16U2 on a real Arduino board, but the vast majority of projects use the 16U2 as a straight serial converter, and the CH340G seems to do that job OK).

As other answers have pointed out, clone makers don't contribute to the community, so consider buying a real board occasionally. On the other hand, Arduino Mega clones are literally 25% the price of the original, so for that board, going with a clone is certainly tempting.


body: You could buy an official board, but if you're worried about the price, I wouldn't go for the EBay ones. There are other better clones out there. For example, I know that SparkFun makes their own Arduino Uno board, and while it's not called the Uno, it works exactly like it's supposed to, without any surprises. From what I remember, it's cheaper than the official Uno too.


body: I bought some of those boards and have had no problems with them.  They are not as some claim, counterfeit boards.  If they were, that would mean that the 'arduino' boards are not open source.  I have also never seen any boards claiming to be built from italy.  They are specifically labeled "Made In China".


message:
Arduino Uno to drive 2 unipolar stepper motors

I need to use two stepper motors to move microscope positioning knobs in the X/Y direction. The stepper motors I have are unipolar and are 6V rated (I think).

I know it's possible to drive a unipolar stepper motor via a ULN2003 using an Arduino Uno. I know I can wire it using the 2-wire or 4-wire method.

But my questions are:

Is it possible to drive 2 of them? What are the modifications I will need to make to the circuit? Will this harm my Arduino? Do I need a stepper motor shield?

body: I'd suggest to have a look at the [EasyDriver](http://www.schmalzhaus.com/EasyDriver/index.html) stepper motor drivers developed by Brian Schmalz. They are easy to set up and do support **microstepping**, which might be interesting for a more fine control of the microscope.


body:
No problem. Just use two ULN2003 chips, one for each stepper.

No need for a motor/stepper shield on these unipolar steppers.

It will not harm the arduino (if wired correctly).


message:
Arduino Piccolo Example Script Error

So I am trying to make an audio visualizer from this tutorial listed [here.][1]

  [1]: https://learn.adafruit.com/piccolo/overview

So I downloaded all the files needed, and downloaded the code. But when I try to verify it, I get this Error:

    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp: In constructor 'RobotControl::RobotControl()':
    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:8: error: 'LCD_CS' was not declared in this scope
    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:8: error: 'DC_LCD' was not declared in this scope
    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:8: error: 'RST_LCD' was not declared in this scope
    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp: In member function 'void RobotControl::begin()':
    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:18: error: 'MUXA' was not declared in this scope
    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:18: error: 'MUXB' was not declared in this scope
    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:18: error: 'MUXC' was not declared in this scope
    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:18: error: 'MUXD' was not declared in this scope
    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:19: error: 'MUX_IN' was not declared in this scope
    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:22: error: 'BUZZ' was not declared in this scope
    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Robot_Control\ArduinoRobot.cpp:25: error: 'Serial1' was not declared in this scope
    core.a(main.cpp.o): In function `main':
    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\hardware\arduino\cores\arduino/main.cpp:11: undefined reference to `setup'
    C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\hardware\arduino\cores\arduino/main.cpp:14: undefined reference to `loop'

I've looked this up before, and couldn't find anything on it. So I came here for a last resort.

Any ideas?
-

EDIT: So I reinstalled the folders, and renamed the LED folder but now I get a new error:

Piccolo:112: error: 'Adafruit_BicolorMatrix' does not name a type
Piccolo.pde: In function 'void setup()':
Piccolo:130: error: 'matrix' was not declared in this scope
Piccolo.pde: In function 'void loop()':
Piccolo:168: error: 'matrix' was not declared in this scope
Piccolo:168: error: 'LED_RED' was not declared in this scope
Piccolo:169: error: 'LED_YELLOW' was not declared in this scope
Piccolo:170: error: 'LED_GREEN' was not declared in this scope
Piccolo:207: error: 'LED_OFF' was not declared in this scope
Piccolo:210: error: 'LED_OFF' was not declared in this scope

EDIT 2: Deleted Robot_Control and got this error:

In file included from Piccolo.pde:34:
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Adafruit_LEDBackpack/Adafruit_LEDBackpack.h:94: error: expected class-name before '{' token
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Adafruit_LEDBackpack/Adafruit_LEDBackpack.h:103: error: expected class-name before '{' token
C:\Users\ted\Desktop\Arduino_Sandbox_Windows_01\Arduino\libraries\Adafruit_LEDBackpack/Adafruit_LEDBackpack.h:112: error: expected class-name before '{' token
Piccolo.pde: In function 'void loop()':
Piccolo:168: error: 'class Adafruit_BicolorMatrix' has no member named 'fillRect'
Piccolo:169: error: 'class Adafruit_BicolorMatrix' has no member named 'fillRect'
Piccolo:170: error: 'class Adafruit_BicolorMatrix' has no member named 'fillRect'
Piccolo:207: error: 'class Adafruit_BicolorMatrix' has no member named 'drawLine'
Piccolo:210: error: 'class Adafruit_BicolorMatrix' has no member named 'drawLine'

body:
As I mentioned in the comments, reinstalling/updating all your 3rd party libraries to the latest versions is probably the first thing to try. Updating the IDE itself may also help.

If that hasn't worked then a forum topic here seems to describe the same kind of issue: http://forum.arduino.cc/index.php?topic=168854.0

One of the users seems to have tracked the problem down to a couple of Adafruit libraries. He suggests the following:

> 1) Delete the folder "Robot_Control" from Program
> Files\Arduino\libraries\
>
> 2) Make sure, that the two Adafruit folders in the same folder are
> named Adafruit_GFX and Adafruit_ST7735. I had them named "AdafruitGFX"
> and "AdafruitST7735", but that was wrong.

Deleting the `Robot_Control` folder doesn't sound like an ideal solution to me, but perhaps there's an incompatibility which can't be easily fixed. Unfortunately, the Arduino IDE handles libraries in a slightly strange way, so weird problems can happen from time to time.


message:
analog serial read values are not equal

I have not used the Arduino in over 2 years and have forgotten a bunch of stuff I was wondering if someone could help me out. I have two analog sensors both the same connected to the appropriate analog pins. I am getting a read on the serial monitor and when i test the sensors the values are changing so i know the circuit is correct and everything is in the right place. I just have an issue with my code.

    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue1 = analogRead(A0);

      // print out the value you read:
      Serial.println(sensorValue1);
       //Serial.print("val1 = " );
      Serial.print(sensorValue1);
      Serial.print(" ");

      delay(1000);        // delay in between reads for stability

       // read the input on analog pin 1:
      int sensorValue2 = analogRead(A1);

      // print out the value you read:
      Serial.println(sensorValue2);
      //Serial.print("val2 = " );
      Serial.print(sensorValue2);
      Serial.print(" ");
      delay(1000);        // delay in between reads for stability

     }

once i view this in the serial monitor it is not organized and the sensorvalue1 is skipping over to the next line. I would appreciate the help.

![This is the serial output on the serial monitor][1]

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

There are two sensors so there should be two values but in the picture the values are all messed up i would ideally like it to give me a two seperate values one for each sensor

val1= sensorvalue1
val2= sensorvalue2

body:
Try something like this

    void loop() {
      // read the input on analog pin 0 and 1 with delays for stability:
      delay(1000);
      int sensorValue1 = analogRead(A0);
      delay(1000);
      int sensorValue2 = analogRead(A1);

      // print out the value you read:
      Serial.print("val1 = " );
      Serial.print(sensorValue1);
      Serial.print(" val2 = " );
      Serial.println(sensorValue2);

     }


body: The problem here seems like you are writing the value with a println(), and then again the value without new line but space. Then you write value2 with an ending newline and again value2 without newline. In your output there is also a string that does not match up anywhere in the code you posted. Double check what you are uploading and check if it has error.


message:
Can I set the Arduino board type in code

When I've come back to Arduino programming after a spell doing other things, I keep forgetting that I last experimented with a different type of board and get a "avrdude: stk500_getsync(): not in sync: resp=0x00" error.

I have one sketch which will always be compiled and uploaded against a specific piece of hardware. Therefore, I would like to specify the board type and preferably COM port as well, in my sketch.

Can it be done?

body:
Yes you could do this, but you won't get much support from the Arduino libraries. From what I have used, the board type is evaluated at library compile time.

But if you are willing to delve through the datasheets for all the boards you want to support, then writing a board-agnostic driver should not be impossible.


body:
No, it cannot. Neither the compiler invocation nor the subsequent upload examine the code for the hardware in use, so there is no way of doing what you are asking.

What you can do is to create entries in a new `boards.txt` and `programmers.txt` using an existing core that specify all the parameters, and all you would have to do is select them in the IDE for everything to be set at once. See Google Code/Arduino/Platforms for more information.


message:
Is it possible to use ESP8266 modules interchangeably?

I discovered that there are multiple types & versions of `ESP8266` modules.

I'm wondering:

 - Build my application around one type (eg ESP-03) and in future swap the module with another (ESP-07), continuing to use the same library and code?

Given the lack of information online, I couldn't find an answer for this online.

body:
yes they are interchangeable since they all use the same chip (esp 8266). However the pin outs of the different modules can (and will be) laid out different. So you have to watch out that your wires are connected to the correct pads on the module.

Also mind that different esp8266 modules can be (stock) loaded with different firmware. If you are using the AT firmware in your current arduino project it can be necessary to flash your new esp8266 module with the same firmware. If you are not sure how to do this you might have a look to the [esp8266][1] forum

  [1]: http://www.esp8266.com/


body:
Well...
Yes, but... **mostly** only if you are using the simple serial lines(rx and tx) to communicate with it and only using the AT flash image.

Just as a for-instance:
The ESP8266-01 and ESP8266-02 have three and two IO pins (respectively) that are reprogrammable.
The ESP8266-03 has seven IO pins.
The others have different amounts of pins found on this page:
http://hackerspace.pbworks.com/w/page/88183850/ESP8266

 So if the program you use to flash the module uses more pins then you have to use the module that has the proper amount of IO pins or rewrite the flash image.

Instructions for compiling a toolchain to write and flash your own flash images to the ESP8266-XX module are found on this page:
https://github.com/esp8266/esp8266-wiki/wiki/Hardware_versions


message:
Is the supply voltage made available anywhere on the Arduino Uno Board?

I need to power an OpAmp based circuit that will be connected to my Arduino Uno input. Since I have a 12V adapter for the Arduino board, I want to draw power from it for this opamp(LM358).

Does anybody know if there is any way I can do this from the Arduino board(pins?)is as opposed to having to solder wires directly to the bottom of the DC jack?

body: The `Vin` pin is available (next to `Gnd`) pins.


message:
What should the frequency reading of the SPI clock be with this code?

My Extech EX330 multimeter is reading 3.439Mhz on the pin 13 on my Arduino Uno running the following code. Is the reading correct? If the divider is 2, shouldn't I get 8 Mhz (16Mhz / 2)?

        #include <SPI.h>
    void setup()
    {
      pinMode(13, OUTPUT);

      digitalWrite(13, HIGH);
      SPI.begin();
      SPI.setClockDivider(SPI_CLOCK_DIV2);

    }
    void loop()
    {

      byte pot = B0;
      SPI.transfer(pot);                        //  Do SPI transfer of variable pot
    }

body: No, because neither the allocation and assignment of `pot` nor the call to `SPI.transfer()` come for free. And the time taken by both slows the average frequency down to about the measured value.


body:
Yes, the clock speed should be (and most probably is) 8 MHz.  However, you're not generating an 8 MHz clock.

What you are in fact generating is 8 clock pulses of 8 MHz, then you have a delay while it deals with the rest of your code, and then it generates another 8 clock cycles of 8MHz.

The overall frequency is evidently sensed as 3.439 MHz.

To generate a pure 8 MHz clock you would have to use a different transfer method. I don't know if the 328P has DMA available, but if it does, that would give you much faster transfers.  Also, you could write a more non-blocking version of SPI.transfer().

The normal SPI.transfer() first starts the transfer, then waits for the transfer to finish, and returns the results of the transfer.  If you're only interested in transmitting, and not receiving, or the transmitted and received data don't need to c correlate completely, you can instead change the order of how it works:

1. Wait for there to be no transfer in operation
2. Store the result of the last transfer
3. Start the new transfer
4. Return the results of the last transfer.

That way it runs much smoother as it's doing the current transfer at the same time as running your other code.


message:
"void does not name a type"

Hi I'm new at this and can't figure out why I get this error "void does not name a type" on lines 3,5,8,26

    // _2-5 set Debounce Button
    const int BUTTON=2;
    const int LED=9;
    boolean lastButton = LOW;
    boolean currentButton = LOW;
    boolean ledOn = false;

    Void setup()
    {
      pinMode (LED, OUTPUT);
      pinMode (BUTTON, INPUT);
    }

    boolean debounce(boolean last)

    {
      boolean current = digitalRead(BUTTON);
      if (last != current)
      {
        delay(5);
        current = digitalRead(BUTTON);
      }
      return current;
    }

    Void loop()
    {
      currentButton = debounce(lastButton);
      if (lastButton == LOW && currentButton == HIGH)
      {
        ledOn = !ledOn;
      }

      lastButton = currentButton;
      digitalWrite(LED, ledOn);

    }

body:
I thing the problem is not "void does not name a type", but "Void does not name a type".  Subtle difference:

    Void setup()

should read:

    void setup()

The same on

    Void loop()

should be

    void loop()

Watch those caps - C is case sensitive.


message:
Yun as a Conventional Wireless Access Point

I want my YUN to act as a server in a client/server architecture so students can control their wifi robots via their desktops. I can plug the YUN directly into an ethernet port on our network and want to have robots communicate with it through a client/server architecture. Can somebody steer me in the right direction?

body:
Check out [this project][1], made by @Vadorequest the early days of the Yun: he hacked a car to control it via his smartphone. There's a [nice video][2] on youtube.

  [1]: https://github.com/Vadorequest/AAD1
  [2]: https://www.youtube.com/watch?v=amPQWXRpA-A


message:
Get USB host controller serial number or ID using Teensy or other HID devices

I have a [Teensy][1] board and would like to know if there's a way to get a serial number (or any other kind of ID that is preferably unique) of the **host** controller that I plug my Teensy into. E.g. can I get any unique identification numbers of my Macbook's USB controller when I plug my Teensy into it? C/C++ code examples for Teensy would be highly appreciated.

  [1]: https://www.pjrc.com/teensy/

body:
Nothing in the USB spec requires the host to provide any sort of identification to connecting devices. The standard way of implementing what you want consists in writing a custom driver which communicates the necessary information to the device. If installing a custom driver is not an option, all you can do is try to detect the OS by observing what it does during the enumeration process. Such identification will not be reliable (enumeration process can change after an OS update) and by no means unique.

Note that if your goal is to make sure the host is *trusted*, a simple ID will not be enough as it can be easily spoofed. You'll have to implement some sort of authentication scheme, e.g. [challenge-respose](https://en.wikipedia.org/wiki/Challenge–response_authentication).


message:
Ultrasonic PING: multiple trig on single dig. pin

This may seem a little stupid, i apologize  if so as i'm new to electronics/arduino.

I have 4, 4-pin ping sensors. I'm running out of available pins on my UNO.

I had a ponder & wondered if it was possible to link all 4 sensor's trig pins to a single digital pin, with the echo pins assigned to their own pin. In my head, on each sensor call (sorry i'm used to programming terms) all 4 sensors would send a pulse, then only the sensor (or echo pin) in question would be read. Is that plausible? each ping sensor is about 20-30 cm separated, but facing internally, in a spiral downwards.

body:
I was able to achieve the result using my suggested method in the question.
As BrettAM stated, the signals are wasted on the other 3 pins when checking 1.
This solution was suitable as a proof of concept


message:
4 bit to Decimal Converter IC

im using arduino and im out of pins.

I need something like a decoder but the problem is that the decoders only change one output pin I.E. for 0011 the output will be 0001000000000000 what i need is to have the first outputs on I.E for 1000 the output will be 111111111000000000 i basically need to light up to 16leds and im out of pins so i was wondering is there is any IC that does this for me if i have 1111 it will output 16 ones.

body:
You can use one (or more, daisy-chained) **shift register** for that.

It will normally take you 3 pins and provide 8 outputs, or 8n where n is the number of chained shift registers still using only 3 Arduino pins.

One example of a shift register that fits your situation is the **74HC595**.

On Arduino, you can use `shiftOut` function to help handle those ICs.


body:
You could use the MCP23017 an i2c 16 input/output port expander. ([datasheet](http://www.adafruit.com/datasheets/mcp23017.pdf))

It allows you to control 16 I/O pins via a simple I2C interface (only 2 pins needed).  And an [Arduino library](https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library) exists for it.


message:
Using displays with Arduino Uno

Does anybody know if there is any documentation available online on basic information about using displays with Arduino Uno? I've never used displays before and would very much appreciate some basic information on the different types etc..

Any information that can help me choose what display I want to buy for my next project will be helpful.

for ex: Right now I don't even know what a shield is in context to a display and whether or not I should look for one in my purchasing my display.

body:
The Arduino website has a [list of LCD displays][1] and link with more information about each one. For controlling the display you may want to look at Arduino's [LiquidCrystal Library][2].

If you are looking for a step by step guide for using a lcd display with the Arduino, there is a [nice guide on Adafruit][3].

  [1]: http://playground.arduino.cc/Code/LCD
  [2]: http://www.arduino.cc/en/Reference/LiquidCrystal
  [3]: https://learn.adafruit.com/adafruit-arduino-lesson-11-lcd-displays-1/


message:
Arduino LCD Display drawing image issue

I am playing with 3,5" (400x240) TFT display which is placed into Arduino Mega 2560 R3 board.

My final *goal* is taking .raw data from SD card and drawing it on display.

What I have done so far:

**-** My **drawing** method in the sketch:

    void LoadImage(File& file)
    {
        for (int y = 0; y < SCREEN_HEIGHT && file.available(); y++) {
            uint16_t buf[SCREEN_WIDTH];
            for (int x = SCREEN_WIDTH - 1; x >= 0; x--) {
                byte l = file.read();
                byte h = file.read();
                buf[x] = ((uint16_t)h << 8) | l;
            }
            myGLCD.drawPixelLine(0, y, SCREEN_WIDTH, buf);
        }
    }

**-** For reference **drawPixelLine** method's implementation from UTFT library:

    void UTFT::drawPixelLine(int x, int y, int sx, uint16_t* data)
    {
     unsigned int col;
        cbi(P_CS, B_CS);
        setXY(x, y, x+sx-1, y);
        for (int tc=0; tc<sx; tc++)
        {
            char* p = (char*)&data[tc];
            LCD_Write_DATA(*(p + 1), *p);
        }
        sbi(P_CS, B_CS);
    }
    void UTFT::setXY(word x1, word y1, word x2, word y2)
    {
     if (orient==LANDSCAPE)
     {
      swap(word, x1, y1);
      swap(word, x2, y2)
      y1=disp_y_size-y1;
      y2=disp_y_size-y2;
      swap(word, y1, y2)
     }
      LCD_Write_COM(0x2a);
        LCD_Write_DATA(x1>>8);
        LCD_Write_DATA(x1);
        LCD_Write_DATA(x2>>8);
        LCD_Write_DATA(x2);
        LCD_Write_COM(0x2b);
        LCD_Write_DATA(y1>>8);
        LCD_Write_DATA(y1);
        LCD_Write_DATA(y2>>8);
        LCD_Write_DATA(y2);
        LCD_Write_COM(0x2c);
    }
*My current rendering:*

![current result][1]

*Desired image:*

![enter image description here][2]

*TFT Lcd and Mega Board*
![enter image description here][3]

**UPDATE1**

I ran henningan test from utft library, drawing sin/cos graph and simple squares

![enter image description here][4]

Here is attempt to render yellow square 100x100 raw data

![enter image description here][5]

  [1]: https://i.stack.imgur.com/V82Vh.jpg
  [2]: https://i.stack.imgur.com/iVXZg.jpg
  [3]: https://i.stack.imgur.com/eAa2P.jpg
  [4]: https://i.stack.imgur.com/5bZe0.jpg
  [5]: https://i.stack.imgur.com/F5k4J.jpg

body:
I'have the same LCD from mcufriend and it doesn't work with original UTFT library.

Try modified version from https://github.com/dgolda/UTFT and use:

    myGLCD(NIC35WS,38,39,40,41); //3.5" TFTLCD for arduino 2560 from mcufriend.com


message:
4 channel relay module reversed? Or is it my code?

So I am designing a simple project where my Arduino reads analog values from a potentiometer, or rotation sensor, as it is called on EBay, and uses that value to determine how many relays to close. I am connecting 4 digital pins to the relay module, and powering it with a constant digital signal from pin 2.

Here is my code:

    //set up the pins for activating each relay on the module
    #define in1 13
    #define in2 11
    #define in3 10
    #define in4 9
    #define power 2      //set up the power pin for the module

    void setup(){
     Serial.begin(9600);
     pinMode(in1, OUTPUT);
     pinMode(in2, OUTPUT);
     pinMode(in3, OUTPUT);
     pinMode(in4, OUTPUT);
     pinMode(power, OUTPUT);
     digitalWrite(power, HIGH);        //for power to the relay module
    }

    void loop(){
     float rotationValue = analogRead(A0);          //read raw value from potentiometer
     float percentValue = rotationValue / 10.23;       //convert the value to 0%-100%
     Serial.println(percentValue);                  //print it out on screen
     if(percentValue >= 0.00 && percentValue <= 1.00){         //all relays off
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
     }
     else if(percentValue > 1.00 && percentValue <= 25.00){        //relay #1 on
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
     }
     else if(percentValue > 25.00 && percentValue <= 50.00){           //relay #1, #2 on
      digitalWrite(in1, HIGH);
      digitalWrite(in2, HIGH);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
     }
     else if(percentValue > 50.00 && percentValue <= 75.00){     //relay #1, #2, #3 on
      digitalWrite(in1, HIGH);
      digitalWrite(in2, HIGH);
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
     }
     else if(percentValue > 75.00){             //all relays on
      digitalWrite(in1, HIGH);
      digitalWrite(in2, HIGH);
      digitalWrite(in3, HIGH);
      digitalWrite(in4, HIGH);
     }
    }

Ok, here's the problematic part. After I upload the program onto the board, when I set the potentiometer to the 0 position, all relays are on. And when I twist it to the 100 position, which is maximum, all relays are off. Although it is usable, what's weird is that when I start from 100 and twist it back toward 0, the relays will activate, but in the opposite order. So relay #4 will activate, then #3, then #2, and then #1, and all four are on when I reach 0. Is it something wrong with my code? I've checked and rechecked, and even checked with a different project where I connect the pins to LED's. And they work normally. But when I connect up the relay module, it's reversed. Any ideas?

Here is the relay module: http://www.miniinthebox.com/4-channel-relay-module-with-optocoupler-5v_p903429.html?currency=USD&litb_from=paid_adwords_shopping&gclid=Cj0KEQiAts-kBRCbgrXc1rnXw7MBEiQAnFqTdph_qI5n7rrpW7gZaxafVVkeWitQlN8FUSUJzdsV2JwaAlBA8P8HAQ

And here is the potentiometer: http://www.ebay.com/itm/Potentiometer-Sensor-module-Rotation-Angle-Sensor-Arduino-competible-/251656942542

I mean, right now I'm even thinking that the relay module may be labeled incorrectly, that the numbers are printed the wrong way. But it could be my fault, most likely.

Thanks for any help.

body: All the relay boards I've come across are 'active low' i.e. as you've discovered bringing the control pin down to earth activates the relay. As an aside just be careful that the arduino has enough juice to power the relays, a separate supply is normally required if these are coil rather than ssr type relays


message:
PWM signaling with Arduinos: What is the reason for the ground connection?

*This may sound like a very dumb question and I apologise in advance.*

I've gone through reading about PWM and working on some example sketches to control PC fan speeds using PWM and Arduino.

In all documents I read, it is mentioned that "PWM is a signal".

**My questions:**

1. Is PWM **really** a signal? To me, it looks like an electric current turned on and kept on for a certain time, then off for a while repeatedly. What makes this a "signal"?

2. If PWM is a signal, why do we need to connect the Ground from Arduino to the ground of the device to which "PWM signal" is being sent to?

This is confusing me because in my mind, for example, radio signals do not need a ground connection. The signal comes and gets read.

body:
> Is PWM **really** a signal? To me, it looks like an electric current turned on and kept on for a certain time, then off for a while repeatedly. What makes this a "signal"?

At the most basic, it is a signal because we call it such. Even a constant voltage can be a signal, signalling that e.g. a window has not been broken. A PWM signal indicates that we want to apply a certain fraction of full power to a load.

> If PWM is a signal, why do we need to connect the Ground from Arduino to the ground of the device to which "PWM signal" is being sent to?

Because it is a voltage-based signal, and ground serves as the reference for this voltage. Voltage only exists *between* two points.

> This is confusing me because in my mind, for example, radio signals do not need a ground connection. The signal comes and gets read.

Radio signals are photon-based; the oscillation of photons at a given frequency being broadcast from a location are what define the signal. Since frequencies are absolute, they can be discriminated without a (relative) reference.


message:
Using an Ethernet Shield and a tlc5940 together

I have am using an Arduino Uno R2 and [TLC5940][1] to control a bunch of RGB LEDs. I want to add an Ethernet Shield R3 so that I can control the LEDs over a web-interface. However, the ethernet shield and TLC5940 use many of the same pins. Can I use them together? How?

  [1]: http://playground.arduino.cc/Learning/TLC5940

body:
When using multiple SPI devices the normal way to have them share a bus is to assign them distinct slave select lines. The problem here is that although the '5940 libraries use SPI to send data to it, the '5940 is not actually a proper SPI device and so lacks any sort of slave select line.

All is not lost, however. Since the '5940 responds only to SCLK (and GSCLK of course, but you should be running that one separately) all you need to do is inhibit it while nSS for the Ethernet module is active. This can be done with just a little bit of external circuitry. Since nSS must be high in order for the Ethernet module to be inactive, we can AND SCK with nSS to derive SCLK from it.

Using a 74HC08 for this would work, although it leaves 3 of the gates unused. A 74HC02 will let you do it with no wasted gates, but with a slightly higher propagation delay.

And of course, the requirement to clock in the grayscale data before the grayscale cycle completes is still there; properly interleaving this with the Ethernet communications is left as an exercise for the reader.


body:
You can do this with out any additional hardware by putting the TLC5940 to BITBANG mode instead of SPI mode and making the Ethernet Shield use D8 pin instead of D10 pin.

## Software Changes ##

 1. On line 61 of `sketchbook/libraries/Tlc5940/tlc_config.h` replace

        #define DATA_TRANSFER_MODE    TLC_SPI
    with

        #define DATA_TRANSFER_MODE    TLC_BITBANG

 2. On lines 339 - 341 of `arduino/libraries/Ethernet/utility/w5100.h` replace

         inline static void initSS()    { DDRB  |=  _BV(2); };
         inline static void setSS()     { PORTB &= ~_BV(2); };
         inline static void resetSS()   { PORTB |=  _BV(2); };
with

         inline static void initSS()    { DDRB  |=  _BV(0); };
         inline static void setSS()     { PORTB &= ~_BV(0); };
         inline static void resetSS()   { PORTB |=  _BV(0); };

## Hardware Changes ##
 1. Bend leg of the D10 pin on the Ethernet Shield so it doesn’t connect to the D10 pin on the Arduino.

 2. Connect D10 pin of Ethernet Shield to D8 pin on the Ethernet Shield
    ![D10 pin connected to D8 pin][1]

 3. Connect the TLC5940 using the following pins:

        -------------                                  ---u----
        Ethernet   13|                           OUT1 |1     28| OUT channel 0
        Shield     12|                           OUT2 |2     27|-> GND (VPRG)
                   11|                           OUT3 |3     26|-> SIN (pin 7)
        10,underneath|-> BLANK (pin 23)          OUT4 |4     25|-> SCLK (pin 4)
                    9|-> XLAT (pin 24)             .  |5     24|-> XLAT (pin 9)
                    8|-> to pin 10 on shield       .  |6     23|-> BLANK (pin 10 underneath shield)
                    7|-> SIN (pin 26)              .  |7     22|-> GND
                    6|                             .  |8     21|-> VCC (+5V)
                    5|                             .  |9     20|-> 2K Resistor -> GND
                    4|-> SCLK (pin 25)             .  |10    19|-> +5V (DCPRG)
                    3|-> GSCLK (pin 18)            .  |11    18|-> GSCLK (pin 3)
                    2|                             .  |12    17|-> SOUT
                    1|                             .  |13    16|-> XERR
                    0|                           OUT14|14    15| OUT channel 15
        -------------                                  --------

Tested with Arduino 1.0.5 on Linux Mint 17 with r14 of the [tlc5940arduino][2] library.

References:

http://blog.andrewwei.mu/?p=19

http://forum.arduino.cc/index.php/topic,22111.0.html

http://forum.arduino.cc/index.php/topic,142977.0.html

http://forum.arduino.cc/index.php/topic,118265.0.html

  [1]: https://i.stack.imgur.com/QnHfh.jpg
  [2]: https://code.google.com/p/tlc5940arduino/


message:
Powering 5V Accesories

I'm using an Uno to control NeoPixels LED strips (60 per metre). These are powered with a 5V DC supply. Now, when using USB to power the Arduino it works lovely. However I want to move the Arduino into a standalone "installation" where I'll only want one power supply.

I've already got a 5V DC supply which outputs about 5.2V. What is the best way to power both the Arduino and the LEDs? I understand the need for at least 7V at the Arduino's voltage regulator input. Would my best bet be to get a 12V supply (or similar) and use a buck converter to power the LEDs? The total current draw *could* reach 3.6A but will be 400mA for the majority of the time.

body: If your supply is regulated (put a 47ohm resistor across it and measure the AC voltage with a DMM; it should be almost nothing if properly regulated) then you can use it for both the Uno and the NeoPixels. The ATmega328P has a maximum input voltage of 5.5V, and the WS2812B has a maximum voltage of 5.3V, putting the supply within the proper range to run them.


message:
Connecting two pressure sensors with one uno

I'm trying to connect two BMP180s to an arduino uno by using a multiplexer.

Here is the code that a guy has written before:
I imported SFE_BMP180 library but didn't do anything with the "typedef.h" thing.

I'm getting "Data does not name a type" error at the line 9.
How can  I solve this problem?

         #include <SFE_BMP180.h>
        #include <Wire.h>
        #include "typedef.h"

        #define SELECT_PIN 9
        #define ALTITUDE 510.0

    #define P1_ACTIVE digitalWrite(SELECT_PIN,HIGH); //delay(10);
    #define P2_ACTIVE digitalWrite(SELECT_PIN,LOW);  //delay(10);

    SFE_BMP180 bmp1,bmp2;
    boolean readSensors(Data *data1, Data *data2);

    Data newData(char id)
    {
      Data d ;
      d._id = id ;
      return d ;
    }
    void setup()
    {
     boolean failed = false ;
     pinMode(SELECT_PIN, OUTPUT);

     Serial.begin(9600);

     P1_ACTIVE

     if(bmp1.begin()){
      Serial.println("BMP #1 init success.");
     }
     else
        failed = true ;

     P2_ACTIVE
     if(bmp2.begin()){
        Serial.println("BMP #2 init success.");
     }
     else
      failed = true ;

     if(failed){
      Serial.println("Error in BMP180 init.");
      while (1);
     }
    }

    void loop()
    {
      Data d1 = newData('1');
      Data d2 = newData('2');

      boolean read = readSensors(&d1,&d2);

      if(read){
           /* print the value to serial terminal */
    ...

body:
You can try my [BMP080/BMP180 Arduino library][1]
My library doesn't require use of floats of math library, making your sketch very small and fast.

  [1]: https://github.com/cano64/Arduino-BMP085-Library-no-pow


message:
Interrupts don't work

I tried to run a sketch that tests my AVR's interrupts,
I have an UNoriginal Arduino Uno, and I've checked pins 2 and 3 like the following:

    - at void setup()
    attachInterrupt(2, inter, CHANGE);
    - at void inter()
    Serial.println("Interrupt pin 2");

I did the same on pin 3, I checked them by attaching the pins to a button with a Pull-Up,
When I click the button it goes from HIGH to LOW.
But yet, the arduino doesn't run the 'inter'.
Is it possible that because my Arduino is not original it won't work?
And this type of interrupts are software not hardware right?

body:
On all Arduino boards except the DUE, `attachInterrupt()` does not use the pin number as first argument but the interrupt number, which is different:

    void attachInterrupt(uint8_t interrupt, void (*ISR)(void), int mode);

As documented on [Arduino reference][1], for an Arduino UNO, the mapping is as follows:

 - Interrupt 0 -> Pin 2
 - Interrupt 1 -> Pin 3

So just change the code in `setup()` to:

    attachInterrupt(0, inter, CHANGE);

And that should work for pin 2.

  [1]: http://arduino.cc/en/Reference/AttachInterrupt


message:
Setting serial number on CH340 USB-Serial device

Reading http://playground.arduino.cc/Linux/Udev there appears to be a way to write out to a FTDI USB-Serial EEPROM to set a given SerialNumber, allowing you to identify a given nano/other arduino to handle it specifically in UDEV.

I have a nano-style boad with a QinHeng Electronics HL-340 USB-Serial adapter, which clearly isn't an FTDI chip, and the FTDI programmer therefore doesn't work. Does anyone know of an alternative utility/where I can find information to do the same with this chip?

Currently the device identifies itself with:

    [ 6850.608080] usb 2-1.2: new full-speed USB device number 7 using ehci-pci
    [ 6850.701496] usb 2-1.2: New USB device found, idVendor=1a86, idProduct=7523
    [ 6850.701505] usb 2-1.2: New USB device strings: Mfr=0, Product=2, SerialNumber=0
    [ 6850.701510] usb 2-1.2: Product: USB2.0-Serial
    [ 6850.702201] ch341 2-1.2:1.0: ch341-uart converter detected
    [ 6850.704210] usb 2-1.2: ch341-uart converter now attached to ttyUSB0

Which is essentially useless, as I can't identify the given board attached (when I attach two, their details are the same).

body:
If what you want is to tell apart 2 devices that are basically identical, you have 2 ways:

 - always plug them in the same ports and use the USB tree to differentiate them
 - create an handshake protocol, where each Arduino uses a code that you have previously stored in their respective EEPROMs. It might even be possible to write a helper function for UDEV, so that the helper function does the handshake and tells UDEV the serial that is stored in each EEPROM. That would allow to write a UDEV rule for your devices.


body:
Put a Maxim DS18S20 on your board, each has a unique serial number and are very inexpensive.  There are a lot of software examples on the internet using this device.  You could dead-bug it to the nano.  to operate it needs a 4.7K resister connected to +5 and a ground connection. You can connect both the 5V and Ground connections of the device to ground.  It would be easy to dead bug this to the nano then by simple communication via one pin you can get the serial number. There are several packages available.  With care you could use an input pin, read the serial and save it for future use.  When it Inits it will do this again. Just be sure the input is not driven low during the init process.

Good Luck,

Gil


body:
I hate to say it, but the answer is no, there is not way to uniquely identify multiple 340 based usb-serial converters.

I have the same problem, where I have multiple (4+) usb-serial converters, any one could be plugged into any port, and they were purchased at the same time and therefore are identical in every way (including iSerial of 0).

Basically, if I move things around, I have to connect by hand to see what's attached, peruse dmesg output, etc. It's a big pain.

tom


body:
There is no storage on the CH340 and family of UARTs where you could put a unique ID. This is also a problem for the PL2303 type. I have been trying to find solutions for this problem. First and easiest is the position of the device on the USB bus. It will be unique for each device. If you're using linux you can find each device under /dev/serial/by-path . There is also a /dev/serial/by-id but there will only be one entry there for this device because it shows the last one connected. FTDI chips will each have unique entries here. Cheap chips won't, but they each have an entry under /dev/serial/by-path.
This position, and the device names, should persist across reboots. If you have a lot of changes to your USB devices, plug all the CH340 devices into the same hub, then plug that in. The devices will enumerate in the order that they are plugged in to the hub. This one-hub trick should work for MacOS and windows too, they should come up in the same order.

Harder method- udev rules.
For devices with a unique ID such as FTDI you can set a udev rule that sees it's serial number and then creates a symlink to that device, it's straightforward.

For devices with the same or no Serial number, it's a lot more complex. I created a udev rule that looks like this:

SUBSYSTEM=="tty", ATTRS{product}=="USB2.0-Serial", RUN+="/usr/local/bin/cheapduino.py %k", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", ENV{ID_MM_DEVICE_IGNORE}="1"

when the device matches the product and vendor of the cheap arduino, it runs the script 'cheapduino.py' with the device as argument, for instance

cheapduino.py ttyUSB0

Then the cheapduino script connects by serial to the device and sends the string 'ID' and the software on the device responds DEVID=THX1138 or whatever. The script then creates a symlink /dev/THX1138 that points to /dev/ttyUSB0

There are a lot of drawbacks to this method. The script must time out if the software on the cheapduino doesn't answer. Also this is not using the SYMLINK function of udev so it won't clean up dead links on disconnect, but it will overwrite them on reconnect. All of your cheapduinos must have this functionality in their software, with different device IDs set. They all must use the same baud rate as the script unless you want to write a very complex script that takes a long time. Finally, this method works much better at low baud rate than at high baud rate, which for timing reasons may not succeed every time. (cheapduinos are cheap!) 9600 works much better than 115200 which works after several tries. But since all your CH340 arduinos must be the same speed with this method, you can only go as slow as your fastest device.

This method DOES work though, and it's what I'm using because I bought way too many of these cheap things.

In the end, buy genuine Arduinos or at least ones with FTDI chips or something else that sends a unique device ID.

=Rich


body:
CH340B (not the G) has an EEPROM where you can store the serialnumber.

https://www.mpja.com/download/35227cpdata.pdf

There is a windows tool as well to read/write it:

http://www.downxia.com/downinfo/196126.html

Will try to install and see how the G version behaves...


body:
Here is a software tool that I wrote which can be used to update serial number of WinChip Head CH340B. This will be useful for some one who wants to connect multiple CH340B Virtual COM Port devices to their Windows PC.

You can get the source code of this tool from the following github repository.

https://github.com/senthilnathant/tools-ch340b-configuration


message:
How to move from arduino to physical prototype

I've been reading a bit about moving from Arduino to PCB and it seems a bit daunting. For now, all I really want to do is take something I've built, and make a few changes so that I can actually create a casing for it and make sure everything stays connected.

I've attached a photo of my project. What I am trying to do is create a box, where 4 pushbuttons sit in a box, with LEDs next to them. I will probably create foamboard cutouts for the spaces where the pushbuttons and leds sit. The wiring for the push buttons and the LEDs need to be hidden below the foam board, along with the arduino itself and the servo motor - which is where I get stuck.

What do I need to do to essentially "lengthen" the wires for the pushbuttons and LEDs, and make sure all the components stay secure in the breadboard (the push buttons in particular like to pop out)? Is there a way to do this without making a PCB? I understand the concept of soldering components into protoboard, but as far as cutting / printing the circuits or whatever, it is really confusing to me.

I'd appreciate any guidance. If you see anything wrong with my wiring setup too, I'd love a learning experience on that as well. Thanks!

![enter image description here][1]

![enter image description here][2]

  [1]: https://i.stack.imgur.com/zuw5E.jpg
  [2]: https://i.stack.imgur.com/ZfWWo.png

body:
Using a **stripboard** is perfectly convenient to create a circuit that:

- will last longer than a breadboard prototype
- will cost less than wasting a breadboard for a long time

Stripboards can be found in any good electronics retailer (I buy mines at Conrad).

You will need a soldering iron (and the skills that are needed for it, but that is not so difficult as some people think).

You could even go one step further and create an Arduino on the same stripboard (many components from the UNO are not required for a circuit you want to build and keep "forever").

Another option, just a little bit more expensive, would consist in affording a **prototype shield** for Arduino, solder you circuit onto it and directly plug it onto your Arduino. The principles are the same as for a stripboard, except the prototype are has typically no strip, only holes on which you can solder components and wires.


body:
The best thing to do is, of course, to use a PCB. But it doesn't need to be a custom PCB; there are plenty of pre-made PCBs that are usable for approximately 98% of designs. Here are just a few:

- Adafruit Perma-Proto boards are connected just like breadboards, so direct transfer is possible.

- BusBoard proto boards come in a *ridiculous* variety of configurations, including enclosure kits, and they even have SMD boards if you're up to it.

For switches just use a panel mount form. They come in everything from simple to robust to ridiculous.

LEDs can also be panel mount, or you can use a light pipe to make a LED on the PCB visible from the outside.

For power you can use a USB connection or a separate power jack with a voltage regulator. If you also need a serial connection then you should consider a pre-made serial module, and either use its built-in USB jack or a separate panel mount USB jack.

The servo can be mounted inside the case if appropriate, or can be connected to a PCB mount or panel mount connector instead.

Naturally the MCU itself should also be placed in a socket directly on the PCB. Don't forget the decoupling, the oscillator, and the ISP connector.

As for the circuit itself, you can get rid of the pullup resistors on the switches if you use internal pullups instead. And 100ohm is *way* too low a value for switch pullups regardless.


body:
Learning to design a PCB can be a challenge. First, there's software choices, there's file formats, and then actually laying out a good board. That's before production and assembly, each with its own struggles along the way. It's no different than the first time you open Xcode and learn about Storyboards and Frameworks and Simulators and all that, or for that matter, learning any new skill, which at first is a daunting experience but through both setbacks and success eventually becomes easy.

So, I agree with everyone that suggests perfboards and variants. But I also want to show, as perhaps motivation, where you could be in a few months. I tend to see Arduinos as the development tool, not the final product, but I understand others are content to just use a standalone Nano or Pro Mini and forever dedicate it to their project.

These are three variants of the same device, it combines an Arduino/ATMega, a GPS, a serial port, and an RGB LCD. I first created it in on a breadboard, then moved to a perfboard, thought "that is ugly" and made a simple PCB. Pleased with that experience, I kept refining the schematic and layout until I finally called the project "done."

![perfboard project][1]
![primitive PCB][2]
![Final PCB][3]

You also might consider making tiny PCBs just for specific components, like these two boards I make for buttons and lights.

![hardware switch denouncer and LED breakout boards][4]

The very first PCB I ordered from OSHPark was an amazing experience, opening the envelope and holding it like some religious relic. But since then it's become routine. If you do later go the PCB route, you might appreciate [my summary][5] of low-volume shops I've ordered from.

  [1]: https://i.stack.imgur.com/L9tFI.jpg
  [2]: https://i.stack.imgur.com/ccGK8.jpg
  [3]: https://i.stack.imgur.com/wUeOj.jpg
  [4]: https://i.stack.imgur.com/nAmXO.jpg
  [5]: http://www.ardueasy.com/2014/11/manufacturing-printed-circuit-board.html


body:
You can use Arduino proto shield. It's a prototyping board shaped the way it can be plugged into the Arduino. There are over 9000 of them from different manufacturers. Then just solder the stuff you need on the proto shield.

![enter image description here][1]

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


message:
Cannot retrieve data from homemade ECG

For the past couple of weeks, I have not been able to find a solution to my problem.  My problem is that I cannot retrieve the data from my homemade ECG that I created from Arduino.  I am a total amateur at this, but I'm pretty sure it's a circuitry issue.  Here is what my circuit looks like now.  (Note: the thing that says 'Dual O' on the far left is the instrumentation amplifier, not an operational amplifier like the one near the middle)

Here is the code I'm using:

    const int  signal = 5;    // Pin connected to the filtered signal from the circuit
    unsigned long currentBeatTime;
    unsigned long previousBeatTime;

    unsigned long frequency;

    // Internal variables
    unsigned long period = 0;
    int input = 0;
    int lastinput = 0;

    void setup() {
    pinMode(signal, INPUT);
    Serial.begin(9600);

    previousBeatTime = millis();
    }

    void loop() {
    delay(500);
    input = digitalRead(signal);

    if ((input != lastinput) && (input == HIGH)) {
        // If the pin state has just changed from low to high (edge detector)
        currentBeatTime = millis();

        period = currentBeatTime - previousBeatTime; // Compute the time between the previous beat and the one that has just been detected
        previousBeatTime = currentBeatTime; // Define the new time reference for the next period computing
    }

    lastinput = input; // Save the current pin state for comparison at the next loop iteration

    // Detect if there is no beat after more than 2 seconds
    if ( (millis() - previousBeatTime) > 2000 )
    {
        Serial.println("dead");
    }
    else
    {
        if (period <= 0)
        {
            frequency = 0;
        }
        else
        {
            frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
        }

        Serial.print(frequency);
        Serial.println(" : alive! ");
    }
    }

I would appreciate if someone could get back to me as soon as possible.  Thank you!

EDIT:
Here's a schematic.  I used Fritzing, and since I am a total beginner at this, it looks like a complete mess.  Anyways, here it is:

![2](https://i.stack.imgur.com/dhuXF.jpg)

Thank you for your help.

body:
Has any part of it ever worked? What have you done to it since?
My approach to debugging this would be to
 - Temorarily replace the Bluetooth with wired serial communication;
 - Comment out, or stub out(*), anything you aren't utterly and completely confident in.
 - Get some minimum amount of hardware and software working.
 - Add back one piece of hardware or one section of code at a time, fixing whatever you have to to get it working again.
 - Repeat, until everything is back together and playing nicely.

(*) Stubbing is the technique of replacing a function or a section of code with something trivial (and therefore hard to get it wrong!) that lets the rest of the code mostly work.<br>
Suppose you had written a digitalRead() function. (I know it's a library function and we have total confidence in it, but for a moment, just suppose....) You might replace the contents of your digitalRead() with a single statement:

    int digitalRead(uint8_t pin){
       // untested code commented out here
       // ...
       return(4);  // any value that means something to the calling code
    }

Now you can work on the code that calls your digitalRead() without having a working digitalRead(). The caller will only ever get the same value every time it calls, but that may be enough get some part of it working until you can come back and fix your digitalRead() function.


message:
Can I drive this relay shield with an Arduino Due?

Sorry I'm new to electronics while I've some experience in coding. This let me very curious about the Arduino Due board: it is super powerful and I can run some C++ code that I can not with the normal Arduino Uno. But I lack in electronic theory, sorry if the question is a little bit dumb.

Can I drive [this shield][1] with an Arduino Due? The Due board is at 3.3V while [the relays][2] in the shield are at 5V.

What do I need to make them run smoothly?

Actually I'd like to run 5 of those shield with only one Arduino Due board. Do I have some problem with power supply?

  [1]: http://www.ebay.com/itm/8-Channel-5V-Relay-Module-Board-Shield-for-Arduino-PIC-AVR-MCU-DSP-ARM-US-Stock-/360717697832
  [2]: https://www.ghielectronics.com/downloads/man/20084141716341001RelayX1.pdf

body:
You'd have to remove the yellow jumper. Connect 3.3v to the VCC and 5v to the JDVCC. But please double check that JDVCC is connected to one side of all the relays.

This way the opto-couplers are activated by 3.3v signals, which in turn activate the transistor (5v) used to engage the relay.


message:
How to avoid the code interrupting itself?

I have this code, which I am using with a potentiometer to control the speed of a automotive fuel injector. In it, I have specified how long the injector shall stay open by using the delay functions. However, whenever the code runs into a delay call, it pauses the whole code for that amount of time. Although it's not significantly long, it would still be better if it could keeping running analogInput and at the same time run through the if statements, without any interference from either. So basically run two different process simultaneously.

I remember reading somewhere that this is possible with threading? But do you need a library for that? I know Python has a threading library built in, and you can actually use it pretty easily, but what about Arduino? How could I run these two process at the same time?

Here's my code:

    #define in1 12

    void setup(){
     Serial.begin(9600);
     pinMode(in1, OUTPUT);
    }

    void loop(){
     float rotationValue = analogRead(A1);            //read raw input from potentiometer
     float percentValue = rotationValue / 10.23;      //convert to percent 0-100
     Serial.println(percentValue);                    //print it to screen
     if(percentValue >= 0.0 && percentValue <= 1.0){
      digitalWrite(in1, LOW);                         //injector 1 off
     }
     else if(percentValue > 1.0 && percentValue <= 25.00){    //cycle at 100 millisec.
      digitalWrite(in1, HIGH);
      delay(100);
      digitalWrite(in1, LOW);
      delay(100);
     }
     else if(percentValue > 25.00 && percentValue <= 50.00){    //cycle at 50 millis.
      digitalWrite(in1, HIGH);
      delay(50);
      digitalWrite(in1, LOW);
      delay(50);
     }
     else if(percentValue > 50.00 && percentValue <= 75.00){      //cycle at 25 millis.
      digitalWrite(in1, HIGH);
      delay(25);
      digitalWrite(in1, LOW);
      delay(25);
     }
     else{              //cycle at 10 millis.
      digitalWrite(in1, HIGH);
      delay(10);
      digitalWrite(in1, LOW);
      delay(10);
     }
    }

body:
You can't use threads on an arduino, they don't exist. you can get some pseudo multitasking going with interrupts, but that is not necessary in your case.

You should be able to refactor your code to avoid using delays without much work. The arduino library provides `millis()` to keep tract of the time since the arduino was powered on in milliseconds.

something like this could replace all the delays in your code

    static boolean state;
    static uint32_t time;
    if(time < millis()){
     time += delayFromPercent(percentValue);

     state = !state;
     if(percentage < 1.0) state = false;
     digitalWrite(in1, state);
    }

Then, somewhere else place

    uint32_t delayFromPercent(float percent){
     if(percent < 25) return 100;
     if(percent < 50) return 50;
     if(percent < 75) return 25;
     return 10;
    }

alternately, if you don't really want the discrete steps, you could use this instead

    uint32_t delayFromPercent(float percent){
     return max(10, 100-percent); // don't return less than 10ms
    }

you could change it to react a bit quicker by comparing the time plus calculated delay now rather than when it last set the pin, but that strays farther from what your initial implementation would have done.

In any case, this code will should be able to switch pin in1 without making the rest of your code slow down, as long as the other code does not use delays either.


message:
Controlling Arduino from Raspberry Pi

I am trying to control an Arduino Leonardo R3 to run some code when "triggered" from a Raspberry Pi. This would be in a loop so that it can be run multiple times. I have set up the Raspberry Pi and tested it with an LED and the output is working fine.

I then connected this to the Arduino and checked for a HIGH input from the RPi using an if statement.

    void setup() {
      pinMode(7,INPUT);
      if(digitalRead(7)==HIGH) {
        // CODE IN HERE
      }
    }

I found that this did not work as the if statement was always true because of pullup resistors not being used. I would greatly appreciate some guidance on this.

body:
You have to verify, at least:

A. if the 3.3V of the RPi can be read as high on the Atmega, if so you can connect them without any resistor.

B. if not, you have to use a voltage adapter (yes, other components and many possible solutions), otherwise you RPi GPIO will be ruined if using a pullup on the 5V.

The pullup and pulldown, in this case, should be used when you are in A and the peripheral support the higher voltage. This is not the case.


body:
I don't have much experience about Arduino boards connected to the Pi, never tried anything other than Arduino Due, but I do have some experiences with ATmega328P directly attached to the Pi. The ATmega is clocked at 12MHz instead of 16 to guarantee a stable state at 3.3V supply voltage.

Physical connection takes 5 signal wires besides the 3.3V power rail, with the ATmega talking with the Pi over SPI as a slave device, using both slave select lines, one at the SS pin and the other at RESET pin. This allows communication over proper hardware interfaces while eliminates the need of a programmer or preprogrammed chips as the ATmega use its SPI interface as ICSP, this setup essentially keep ICSP properly wired to the Pi at all times. An additional pin can be used as a IRQ pin from the ATmega to the Pi.

About the protocol that part is up to yourself. There are endless possibilities and you can implement anything that fits your need and easy to use.


body:
I have done this in a different manner.

I have used the UART TX pin of RPi connected to the RX pin of the arduino and sent serial messages from Arduino to RPi.

That worked fine.

But the thing is, what you have done is correct and has to work.

Please make sure that you have connected Arduino's ground and RPi ground together.

------------------------------------------------------------------------

If you not do that and try the same code it has to work. Because the RPi and Arduino are in two different circuits, so in order to work, make them one make GROUND common.


message:
Capture output from external device using Arduino Uno

I was unable to find this question anywhere but I want to use my Arduino Uno to capture the output of a Code 39 signal coming out of a separate device. Currently, my setup is similar to this:

![enter image description here][1]

I have a [biometric hand reader](http://us.allegion.com/Products/biometrics/handkey2/Pages/default.aspx) that outputs a Code 39 signal along D1 while D0 stays at a constant 0 which can be seen here:

![enter image description here][2]

Ultimately, I want to use the Arduino Uno to take the input from the data line and convert the Code 39 signal to ASCII. The process should functions like this:

1. User enters their code into the hand reader and hand reader measures their hand
2. Reader *outputs* Code 39 signal to Arduino and software on Arduino converts barcode format to ASCII.
     * Note: I believe the Code 39 signal will represent something similar to this `*12345*`. The user ID code will **always** be five digits. `*` represent the start and stop characters for Code 39 barcode format
3. Arduino sends ASCII code to computer which checks remote database to ensure user is valid

I have my correct pins set as follows:

 #include <SoftwareSerial.h>
 #define D1 3
 #define D0 2

 void setup() {
  pinMode(D1, INPUT);
  pinMode(D0, INPUT);
 }

Is it possible to either print out the binary representation of the signal via the Serial console or write to a file that I can view later on? My idea is to use the `loop` function to listen for the signals via `digitalRead()`

 void loop() {
  digitalRead(D1);
  digitalRead(D0);
 }

The last part is the thing I'm having an issue with since I can't seem to get the information printed to the serial console or written to a file. I tried this but it didn't work:

 void loop() {
  foo();
 }

 void foo() {
  digitalRead(D1) == HIGH ? Serial.print("0") : Serial.print("1");
  Serial.println("");
  digitalRead(D0) == HIGH ? Serial.print("0") : Serial.print("1");
 }

Any ideas on how to make this happen or is it impossible? I want to see the output of device so I can verify it's outputting what I think it is.

Lastly, I am using Visual Studio with the Visual Micro plugin so I can attempt to debug my code. I also have a OS X machine that has the Arduino IDE installed on it if I need a Mac for anything.

**Addendum:** I don't have ready access to an oscilloscope. However, I have tested this device on an oscilloscope and I did have output that seemed all wrong. I want to see what the arduino says it is to verify things before I continue with this project.

  [1]: https://i.stack.imgur.com/0oF2Q.png
  [2]: https://i.stack.imgur.com/7tRb3.jpg

body:
First, let's find, what's wrong with your method. You try to poll the signal pins continously and write them out to serial. Default serial rate is 9600. Which means, that you can transmit approx. 900 characters per second. Looking at your oscillogram we can tell, that the signal you want to analyse has a base clock of roughly 2.5 kHz. Which means you definitely won't be able to sample every change of level with your method.

You can in fact use the `loop()` function to listen for changes, i.e. poll the signal, when you increase your serial baud rate. But I suggest using interrupts.

My suggestion is a three step process.

 1. get the signal thoroughly recorded with all relevant information about the signal. This includes transmission to your PC via serial interface.
 2. Analyse the signal offline. i.e. after having it received on your PC
 3. Adapt your arduino code to decode it further before transmitting it to your PC

let's get to part 1):
read [Arduino documentation on interrupts][1]
the interrupt allows you to prevent interference of your two tasks (reading the inputs and writing to serial).
What is the interesting information? I think it's the waveform (i.e. the signal in best resolution you can deliver). You can sample your waveform at a high rate, but the resulting data volume will overwhelm your serial output. Fortunately your signal has some obvious characteristics. Which are:

 - obeys some timing (i.e. a clock)
 - has a limited transmission length (protocol frame)
 - has a limited transmission rate (as can be seen from oscillograph)

The best way to keep as much of the signal information by reducing the amount of serial transmission is to record the time of every level change.

**Updates: buffer used, buffered output after receiving timeout**

    #define RECVTIMEOUT 2000 // we think, more than 2000 usec is end of transmission
    #define MAXEVENTS 100

    uint8_t inpin=2;
    volatile unsigned long timestart=0;
    uint8_t transmitLevel=LOW;

    volatile uint8_t state=0; // little state machine: 0=nothing happened yet, 1=receiving data, 2=receiving timeout
    volatile uint16_t tstamps[MAXEVENTS]; // we store timestamps of received symbols here
    volatile uint16_t levels[MAXEVENTS]; // we store levels of received symbols here
    volatile uint8_t index=0; // we save index of data here.
    uint8_t count=0; // counter for later use.

    volatile bool conflict=false; // will be set, if transmission conflicts with receive function.

    void pinchange() // the ISR (interrupt service routine)
    {
        switch(state)
        {
        case 0:
           timestart=micros();
           tstamps[index]=0;
           levels[index]=digitalRead(inpin);
           state=1;
           ++index;
        break;
        case 1:
           tstamps[index]=micros()-timestart;
           levels[index]=digitalRead(inpin);
           ++index;
        break;
        case 2:
           conflict=true;
        }
    }

    void setup()
    {
        Serial.begin(115200); // high serial rate. don't forget to set the same in your IDE
        attachInterrupt(0, &pinchange, CHANGE); // the controller needs to know, where your ISR is.
    }

    void loop()
    {
        switch(state)
        {
        case 1:
           if (index > 20)
           {
              if (micros()-timestart > RECVTIMEOUT)
              {
                 state=2;
              }
           }
           if (index >= MAXEVENTS)
           {
              state=2;
           }

        break;
        case 2:
           for (count=0; count<index; ++count)
           {
             Serial.print(tstamps[count]);
             Serial.print(";");
             Serial.println(levels[count]);
           }
           if (conflict)
           {
             Serial.println("too less time to send data");
           }
           index=0;
           conflict=0;
           state=0;
        }
     }

This should output a fine csv with all your signal edges in microseconds, which you can paste directly to your favourite spreadsheet application. This is only for one signal. For analysing both, you have to enhance it accordingly.

**Update 1**

part 2)

 from the gained data of our previous code version (snippet for brevity)

    time signal timedifference
    2614592 0 468
    2615056 1 464
    2615524 0 468
    2616496 0 972
    2616960 1 464
    2617956 0 996
    2618960 1 1004
    2620424 1 1464
    2621352 1 928
    2622324 1 972
    2623320 0 996

we can see two things.

 1. The code in my first version of the answer didn't work properly. Every 1 should be followed by a 0 in column 2 and vice versa. This is apparently not true, which leads us to the conlusion, that we missed some events.
 2. time differences seem to be multiples of roughly 470 μs. We can consider this as the length of a symbol.

So what's wrong with the code? I used noInterrupts() to stop Interrupts for copying the data. I hoped, there won't be level changes in this short period of time, but apparently this was not true. How to fix it? We better find another way to register the events and transfer them.
I recommend sticking to the interrupt technique, but changing the way we store the events and reading it out. Let's use a buffer big enough for all events of a transmission. After a transmission we can send all data without hassle via serial to the PC.

What can we expect? 0s and 1s should be transmitted alternating, with reasonable timings. If we can prove this, we can change the main loop again for decoding code 39.

part 3)

 - write code which stores a word of code 39 in a buffer
 - another code which decodes that word into a byte when the buffer is full
 - transmit that byte via serial

(many improvements possible).

  [1]: http://arduino.cc/en/Reference/AttachInterrupt


message:
Determining contrast on LCD

So I am using this code here and I do get text written on my LCD screen. Problem is that text is almost invisible. I tried with background light on or off and it did not help. LCD is connected to 5v and backlight is connected to 3.3V. Backlight is connected through potentiometer.

How to control text contrast? To have more contrast?

    #define PIN_SCE   7
    #define PIN_RESET 6
    #define PIN_DC    5
    #define PIN_SDIN  4
    #define PIN_SCLK  3

    #define LCD_C     LOW
    #define LCD_D     HIGH

    #define LCD_X     84
    #define LCD_Y     48

    static const byte ASCII[][5] =
    {
     {0x00, 0x00, 0x00, 0x00, 0x00} // 20
    ,{0x00, 0x00, 0x5f, 0x00, 0x00} // 21 !
    ,{0x00, 0x07, 0x00, 0x07, 0x00} // 22 "
    ,{0x14, 0x7f, 0x14, 0x7f, 0x14} // 23 #
    ,{0x24, 0x2a, 0x7f, 0x2a, 0x12} // 24 $
    ,{0x23, 0x13, 0x08, 0x64, 0x62} // 25 %
    ,{0x36, 0x49, 0x55, 0x22, 0x50} // 26 &
    ,{0x00, 0x05, 0x03, 0x00, 0x00} // 27 '
    ,{0x00, 0x1c, 0x22, 0x41, 0x00} // 28 (
    ,{0x00, 0x41, 0x22, 0x1c, 0x00} // 29 )
    ,{0x14, 0x08, 0x3e, 0x08, 0x14} // 2a *
    ,{0x08, 0x08, 0x3e, 0x08, 0x08} // 2b +
    ,{0x00, 0x50, 0x30, 0x00, 0x00} // 2c ,
    ,{0x08, 0x08, 0x08, 0x08, 0x08} // 2d -
    ,{0x00, 0x60, 0x60, 0x00, 0x00} // 2e .
    ,{0x20, 0x10, 0x08, 0x04, 0x02} // 2f /
    ,{0x3e, 0x51, 0x49, 0x45, 0x3e} // 30 0
    ,{0x00, 0x42, 0x7f, 0x40, 0x00} // 31 1
    ,{0x42, 0x61, 0x51, 0x49, 0x46} // 32 2
    ,{0x21, 0x41, 0x45, 0x4b, 0x31} // 33 3
    ,{0x18, 0x14, 0x12, 0x7f, 0x10} // 34 4
    ,{0x27, 0x45, 0x45, 0x45, 0x39} // 35 5
    ,{0x3c, 0x4a, 0x49, 0x49, 0x30} // 36 6
    ,{0x01, 0x71, 0x09, 0x05, 0x03} // 37 7
    ,{0x36, 0x49, 0x49, 0x49, 0x36} // 38 8
    ,{0x06, 0x49, 0x49, 0x29, 0x1e} // 39 9
    ,{0x00, 0x36, 0x36, 0x00, 0x00} // 3a :
    ,{0x00, 0x56, 0x36, 0x00, 0x00} // 3b ;
    ,{0x08, 0x14, 0x22, 0x41, 0x00} // 3c <
    ,{0x14, 0x14, 0x14, 0x14, 0x14} // 3d =
    ,{0x00, 0x41, 0x22, 0x14, 0x08} // 3e >
    ,{0x02, 0x01, 0x51, 0x09, 0x06} // 3f ?
    ,{0x32, 0x49, 0x79, 0x41, 0x3e} // 40 @
    ,{0x7e, 0x11, 0x11, 0x11, 0x7e} // 41 A
    ,{0x7f, 0x49, 0x49, 0x49, 0x36} // 42 B
    ,{0x3e, 0x41, 0x41, 0x41, 0x22} // 43 C
    ,{0x7f, 0x41, 0x41, 0x22, 0x1c} // 44 D
    ,{0x7f, 0x49, 0x49, 0x49, 0x41} // 45 E
    ,{0x7f, 0x09, 0x09, 0x09, 0x01} // 46 F
    ,{0x3e, 0x41, 0x49, 0x49, 0x7a} // 47 G
    ,{0x7f, 0x08, 0x08, 0x08, 0x7f} // 48 H
    ,{0x00, 0x41, 0x7f, 0x41, 0x00} // 49 I
    ,{0x20, 0x40, 0x41, 0x3f, 0x01} // 4a J
    ,{0x7f, 0x08, 0x14, 0x22, 0x41} // 4b K
    ,{0x7f, 0x40, 0x40, 0x40, 0x40} // 4c L
    ,{0x7f, 0x02, 0x0c, 0x02, 0x7f} // 4d M
    ,{0x7f, 0x04, 0x08, 0x10, 0x7f} // 4e N
    ,{0x3e, 0x41, 0x41, 0x41, 0x3e} // 4f O
    ,{0x7f, 0x09, 0x09, 0x09, 0x06} // 50 P
    ,{0x3e, 0x41, 0x51, 0x21, 0x5e} // 51 Q
    ,{0x7f, 0x09, 0x19, 0x29, 0x46} // 52 R
    ,{0x46, 0x49, 0x49, 0x49, 0x31} // 53 S
    ,{0x01, 0x01, 0x7f, 0x01, 0x01} // 54 T
    ,{0x3f, 0x40, 0x40, 0x40, 0x3f} // 55 U
    ,{0x1f, 0x20, 0x40, 0x20, 0x1f} // 56 V
    ,{0x3f, 0x40, 0x38, 0x40, 0x3f} // 57 W
    ,{0x63, 0x14, 0x08, 0x14, 0x63} // 58 X
    ,{0x07, 0x08, 0x70, 0x08, 0x07} // 59 Y
    ,{0x61, 0x51, 0x49, 0x45, 0x43} // 5a Z
    ,{0x00, 0x7f, 0x41, 0x41, 0x00} // 5b [
    ,{0x02, 0x04, 0x08, 0x10, 0x20} // 5c ¥
    ,{0x00, 0x41, 0x41, 0x7f, 0x00} // 5d ]
    ,{0x04, 0x02, 0x01, 0x02, 0x04} // 5e ^
    ,{0x40, 0x40, 0x40, 0x40, 0x40} // 5f _
    ,{0x00, 0x01, 0x02, 0x04, 0x00} // 60 `
    ,{0x20, 0x54, 0x54, 0x54, 0x78} // 61 a
    ,{0x7f, 0x48, 0x44, 0x44, 0x38} // 62 b
    ,{0x38, 0x44, 0x44, 0x44, 0x20} // 63 c
    ,{0x38, 0x44, 0x44, 0x48, 0x7f} // 64 d
    ,{0x38, 0x54, 0x54, 0x54, 0x18} // 65 e
    ,{0x08, 0x7e, 0x09, 0x01, 0x02} // 66 f
    ,{0x0c, 0x52, 0x52, 0x52, 0x3e} // 67 g
    ,{0x7f, 0x08, 0x04, 0x04, 0x78} // 68 h
    ,{0x00, 0x44, 0x7d, 0x40, 0x00} // 69 i
    ,{0x20, 0x40, 0x44, 0x3d, 0x00} // 6a j
    ,{0x7f, 0x10, 0x28, 0x44, 0x00} // 6b k
    ,{0x00, 0x41, 0x7f, 0x40, 0x00} // 6c l
    ,{0x7c, 0x04, 0x18, 0x04, 0x78} // 6d m
    ,{0x7c, 0x08, 0x04, 0x04, 0x78} // 6e n
    ,{0x38, 0x44, 0x44, 0x44, 0x38} // 6f o
    ,{0x7c, 0x14, 0x14, 0x14, 0x08} // 70 p
    ,{0x08, 0x14, 0x14, 0x18, 0x7c} // 71 q
    ,{0x7c, 0x08, 0x04, 0x04, 0x08} // 72 r
    ,{0x48, 0x54, 0x54, 0x54, 0x20} // 73 s
    ,{0x04, 0x3f, 0x44, 0x40, 0x20} // 74 t
    ,{0x3c, 0x40, 0x40, 0x20, 0x7c} // 75 u
    ,{0x1c, 0x20, 0x40, 0x20, 0x1c} // 76 v
    ,{0x3c, 0x40, 0x30, 0x40, 0x3c} // 77 w
    ,{0x44, 0x28, 0x10, 0x28, 0x44} // 78 x
    ,{0x0c, 0x50, 0x50, 0x50, 0x3c} // 79 y
    ,{0x44, 0x64, 0x54, 0x4c, 0x44} // 7a z
    ,{0x00, 0x08, 0x36, 0x41, 0x00} // 7b {
    ,{0x00, 0x00, 0x7f, 0x00, 0x00} // 7c |
    ,{0x00, 0x41, 0x36, 0x08, 0x00} // 7d }
    ,{0x10, 0x08, 0x08, 0x10, 0x08} // 7e ←
    ,{0x78, 0x46, 0x41, 0x46, 0x78} // 7f →
    };

    void LcdCharacter(char character)
    {
      LcdWrite(LCD_D, 0x00);
      for (int index = 0; index < 5; index++)
      {
        LcdWrite(LCD_D, ASCII[character - 0x20][index]);
      }
      LcdWrite(LCD_D, 0x00);
    }

    void LcdClear(void)
    {
      for (int index = 0; index < LCD_X * LCD_Y / 8; index++)
      {
        LcdWrite(LCD_D, 0x00);
      }
    }

    void LcdInitialise(void)
    {
      pinMode(PIN_SCE, OUTPUT);
      pinMode(PIN_RESET, OUTPUT);
      pinMode(PIN_DC, OUTPUT);
      pinMode(PIN_SDIN, OUTPUT);
      pinMode(PIN_SCLK, OUTPUT);
      digitalWrite(PIN_RESET, LOW);
      digitalWrite(PIN_RESET, HIGH);
      LcdWrite(LCD_C, 0x21 );  // LCD Extended Commands.
      LcdWrite(LCD_C, 0xB1 );  // Set LCD Vop (Contrast).
      LcdWrite(LCD_C, 0x04 );  // Set Temp coefficent. //0x04
      LcdWrite(LCD_C, 0x14 );  // LCD bias mode 1:48. //0x13
      LcdWrite(LCD_C, 0x20 );  // LCD Basic Commands
      LcdWrite(LCD_C, 0x0C );  // LCD in normal mode.
    }

    void LcdString(char *characters)
    {
      while (*characters)
      {
        LcdCharacter(*characters++);
      }
    }

    void LcdWrite(byte dc, byte data)
    {
      digitalWrite(PIN_DC, dc);
      digitalWrite(PIN_SCE, LOW);
      shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
      digitalWrite(PIN_SCE, HIGH);
    }

    void setup(void)
    {
      LcdInitialise();
      LcdClear();
      LcdString("Hello World!");
    }

    void loop(void)
    {
    }

body:
Have you even read your own code? Notably line 141; `LcdWrite(LCD_C, 0xB1 );  // Set LCD Vop (Contrast).`.

Try sending a different value. Note that the first bit should always be 1 so the value should be between 0x80 and 0xFF


body:
`Backlight is connected through potentiometer.`

You should try to turn the potentiometer.

If that doesn't work, there might be something wrong with the connection from the potentiometer to the `Backlight`.

----------

Check out this video: https://www.youtube.com/watch?v=XR8ede6V6eA&t=65
Where the led would be replaced with the BL (black-light) pin.


body:
I assume you are using a 16 pin 16x2 display.  Try wiring a potentiometer like this with the pot wiper on pin 3. This is what adjusts text contrast:
 ![enter image description here][1]

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


body:
Same problem, I solved it following this:

> The contrast can be adjusted by the potential-meter displayed in the following picture.

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

[credit][2]

  [1]: https://i.stack.imgur.com/BHoOm.png
  [2]: https://www.dfrobot.com/wiki/index.php/I2C/TWI_LCD1602_Module_(SKU:_DFR0063)