text:
16 by 8 Keyboard matrix
I am working on a project, trying to construct an 80 button keypad. My problem is how to multiplex it so that i only feed the arduino with two sets of BCD or binary(whichever is easier) which are supposed to drive a 75 led display board simultaneously with a pair of 7 segments. The led display board is remote, which means i should drive the boards serially. The other 5 buttons remaining out of 80 are for other functions such as clear last number etc.
Please help!

Thank you very much guys. To answer FuaZe, it is 16*8 but will not use the whole 128 buttons. These extra buttons are for future expansion. The input should consist 16colums and 8 rows. The remote output board is a led matrix numbered from 1 to 75, arranged in a 15colums and 5rows. The same display board is to have a two digit 7seg display. The remote board is to be accessed serially so as to use few cables.
When I press a button on the matrix, say column 5 row 2 the number 20 should appear on the 7seg plus a correspondind diode on column 5 row 2 to light. In short if is a bingo board with numbers 1 to 75..

Why is the name of the question: "16 by 8 keyboard matrix", 16*8 does not equal 80 buttons?

Yes, 16x8 = 128 as either 16 outputs multiplexed by 8 inputs, or vice versa, and maybe multiplexing the 75+2x7 segments as another 10 by 7.  Seems like 16+8+10+7 =  41 pins it would fit easily on a 54 IO pin mega.  Maybe you want a 80 button multiplexed input, along with multiplexed 8x10 and 7x2 outputs?  Tell more about the remoteness requirement and the board vs boards requirements.

Ask your favorite internet finding service about "charlieplexing keys". This may help to connect more keys using less pins.

Easiest would be to use 2 arduino's, which are connected in some way.
One of them should tell the other one what to do. I suggest you make the one reading the buttons the "master" and the other one it's "slave" device.
You could use 8 inputs, for each column and 10 outputs for each row.
Then you check all 8 inputs per column (pretty rapidly) and then you'll be able to read every button.
You could choose to either send changes or just every value to the slave device.
The slave device would have to do something similiar, but with 2 outputs, to address the right LED's/segments.
Alternatively you could use shift-registers.
There actually are a lot of tutorials on this to be found on the web.
You should check out "Arduino multiplexing" or "Arduino led cube" tutorials.

Another option would be using both shift registers and port expanders, like Adafruit's MCP23017 I2C Port Expander.
You can use that for the buttons, just get a few of them and hook them up on the I2C bus and you have over eighty pins for the price of 2! If you choose to use the previously stated expander, you will also benefit from Adafruit's library.
Then, use a shift register for your LEDs, using one of the pins that is not I2C.
Note: Pin expanders can handle input and output. Shift registers are only for output!
Good luck!

Actually there are shift registers for input as well - such as the CD4021B by Texas Instruments: https://www.ti.com/product/CD4021B. It's widely supported (for example arduino library: https://www.arduino.cc/en/tutorial/ShiftIn) and has a 16 bit version as well


text:
Ethernet shield reset problems
I know there are multiple threads about ethernet shields not starting properly after power up and that there are versions that don't have those problems. But which versions are okay? Which versions do not require extra soldering/pin bending/physical resets?
How good are chinese rip-offs of those versions?

Does the Ethernet shield also have an SD? In that case check that the chip select pins are disabled in the setup().

It does have a SD card slot, but I don't use sd card at the moment.

This might be of some help. http://forum.arduino.cc/index.php?topic=25634.0

Yep I checked it, but I'm still looking for a way that doesn't include bending pins, extra soldering or extra code. If you look at the #41 comment in the link you posted, should that work? What about #48, what version is that?

I have worked with Ethernet Shields and modules. Most of them has reset issue. So I just put a 100nF Capacitor between the reset pin and ground pin. This solution works for most of the time.
This issue is there because the IC on board the shield does not have the power on reset option.
You can also tie the reset pin of your module with the reset pin of the Arduino.

If you don't want to make any modifications to the shield, and you don't want to make any modifications in code, then there really is only one option:

Don't use cheap knockoffs, but buy a genuine Arduino one.

If you have a board that requires modifications to work properly and if you're unwilling to make those required modifications then you can not just magic it into working by waving your magic wand.

I know, but the problem is that the same thing is happening on the original version of arduino shield. I want to buy another original, but there is no way of me buying it if the same problem will happen again.

source: Stack Exchange

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

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

sort: votes


text:
How to drive a 4bit GLCD?
i've got a huge (about 6 x 23 cm) graphics LCD. I used my multimeter and the datasheet the LCD driver chips (6 x KS0104 and 2 x KS0103) to get the pinout. It has the following pins: GND, M, FCS (not 100% shure), CL1, CL2, D0-3, VDD and a ground for the metal part.
My problem is that i dont know how i can drive a 4bit GLCD with an Arduino because i didnt found a library which can do this (e.g. OpenGLCD supports only the KS0104 which is an 8 bit controller)

What type of Arduino? A driver for that will require a lot of memory.

I already got an UNO but if it is necessary i could buy a MEGA (if it works).

How large is the LCD? Number of pixels. According to the product description (KS0104) it is 4-bit per pixel (16 levels gray-scale). Is that correct?

i counted about 17 pixels on 1 cm so this should be something like 391x138

That gives a total of 54K pixels. And with 4-bit per pixel, two pixels in a byte, 27K byte to store a packed off-screen bitmap. Even an Arduino Mega would have too little memory for that. This might explain why there are no supporting library for that device.

You might be right but i think i could also buy a DUE or ZERO (if necessary) and the main problem is not the amount of pixels, it is the 4bit connection (which is not supported by any GLCD library).

I copy-pasted @MikaelPatel comment as an answer. Please, accept it to close your question.

@MikaelPatel answered your question in the comments:

That gives a total of 54K pixels. And with 4-bit per pixel, two pixels
  in a byte, 27K byte to store a packed off-screen bitmap. Even an
  Arduino Mega would have too little memory for that. This might explain
  why there are no supporting library for that device.

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


text:
serialEvents within a class
My .ino looks roughly like this
#include "command.h"

Command command;
void setup() {
}

void loop() {
}

command.h
class Command
{
    public:
        Command();
};

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

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

void serialEvent() {
  while (Serial.available() > 0) {
    char inChar = (char)Serial.read();
    Serial.print(inChar);
  }
}

The serial events don't seem to be happening. It works normally if I move the code out of the class.

Does it work when you move serialEvent() back to the sketch? This might be a build/link issue.

When you put the Serial.begin in the constructor and declare the Command object at file scope, the Serial.begin will occur before setup().  Not recommended, perhaps not allowed.
If you do that, the compiler has to figure out that the Serial instance must be constructed before the Command instance is constructed.  It can't always figure out the correct order.
In general, this is why you see many classes with a begin or init method.  This allows the construction of file-scope instances to take place in any order, before setup.  Then setup does the Command.begin(), which finally calls Serial.begin, long after Serial has been constructed.
Also, using SerialEvent is no better than doing the polling in loop().  If you're busy doing something else, SerialEvent does not get called.  If you need to handle characters in the background, in the RX interrupt, you might want to take a look at a modified version for the Serial object(s) I posted, NeoHWSerial.  You can attach a routine to be called whenever a character is received.

Yes by putting an init method in the Command class and calling it from setup() the problem was fixed.

@user316182, Yes, I am sure that SerialEvent is not called from the RX char interrupt.  It is called from main, which just calls loop and then serialEventRun in the never-ending for loop.  You may as well just call your serialEvent code from loop.  Sadly enough, there was a time when SerialEvent was dispatched from the IRQ, but it was later moved to main. See this commit.  :-(

@slash-dev "...Also, using SerialEvent is no better than doing the polling in loop()." Are you sure about that? SerialEvent (and especially the ones on Teensy3) use hardware interrupts which can be handled in the midst of other operations; even delay() does not block interrupts (http://playground.arduino.cc/Code/AvoidDelay). It's hard to imagine multiple serial streams running at 100 kbaud or better (test reported in PJRC forum) and handling each character in the main loop even if that was all your program did. And why would you want to? There are good reasons interrupts exist.
Update: I'm not allowed to "comment" without 50 reputation. Thanks for the commit link... I can't imagine why HardwareSerial would not use interrupts... that is the default on all other platforms we've used for years.

Uhh... did you notice you were pressing the "Add Another Answer" button?  There is an "add a comment" button below my answer that you should have used.  I have replied above, in a comment to my answer.


text:
Does WiFiClient work on a Yún to send data over a certain IP and port to be received by a Python socket?
I haven't been able to get the example code from the page WiFi:Client:connect() to work on my Arduino Yún. Is this not how I'm supposed to send data over WiFi to be read by something like a socket?
If not, how would I go about doing so? (This is the only solution I've found from the internet).

No, that code is only for the WiFi shield.  For the Yun you need to look at the Bridge library that is bundled with the IDE. It allows you to run commands and perform actions on the Linux based Atheros portion of the Yun which is what has access to the WiFi.


text:
Bootloader only works once with usb to serial module
When programming the Pro Mini using this USB-to-serial adapter the boot loader only works once. After the first programming the programmer is out of sync or not responding.
To be able to program the Pro Mini again I have to burn the bootloader using my Uno as an ISP.
Programming the Pro Mini through an Uno does not present the same problem.
Are the lock bits not being set properly or somehow overridden?

Does that adapter really have a DTR signal?

Please show your full wiring.

I actually have the same adapter and it does not have the DTR signal. Therefore it cannot be used. A reset signal cannot be generated. The adapter has 3.3V, RST, TXD, RXD, GND and 5V. The RTS is not the same as DTR.

It does NOT have a DTR signal. Thank you for your help. Will order one that does.

Make sure you add the inline 100nF capacitor in the DTR line or the newer versions of avrdude will fail miserably.

@mikepatel.  It is not true that RTS will not work.  Using it is mentioned in official arduino guides: https://www.arduino.cc/en/Guide/ArduinoMini  this sounds more like a fuses problem with the bootloader memory not being preserved.

The module I had does not have a DTR signal. I mistook the RTS for DTR. Ordering correct module.

You have received faulty advice. The RTS signal is usable, and in fact used in official guides. Your problem is likely something else.

It sounds likely that the OP (long since gone...) was resetting the board manually to get the bootloader to run even that once; and that the bootloader allowed itself to be overwritten, a critical fuse got changed, or that one successful upload otherwise left itself or the board in an un-bootable state.

no. the problem is OP didn't reset (see his answer), but a fresh bootloader doesn't need reset to bootloader


text:
How to read temperature from multiple DS18B20 faster?
I am writing an Arduino sketch to read temp data from multiple DS18B20 sensors and then write it to serial. The problem is, as I am connecting more sensors, the delay between my temp data is written to a serial increases (like 100ms for 1 sensor and 1s for 4 sensors). Can I somehow improve my sketch to read it faster?
Here is the sketch I am using:
(I am using DallasTemperature to simplify it all)
#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 10
#define TEMPERATURE_PRECISION 8
#define BAUD_RATE 9600

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// arrays to hold device addresses
DeviceAddress devices[10];
int devicesFound = 0;

void setup(void)
{
  // start serial port
  Serial.begin(BAUD_RATE);
  //Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();

  // locate devices on the bus
  Serial.print("Locating devices...");
  Serial.print("Found ");
  Serial.print(sensors.getDeviceCount(), DEC);
  Serial.println(" devices.");

  devicesFound = sensors.getDeviceCount();

  // report parasite power requirements
  Serial.print("Parasite power is: ");
  if (sensors.isParasitePowerMode()) Serial.println("ON");
  else Serial.println("OFF");

  for (int i = 0; i < devicesFound; i++)
    if (!sensors.getAddress(devices[i], i))
      Serial.println("Unable to find address for Device" + i);

  // show the addresses we found on the bus
  for (int i = 0; i < devicesFound; i++)
  {
    Serial.print("Device " + (String)i + " Address: ");
    printAddress(devices[i]);
    Serial.println();
  }

  for (int i = 0; i < devicesFound; i++)
    sensors.setResolution(devices[i], TEMPERATURE_PRECISION);
}

// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
  for (uint8_t i = 0; i < 8; i++)
  {
    // zero pad the address if necessary
    if (deviceAddress[i] < 16) Serial.print("0");
    Serial.print(deviceAddress[i], HEX);
  }
}

// function to print the temperature for a device
String printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC < 10)
    return "0" + (String)tempC;
  else
    return (String)tempC;
}

// function to print a device's resolution
void printResolution(DeviceAddress deviceAddress)
{
  Serial.print("Resolution: ");
  Serial.print(sensors.getResolution(deviceAddress));
  Serial.println();
}

// main function to print information about a device
void printData(DeviceAddress deviceAddress)
{
  Serial.print("Device Address: ");
  printAddress(deviceAddress);
  Serial.print(" ");
  printTemperature(deviceAddress);
  Serial.println();
}

void loop(void)
{
  if (devicesFound == 0)
  {
     Serial.println("No devices found.");
     return;
  }

  sensors.requestTemperatures();

  String sent = "";

  // print the device information
  for (int i = 0; i < devicesFound; i++)
  {
    sent += printTemperature(devices[i]);
    if (i != devicesFound - 1)
      sent += " ";
  }

  Serial.println(sent);
}

A trivial change, but I think it's cleaner:  Where you are adding spacing to the string, I'd use if (i) sent += " ";  as a statement before the statement adding the reading to the string, instead of the statement you currently have after

With 12 bits precision, DS18B20 may take up to 750 ms converting a temp.
Try using async reading, so you don't have to wait for the end of the process.
First you ask for a reading, later your read it
    DallasTemperature sensors(&oneWire);
    ...
    sensors.setWaitForConversion(false);  // makes it async
    sensors.requestTemperatures();
    sensors.setWaitForConversion(true);
    ...
    // Do something else while temp is been reading by the sensor
   ...
   float temp = sensors.getTempCByIndex(0);

Does the getTempByIndex function build in the  wait-for-complete or are you assuming your "do something else" section is longer than a conversion?

I would start by changing this section:
String sent = "";

// print the device information
for (int i = 0; i < devicesFound; i++)
{
  sent += printTemperature(devices[i]);
  if (i != devicesFound - 1)
  sent += " ";
}

Serial.println(sent);

This section should read and print the temperature directly instead of creating a string. The string handling is a large overhead and it does not allow Serial (UART) to work very much in parallel if the buffer is filled. The printTemperature() function is using a lot of strings (and heap operations).
Otherwise you have done what is possible; 1) reduce the conversion resolution (9-bits is minimum), 2) use single conversion request command to all sensors.
The alternative is to use alarm triggers and only read sensors with alarms.

like that http://pastebin.com/NubeaW4M ?

What are the results of that? I did some tests and it is possible to issue a conversion request, read and print the results from 48 sensors at 9-bits resolution and 14 sensors at 12-bits resolution (per second).

delay is still the same

Can you scale it down to a single sensor and measure the conversion request and reading of scratch pad? We need to isolate the issue in the library that you are using.

So, I changed my sketch this way: http://pastebin.com/7EADdVAu, and it shows that around 110ms has passed while reading one sensor.

For 5 sensors it now shows values around 163ms, that's strage, it was bigger when I ran it earlier.


text:
RGB Led - mixing colors using analogWrite
Currently I'm controlling an RGB LED with my Arduino Nano.
I'm mixing the colors using analogWrite
Though, the LED's don't light up at all for low analogwrite values and the difference between the levels is not visible (to me).
I'm using 100 Ohms resistors between the LED's, using a 680Ohms didn't seem to make a difference.
Analogwrite is working by toggling the LED's fast (PWM)? So not by lowering voltage? This is why I think it's weird that they don't light up at all, on low write values.
My sketch below:
#include <SoftwareSerial.h>

int r, g, b = 0;
String command = "";
const byte rxPin = 11;
const byte txPin = 10;

SoftwareSerial blueTooth (rxPin, txPin);

void handleCommand() {
  r = rgbFromCommand("r=",";");
  g = rgbFromCommand("g=",";");
  b = rgbFromCommand("b=",";");

  if(r != -1){
    analogWrite(A2,r);
  }
  if(g != -1){
    analogWrite(A1,g);
  }
  if(b != -1){
    analogWrite(A0,b);
  }
}

int rgbFromCommand(String prefix, String postfix) {
  int idx = command.indexOf(prefix);
  int endIdx = command.indexOf(postfix,idx);
  if(idx>=0 && endIdx>=0){
    idx+=2;
    return command.substring(idx,endIdx).toInt();
  }
  return -1;
}

void setup() {
  pinMode(rxPin,INPUT);
  pinMode(txPin,OUTPUT);
  Serial.begin(9600);
  blueTooth.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    // read the incoming byte:
    char incomingByte = Serial.read();

    if(incomingByte == '\n'){
      handleCommand();
      command = "";
    }else{
      command += incomingByte;
    }
  }
  if(blueTooth.available() > 0){
        // read the incoming byte:
    char incomingByte = blueTooth.read();

    if(incomingByte == '\n'){
      handleCommand();
      command = "";
    }else{
      command += incomingByte;
    }
  }
}

Analog pins aren't PWM pins. Instead you have to use the pins marked with a ~
Pins that aren't PWM pins will be off with a value of 0-127 and on with a value between 128 and 255.

Ah, analogWrite and analog pin caused the confusion!
Also, I find it rather weird that it doesn't cause (atleast) a warning.
I'm using an Arduino Nano, and the silkscreen on it is also rather unreadable. I thought it could be the resolution of the analogWrite, as it did work in native C++ (because I did use the hardware PWM and pins (as at that point it made sense to read the datasheet ;) ))

Yup, found the right pins, now works like a charm (https://www.youtube.com/watch?v=iJPvMaQH3D4) many thanks!


text:
Working with Seed BLE Shield and Adafruit Feather BLE
Long story short: I need to pair these devices:

Arduino UNO with Seeed BLE Shield
Adafruit Feather 32u4 Bluefruit LE.

The Seeed shield is configured and able to connect and communicate via the UART to an Android phone by HM BLE Terminal app from Google Play Store.
I can also connect the phone and Feather. The two independent connections work really well but a problem occurs when connecting the Seeed shield with Feather. Connection isn't troubling No errors are reported but I can't send/receive any data via the serial monitor (I'm using bleuart_cmdmode or bleuart_datamode from the Adafruit examples).
Basically my question is how to make them work: HM-11 module with BLE and the Adafruit board (nRF51822 chipset from Nordic).

Although the nRF51822 supports Central (master) mode, the Adafruit Feather's firmware only support's Peripheral (slave) mode.

The Bluefruit LE firmware from Adafruit is currently peripheral only,
  and doesn't run in Central mode, which would cause the module to
  behave similar to your mobile phone or BLE enabled laptop.
At some point we might consider a new firmware image offering this,
  but since 98% of the uses cases for BLE involved running as a
  peripheral we've concentrated all of our development effort there for
  now.
https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/faq#faq-2

The HM-11 on your Seeed shield is capable of Central (master) mode though. This means your Uno will play the part that your Android phone was playing when you connected the Feather to the terminal app.
To set your HM-11 to Central mode, run the following AT command.
AT+ROLE1

Example code for the HM-11

Alternatively, you could burn the S120 Soft Device and your own custom firmware onto the Feather's nRF51822. You can find all the docs, tools, and Soft Device images on Nordic's website.


text:
Clearing SRAM in loop()
Very broad question here.  I don't know exactly what the problem is but I'll edit this post as we narrow down the possibilities.
I think I'm running into memory constraints.
I'm running a sketch that records two temperature values every 60 seconds and transmits them to an AWS RDB via wifi.  It works well for about two hours then stops.  I don't know if it's a memory constraint but I suspect that it is.  What other common problems (often overlooked by newbies) can cause a sketch to end after a couple hours of run-time?
Is there a simple way to add an instruction to a loop to clear the SRAM?
Arduino UNO + WiFi 101
Edit #1 12/24/2015:It's the WiFi board.  It happily remains connected to my phone's hotspot but only lasts an hour or two on my home network.  Working on root cause...any ideas are welcome!
Edit #2 12/25/2015:Tried to Wifi.disconnect() and reconnect with no luck.  Why do some networks kick the board off while others work just fine?  Will look into the watchdog.

Sounds like maybe you need to implement watchdog reset.

Do you have a link for a decent tutorial?

Look in the log file in WiFi access point for an error message that might guide your debugging.

The problem was solved with a "soft restart" loop. Posts #10 and #11 are all I needed:
http://forum.arduino.cc/index.php?topic=49581.0

Could you provide your sketch? At the rate you mentioned, 2 hours is merely 240 values and this shouldn't even matter since you are probably reassigning values to the same variables and not storing them in some growing array. Perhaps your WIFI shield merely gets disconnected from the network. How do you mean the sketch stops? Like you no longer receive the values in the database? More info is needed.

Good point. I'll try the simple thing first. I'll let it run on my phone hotspot for a few hrs and report back.  I'd also like to avoid posting the sketch...I don't want a spoon-fed answer.


text:
Small, Power-Efficient wireless communication with ATTiny85
For a project that I'm working on I need an extremely small, power efficient wireless device (could be radio, or some other interface) to network between a series of ATTiny85s and a larger Arduino. The communication range only needs to be about 1 foot, max. I'm currently using wired I2C, so it would be excellent if someone could suggest a radio or another device that can use the two digital pins previously occupied by the SCK and SDA lines on the ATTiny. I have those two, along with one extra digital pin available for use.
This device needs to be extremely small - this common NRF24L01 package is too big and its SPI interface uses too many pins.
Thanks for your help.

There are ways to interface with a NRF24L01 with ATTiny85 with reduced pin usage plus you could use a ceramic antenna and cut off the large SPI header. It is possible to turn a NRF24L01 really small.

An RF kit like this one. It's a 2-part kit, Tx and Rx separately -- each needing Vcc, GND and one pin. You need both on each ATTiny to be able to transmit and receive.

A similar product but a lot smaller would be the SYN115 and SYN480R based modules. These are however dumb devices, so you need to implement a protocol for them, and handle/prevent collisions, have some data integrity protection, etc.

Definitely. And that will eat up precious memory -- more code...

Link is dead.  Instead of saying something "this one" can you give a model number that can be searched?

I've also had good results with using the Mchr3k - Arduino Manchester Encoding library with those 315mhz RF kits. It has support for ATTiny85 as well.


text:
Arduino Micro project with Bluetooth low energy
I created my project prototype with Arduino Micro and Adafruit Bluetooth low energy device.
Now I need to develop the prototype to production (like a small USB device). I just need Rx, Tx, 3V pin from Arduino Micro.
I started design with ATmega32U4, USB and BLE by using Fritzing IDE. I am confused with Arduino Micro parts like reset, bootloader and other pins. Is there any problem if I leave the unwanted pins from Arduino unconnected, for my project? Will it work correctly like a Arduino micro?
This is my first PCB design. Please help me to design a final PCB with the unwanted pins left unconnected.

Can you be more specific about what the problem is? Also, do you plan on sending the board out to be manufactured in one of those popular board fabrication shops online, or do you intend to build it yourself?

Thanx. @Ricardo.  Problem.is it need all part in arduino micro for my product production because I wana make my usb device is smallest as possible.  And also I dont know where  I connect 3.3 volt from regulator in atmega32u4.  Please hrlp through schematic diagram. I try to design my self and send board ptoduction through fritzing

How about using a RFduino SMT Module (www.rfduino.com) or something similiar?!

I have started to look at the Arduino Uno schematics, which are free on the website. To make an Arduino is very simple, just need the chip, crystal, a few capacitors and that's it.
Try to copy the same schematics then add the Bluetooth to the RX and TX pins, but be careful about the 3.3V as you don't want to fry your Bluetooth module :)


text:
Arduino hangs after less than a minute, but not on USB
I have arduino uno + ethernet shield + 9V/200mA adapter. I am trying to send some data with HTTP connection. When it's connected to USB it works perfectly, but when I plugged out USB, hangs (after less than a minute, it stops pinging).
I have tried this:
EthernetClient.cpp

int EthernetClient::connect(IPAddress ip, uint16_t port) {
  if (_sock != MAX_SOCK_NUM)
    return 0; // i changed to -1  as suggested on previous link

  for (int i = 0; i < MAX_SOCK_NUM; i++) {
    uint8_t s = socketStatus(i);
    if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT || s == SnSR::CLOSE_WAIT) {
      _sock = i;
      break;
    }
  }

and also example from library Examples-library-WebClientRepeating, but I get the same problem as in my code.
Is my adapter too weak?
This code is from Example WebClientRepeating:
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED    };

// fill in your Domain Name Server address here:
IPAddress ip(193, 77, 60, 66);
IPAddress subnet(255, 255, 255, 0);
IPAddress gateway(193, 77, 60, 7);
IPAddress myDns(193, 77, 60, 213);

EthernetClient client;

char server[] = "www.arduino.cc";
//IPAddress server(64,131,82,241);

unsigned long lastConnectionTime = 0; // last time you connected to the server, in millisecond
const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

void setup() {
  // start serial port:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // give the ethernet module time to boot up:
  delay(1000);
  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip, myDns, gateway, subnet);

  // print the Ethernet board/shield's IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  if (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if ten seconds have passed since your last connection, then connect again and send data:
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP PUT request:
    client.println("GET /latest.txt HTTP/1.1");
    client.println("Host: www.arduino.cc");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();

    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}

EDIT 1:
Also when I plug USB in its start working with 9V power adapter.

Is the voltage regulator on the Arduino very hot, or the external 9V adapter very hot, when it stops pinging? Maybe it is likely one or the other failing. Are the LEDs on the Arduino and shield still on? It might be worth blinking a LED to ensure you can see what is working.

Arduino voltage regulator is not so hot, it's touchable. Leds on arduino are ok but on ethernet shield is only first one on, data lights are off.

Then it is probably not power a power problem. Can you measure the voltage on the Arduino's 5V pin? For example, have you a multi-meter? That would confirm or disprove the power supply theory.

I'm pleased it's working and stable, even if my answer was wrong :-) Merry Christmas!

The problem is that when you are using the external 9V power supply, you are relying on the Arduino's on-board regulator to provide the 5V power supply to both the Arduino and the Ethernet shield. This regulator has very limited current capacity — much less than the 500 mA that's available from a PC's USB port — and you're overloading it.
To avoid this problem, you should use a 5V plug pack with a USB connector to power your system.

I think your description of the cause is slightly incomplete, and so may be misleading for others. Tests show the Arduino UNO's on-board regulator can supply 500mA at 9V, see the Arduino UNO temperature vs current graphs FTDI NerO. It should be easy for the OP to diagnose this as the voltage regulator should be very hot. If this is the case, I agree your solution should work.

Arduino voltage regulator was hot, it was in box. When i get Arduino out, it starts working. So i change 9V adapter With 5V 1A and now is working fine. I'll test it over night. Thanks

It may be that, for some reason, the library thinks Serial communication is working, but when the buffer of unsent characters gets full, it hangs waiting to complete a Serial.print() or Serial.println().
So, try commenting out all use of Serial.
For example change
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

to
  /*
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  */

and Serial.println(...); to // Serial.println(...);
This might happen if the system is started with USB working, and then USB is unplugged.


text:
Combine bits from two ports into a single byte
I'm attempting to read the values of 8 pins at a time into a byte.
The obvious answer to this seems to be the Port registers, however with the way the Arduino is wired, I'd have to split my read across two registers.
In this case, I need a way to combine the lower 5 bits of PORTB with the upper 3 bits of PORTD into a single byte.
For example, this is the physical layout with the data lines I'm attempt to read/write to and their corresponding port assignments.
             SCSI
DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0
|   |   |   |   |   |   |   |
PB4 PB3 PB2 PB1 PB0 PD7 PD6 PD5
            AVR

From what I can gather I need to use some shift operators to achieve this,
perhaps something like:
hi = PORTB & 3;
lo = PORTD >> 3;

But I'm unsure if that's correct and then how I would combine them.
Is it possible to write a macro to make getting and setting this byte easier?
Is there a good learning resource on bit manipulation like this?

OK thanks to Excel (had no idea I could do bit operations in it) I've worked out this would probably give the correct value for reading.
(PORTB & (32-1) << 3) | (PORTD >> 5)
but I'm still uncertain how to go about it for writing.

We overlapped. Is my answer clear enough, or do you need some more?

Hi gbulmer. Thanks for the answer. Indeed it's clear enough. I like method you've got for showing which bytes are being manipulated. Very clever. The only thing I need to think about is writing back to the ports without overriding, say, the serial ports.

Assuming PORTB and PORTD are correctly giving unsigned char values:
result = (PORTB << 3) | (PORTD>>5)

would do it.
As a macro:
#define SCSIBITS ((PORTB << 3) | (PORTD>>5))

Then use like this:
result = SCSIBITS

To make it clearer which specific bits are being used, write:
#define SCSIBITS (((PORTB & B00011111) << 3) | ((PORTD & B11100000) >> 5)))

It should be easier to see that the lower 5 bits of PORTB, and the upper 3 bits of PORTD are being used.
In the general case, where the values being manipulated are not unsigned char (should not be a problem in this specific case, but may be helpful to know), you might write:
#define SCSIBITS ((unsigned char)((PORTB & B00011111) << 3) | ((PORTD & B11100000) >> 5)))

or:
#define SCSIBITS ((((unsigned char)PORTB & B00011111) << 3) | (((unsigned char)PORTD & B11100000) >> 5)))

Here are a few links to bit-manipulation tutorials:
https://www.hackerearth.com/notes/bit-manipulation/
http://www.cprogramming.com/tutorial/bitwise_operators.html
http://www.tutorialspoint.com/ansi_c/c_bits_manipulation.htm

Thanks for that. I really like the little trick there to show which bits are being manipulated. Those resources look good too, though I must admit that playing with the Excel bitwise functions and getting a real-time result really made what was happening much more obvious than reading various pieces on the matter.


text:
Compare const char * to const char
Using ArduinoJson I have assigned a value such as;
const char* id = root["id"];

in the original JSON id was "1"
if (strcmp(id, "1") == 0) {
    // this executes
}

I have an array of structs that I wish to compare the id against. The struct looks like;
typedef struct  {
   char id[2];
   ....
} Device;

I assign an id (1-9) into the struct id by
_cmd.id[0] = '0' + (++DevicesPtr);
_cmd.id[1] = '\0';
Devices[DevicesPtr-1] = _cmd;

where _cmd is of type Device. Devices is an array with up to 8 entries
Now I try to find a match in the devices using the JSON id
for (byte i = 0; i < DevicesPtr; i++) {
    if (strcmp(Devices[i].id, id) == 0) {
       // This code does not execute
    }
}

I can't seem to get a match I have also tried (Devices[i].id == id)

Strcmp is the way to go, but I'm not sure your code is giving away what the issue is, Mikaels answer is a more explicit version of what I imagine your code looks like. I presume you initialize DevicesPtr to 0 at some point? Mikael is also renaming your variables to more useful names another good idea : Could you post the code in full?

Try something like this:
typedef struct  {
  char id[2];
  ....
} Device;

const int DEVICES_MAX = 8;
Device Devices[DEVICES_MAX];

for (int i = 0; i < DEVICES_MAX; i++) {
  Devices[i].id[0] = '1' + i;
  Devices[i].id[1] = 0;
  ...
}

for (int i = 0; i < DEVICES_MAX; i++) {
  if (!strcmp(Devices[i].id, id)) {
  ...
}

Cheers!

You can't compare a char and a string.. How can you compare apples and bananas?
Now, you have two ways to do your job.
1) do as @Mikael Patel suggests, so convert your ids into strings. This is fine because it will allow you to deal with multiple chars ids.
2) a more efficient way to do this (note that this works with just SINGLE CHARS IDS) is the following one:
if (strlen(id) == 1) {
    for (byte i = 0; i < DevicesPtr; i++) {
        if (Devices[i].id == id[0]) {
           // This code will execute if ids match
        }
    }
}

Note that id should be exactly 1 char long, otherwise the whole comparison as you thought is meaningless
With this solution you don't need multibyte id char in the struct definition, so you can just define
typedef struct  {
   char id;
   ....
} Device;

and, in the code,
_cmd.id = '0' + (++DevicesPtr);
Devices[DevicesPtr-1] = _cmd;

Actually this can be improved further. The id field in the struct is not needed as the index is a function of the value (i.e. index = id - '1'). The test is simply that the index must be in [0..last_device] and last_device in [0..MAX_DEVICES-1]. A search is not really required if the id is ['1'...'9'].


text:
Arduino Nano gives 7V on the 5V PIN!
I have an Arduino Nano which is Powered by an external Power supply. This is connected with VIN and GND. The voltmeter says, there are 12,12 V
I have some components connected on the 5V PIN, which altogether draw max. 100mA
Since some of the components are not working anymore, I started measuring...
I have disconnected everything, but the Arduino Nano Power supply. (12,12V)
When I now measure GND and the 5V PIN, the Voltmeter says 6,97V! I guess this is why my components are giving up.

But why are there 6,97 Volts all of the sudden?
Is my Arduino broken now?
Can I fix this?
How can this happen?

I think you should check your voltmeter as the 5v regulator of the nano will not be outputting ~7v

How did you connect it? Try a 5V source on the USB (just a phone charger or USB connection).

Just a stupid question: are you sure you are measuring from 5V to ground and not from 5V and 12V? Because 12V-5V=7V, and I think that's a strange coincidence..

Thanks for the comments. When Powering with USB from PC I have 4,2 V, but that is normal I think. I am 100% sure that I am measuring right and that the voltmeter is fine. :) Also one of the components that is connected with 5V burned through... so there is definately too much voltage on that pin! After the christmasholiday-break I will take a picture for proof ;) Also I tried another Arduino Nano, and there the Power is 5,02 V. So it seems the other one is definately broken.

The 4.2V is a bit too low too. I guess the regulator is broken.

Of course the 5V regulator on the nano can be faulty. Another possibility is the 5V decoupling capacitor. If it goes open circuit the regulator will oscillate and the mean output voltage will be near half the input voltage. Most regs have a minimum decoupling cap value specified.

Since I am using a cheap china-copy instead of an original Arduino, I guess this is exactly what happened.


text:
Serial Communication to Arduino with Node.js
I ran into some strange problems while trying to send data from my Node.js Server to my Arduino. My goal is to transfer an Int to the Arduino Nano and display it on a LCD. So far I managed to connect the server with the Arduino with the help of the serial library. The Arduino returns all data sent to it via Serial and prints it bytewise to the LCD.
These are the problems:

Node.js always opens the port, but is only able to send and receive data when the Serial Monitor from the Arduino IDE is opened.
The Data Node.js is sending seems to have a special format or gets transformed during the Process. If I send a simple int like 2, the display shows a y and an undecipherable character, and the data returned looks like this:  49 50 49 13 10 48 13 10. I noticed that the amount of 13 corresponds with the int I send (3 send = three 13's come back). When I enter data into Arduinos own Serial Monitor, it is displayed correctly and returned as ASCII (because I am saving the return value of Serial.read() as an Int).

Here's my server (the relevant parts):

http = require('http');
fs = require('fs');
serialport = require('serialport');

port = 3000;
host = '127.0.0.1';
SerialPort = serialport.SerialPort;
arduinoPort = '/dev/ttyUSB2';

var printLog = true;
var playerRoundKills = 0;
var playerTotalKills;
var roundLive = false;

//open port
var myPort = new SerialPort(arduinoPort);
parser: serialport.parsers.raw          //rohdatenparser definieren
serialport.on('open', function(){
  console.log('Serial Port Opend');
  serialport.on('data', function(data){
      console.log(data[0]);
  });
});

//implementation of abstract port functions
myPort.on('open', showPortOpen);
myPort.on('data', sendSerialData);
myPort.on('close', showPortClose);
myPort.on('error', showError);

function showPortOpen() {
   console.log('port open. Data rate: ' + myPort.options.baudRate);
}

//output incoming data
function sendSerialData(data) {
   console.log(data[0]);
if(typeof data[1] !== 'undefined') console.log(data[1]);
}

function showPortClose() {
   console.log('port closed.');
}

function showError(error) {
   console.log('Serial port error: ' + error);
}

myPort.on("open", function () {
  console.log('open');
//send data (3) to arduino
myPort.write(3, function(err, results) {
    if(err != null)console.log('Fehler beim ersten senden: ' + err);
    if(results != null)console.log("Killcount erstmals gesendet: "+results);
  });
});

And my sketch:
#include <LiquidCrystal.h>

//LDCD Display
LiquidCrystal lcd(9, 8, 6, 5, 4, 3);  //Digitale Pins an dem das Display angeschlossen ist
#define LCD_WIDTH 16                    //Anzahl Spalten des Display (16)
#define LCD_HEIGHT 2                    //Anzahl Zeilen des Display (2)

#define DEBUG_MODE true

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

  lcd.begin(LCD_WIDTH, LCD_HEIGHT,1);

  lcd.setCursor(0,0);

}

void loop() {
  // when characters arrive over the serial port...
  if (Serial.available()) {

    //clear display for new killcount
    //lcd.clear();
    // wait a bit for the entire message to arrive
    delay(100);
    // read all the available characters
    while (Serial.available() > 0) {
      // write each character to display as ascii
    int temp = Serial.read();
    lcd.write(temp);
    Serial.println(temp);

    }
    //Serial.flush();
  }
}

I'd appreciate any suggestions! =)

49 50 49 13 10 48 13 10 are ascii codes for :
"1" "2" "1" CR LF
"0" CR LF does that give you a clue ?

I solved that by passing the data in a Buffer. The connection only works when the arduino terminal is opened though.

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


text:
FFT (or similar) library for the Arduino
I'd like to build a "low fidelity" spectrum analyzer to run on an Adafruit Trinket Pro. My primary goal is to intrigue my seven year-old niece with something that can be hacked. The plan is to pick up sound from a violin with a mic and use a set of 5 or 6 NeoPixels to represent octaves and use color for amplitude.
My first pass at this used Amanda Ghassaei's frequency detection code. It kind of worked, but seemed to be having problems with complex waveforms. After doing some more reading and looking at simple spectrum analyzers it seems that I'd do better using something like a FFT to collect the frequency information. It also seems that that might be stretching the capability of an Arduino…
Are there any FFT libraries that run well on the Arduino (over a range of about 200 to 4000 Hz)? Or are there other approaches that might work better?

A Trinket might be too slow; there are a number of FFT libraries for things like the Teensy which runs at 72MHz+, as in this Adafruit article

I tell a lie, there do appear to be ones that run on slower processors. This article, also from Adafruit, describes one that samples at around 9.6kHz, which should be enough for up to 4.8kHz analysis.

DFT is an alternative to FFT.

Thanks! As I understand it the DFT is simpler (as in easier to understand the math) than the FFT, but the computational requirements are heavier (O(N^2) vs O(Nlog2(N)), so I think, between the two I'd want to use the FFT – but I am in way over my head here…

I havent used any of the libraries to make the FFT for my personal project, due to complexity. Instead I bought a spectrum chip, which returns 7 frequencies: MSGEQ7  ( 63Hz, 160Hz, 400Hz, 1kHz, 2.5kHz, 6.25kHz and
16kHz ).
Otherwise if you are very keen on using a library, this one is very famous and fast for Arduino processors.
But again, if you dont need to have a precise band and the MSGEQ7 is good enough to detect what you want, go for it.

The MSGE!7 is appealing. I wish I knew where to get one short notice.

I think ebay or maybe from RS or Farnell


text:
How to make an SMS notification to my phone with Arduino Uno?
I am planning to make an SMS notification to my phone with Arduino Uno via a push of a button.
I have an Arduino Uno C520A Embedded System. Is it possible to do so with this model ? If yes, which WIFI module should I get ?
I just want to make an API request to the web through the push of a button.

You're going to need a GSM module and working simcard.

Check the specific devices datasheet for the (usually serial AT) commands.

there are 100's of tutorials, just check them out on YouTube/blogs. Search for: Arduino send SMS.

How is the SMS notification related to the WiFi API requests?

It is possible if your provider has a sms gateway e-mail-address. Just google which it is for your provider (e.g. number@tmomail.net for T-Mobile (US)). And there should be a lot of tutorial about how to send an email with an arduino.
Every wifi-module with arduino support will work if your WiFi is a standart 3.6Ghz. And yes it should work with any arduino compatible microcontroller.

Arduino uno is only the processor, you will need a Ethernet shield or Wifi shield to connect to the internet.
I would suggest Ethernet as it is less pain to configure and no drop of connection.
Then you will need to buy a sms gateway, this one looks pretty cool as they have good http api.
By using the Arduino Ethernet sample, you will need to send a http request to the server when the button has been pressed.


text:
Creating a library for attiny85 out of working program
Apologies if this is the wrong sub-forum, the involvement of ATTiny and arduino places this into a strange category. Please correct me if I should post elsewhere.
It is important for this to be a library as small kids will be using this program and hardware for their own projects. Its kind of a rip on the LOLshield but it involves a lot more steps to integrate more lessons all at once.
My whole program takes 8 bytes of information and converts it to data for a shift register driving two multiplexers all driving an 8x8 LED matrix. It can also use multiple of these packets to make a slide show. I have it in a working state right now and would like to turn it into a library for easy use. I am a bit lost in this step as I had to create an interrupt timer and this makes it more complicated than the tutorial on the arduino website covers.
Also if someone could point me to a library for ATTiny85 that makes calling a timer interrupt easy then the rest of this project will likewise become easier.
Any help would be great! I will be continuing to look on online resources and will update should I figure it out.

I would just implement a callback and tell the consumer "call this callback every so often, preferably with a timer interrupt".

Ok could you direct me to a timer interrupt library compatible with the ATTiny85 then? Programming an interrupt for the attiny85 is stupidly messy to a new programmer.

Nope. But it should be easy enough to port something like Timer1 to arduino-tiny.

Already looked into it, it's not. I'm not exactly a great coder in the first place, this is a learning experience for me.

I had to create an interrupt timer ...

Be warned that there are things you should not do in interrupts, like delays, serial printing, etc.

Code
In the interests of answering the question though, this works:
// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

ISR (TIMER1_COMPA_vect)
  {
  digitalWrite (4, ! digitalRead (4));  //toggle D4 (pin 3 on chip)
  }

void setup()
 {
  pinMode (4, OUTPUT);  // chip pin 3

  // Timer 1
  TCCR1 = bit (CTC1);   // Clear Timer/Counter on Compare Match
  TCCR1 |= bit (CS10) | bit (CS13);  // prescaler of 256
  OCR1C = 123;          // what to count to (zero-relative)
  TIMSK = bit (OCIE1A); // interrupt on compare

  }  // end of setup

void loop()
  {
  // other code here
  }

You can tweak the time delay by changing both the prescaler and the counter in OCR1C. The prescaler gives you coarse tuning, which gets you into the ballpark of the delay time. The timer then counts up to give you the final delay.

Prescaler values
From the datasheet:

In my case I chose a prescaler of 256 which is or'ing together CS10 and CS13.
The delay is then:
125 ns * 256 * 124 = 3.968 ms

Where 256 is the prescaler and 124 is what we are counting to. This is assuming an 8 MHz clock which gives a clock period of 125 ns.

Flashing more slowly
If you put an LED on pin 3 and want to see the flashing, you need it much slower. For example:
TCCR1 |= bit (CS10) | bit (CS11) | bit (CS12) | bit (CS13);  // prescaler: 16384

That toggles the pin every 254 ms, which is visible.

Warning
On this chip Timer 1 is an 8-bit timer, so you cannot put more than 255 into OCR1C.

More information

Timers
Interrupts

Wow that answer was above and beyond what I expected! All this info is super useful! I'll be putting it to good use, hell this post should be put somewhere where more people will see it too!


text:
How to send a pitch bend MIDI message using arcore?
I'm new to MIDI and started playing with an Arduino Leonardo and arcore.
Based on the example code, I can easily send noteOn/noteOff/controlChange messages, but I can't seem to send a pitch bend message.
Having a look at this table:
0xE0    Chan 1 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE1    Chan 2 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE2    Chan 3 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE3    Chan 4 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE4    Chan 5 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE5    Chan 6 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE6    Chan 7 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE7    Chan 8 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE8    Chan 9 Pitch wheel range    Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xE9    Chan 10 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEA    Chan 11 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEB    Chan 12 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEC    Chan 13 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xED    Chan 14 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEE    Chan 15 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)
    0xEF    Chan 16 Pitch wheel range   Pitch wheel LSB (0-127) Pitch wheel MSB (0-127)

I've tried to send a message like so:
MIDIEvent pitchwheel = {0xe0, 127,127};
MIDIUSB.write(pitchwheel);

but this didn't work and I'm not sure what I'm missing/doing wrong.
Any hints/tips will be helpful.

Please show the working code to send a note-on message.

arcore creator Ralf Kistner provided the answer:
// The pitch bend value is a 14-bit number (0-16383). 0x2000 (8192) is the default / middle value.

// First byte is the event type (0x0E = pitch bend change).
// Second byte is the event type, combined with the channel.
// Third byte is the 7 least significant bits of the value.
// Fourth byte is the 7 most significant bits of the value.
void pitchBendChange(byte channel, int value) {
  byte lowValue = value & 0x7F;
  byte highValue = value >> 7;
  MIDIEvent event = {0x0E, 0xE0 | channel, lowValue, highValue};
  MIDIUSB.write(event);
}


text:
3.95 MCU Friend Arduino TFT LCD flickering
I got the 3.95" LCD from aliexpress which uses IL9488. I used the MCUFRIEND_kbv library. I am using an Arduino Mega as I need other GPIO to be used for other purposes. I can't use the Uno because of this limitation.
I have other modules like the DS3231, and ESP8266 connected to the Mega and this 3.95" LCD connected as well. ESP8266 is powered separately using a 12-5V converted supply. The Mega is powered using another source. The normal graphics test is working in the LCD. I am able to make it work with the Nano, Uno and Mega. Even for the Mega I am able to write customized messages.
What I intend to do is to update the time in the LCD which is received from the DS3231. It updates the LCD but I see a flickering issue here.
Every update (LCD display function is from the loop which sets the text when there is a second/time/hour difference in the time) seems like it draining more current as the one of the LED connected to Mega dims, the Rx/Tx LEDs also dim.
I am able to get the LCD refreshed but it shows a flickering. I powered the LCD 3.3V and 5V using another separate source but still the small flickering continues.
Moreover all these time I was connected to the Mega through the USB from the laptop. Once I unplug the USB, LCD starts and shows some update and again become white. This continues and an not able to see anything on LCD there after.
I am not sure why only when the Mega is connected to USB this LCD works and that too flickering but once the USB is removed the LCD is not working at all.
Can someone please do help me in this ?

Are you referring to an LCD on a shield, like LCD Display Module TFT 3.95 inch TFT LCD screen for Arduino UNO R3 Board?  Do you have a way to measure the current draw?

Yes, the same thing only I have. But I am supplying a separate 2amp supply to the LCD .And all the grounds are set together.Not sure whether that gonna be an issue. Thanks for the reply.

Do you have a schematic or picture of your connections?

I think something is wrong with this LCD board. This is because in my case the display works sometimes perfectly with the ILI9481 driver but sometimes something hangs and the display starts to flicker. It looks like a chip charging problem. Anyway I solved the flickering problem by tuning the ILI9488 registers. Simply you have to change the initlcd.h for ILI9481 driver in UTFT library.
enter code here

case ILI9481:

LCD_Write_COM(0x11);
delay(70);

LCD_Write_COM(0x38);//Idle Mode OFF
LCD_Write_COM(0x13);//Normal mode

LCD_Write_COM(0x36); // Memory Access Control  crucial
LCD_Write_DATA(0x0A);

LCD_Write_COM(0x55);
LCD_Write_DATA(0x22);//High enhancment of CE ratio

LCD_Write_COM(0xB1);
LCD_Write_DATA(0x70);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xB4);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xB5);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x12);

LCD_Write_COM(0xB6);        // Display Function Control
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x21);       // 0x42 = Rotate display 180 deg.
LCD_Write_DATA(0x3B);

LCD_Write_COM(0xC0);
LCD_Write_DATA(0x1F);//0X1F
LCD_Write_DATA(0x01);//0X10

LCD_Write_COM(0xC1);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xC2);
LCD_Write_DATA(0x00);//0X44 lower better
LCD_Write_COM(0xC4);
LCD_Write_DATA(0x00);//0X10

LCD_Write_COM(0xC5);
LCD_Write_DATA(0x00);//0X10
LCD_Write_DATA(0x80);//optimum
LCD_Write_DATA(0x80);//0X10

LCD_Write_COM(0x3A);//Interface Pixel Format
LCD_Write_DATA(0x55);

LCD_Write_COM(0x2A);//Column Address Set
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x01);
LCD_Write_DATA(0xDF);//320

LCD_Write_COM(0x2B);//Page Address Set
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x01);
LCD_Write_DATA(0x3F);//480

delay(60);

LCD_Write_COM(0x29);//Display ON
delay(30);

LCD_Write_COM(0x2C);//Memory Write
delay(30);
break;


text:
ERROR: Timed out waiting for Arduino 101 - anything I can do?
I just received an Arduino 101 so I did the following in a wave of excitement...

Connected the USB cable between it and my Macbook Pro
Started the Arduino IDE version 1.6.7
Wrote a little bit of code
Selected Tools | Boards | Boards Manager... and installed the Intel Curie Boards as per Getting Started
Selected Tools | Board: "Arduino 101"
Selected Tools | port: "/dev/cu.usbmodemFA141 (Arduino 101)"
Selected Sketch | Upload

I was expecting something amazing, but I got the error:
Starting upload script
Payload: /var/folders/jr/5rmqcrqj58103d4p1f6_3sjr0000gn/T/build7c6ce067b9e8a57f9917c651ec494989.tmp/orientation.ino.bin
Waiting for device...
ERROR: Timed out waiting for Arduino 101.

Is there anything I can do to debug this or did I miss a step perhaps?
(I tried the good ol' turn it off and on again, including shutting the IDE down).

Press the reset button next to the USB port. (either one, the master reset is between the DC jack and USB ).
This will cause the Arduino 101 to reboot and enter DFU mode for 5 seconds if it is connected on USB. The download will proceed when the Curie enters DFU.
The IDE uses a baud-rate signal over USB. It is a virtual serial port, so baud rate doesn't matter. But when the host side (Arduino IDE) switches the baud rate to 1200, the board will reboot and enter DFU mode for download. If it gets stuck for some reason and misses the message to reboot, you can just hit the reset button and accomplish the same thing.

If the path to your source file contains a space, it might be causing this error. For more information, and a workaround, see this topic in the Arduino forum.

I was having the same problem: unable to upload a program to a brand new 101.  Now it works.
I can successfully load both BLE LED example programs and also the ReadTime program read via Serial Monitor.  (BTW, using the iOS MCP app, you need to send either 00 or 01 to turn the LED on/off.)
I am running a modern 64 bit laptop with USB 3.0 ports.  All ports work fine with either of two USB cables that I have.  So I don't believe the problem is related to USB cables or USB 2.0/3.0.
How did I fix it?  Well, I tried several things and I'm not sure which one fixed it, so perhaps someone can try these methodically and confirm the best fix.

Uninstall the Arduino IDE and manually deleted the Arduino15 folder in user..\AppsData.
Restart laptop.
Download and install IDE 1.6.8.  (Earlier failed attempt was with current 1.6.9.)
Restart laptop.
Open IDE.  In Boards Manager, searched Intel, selected Curie boards, and install v1.0.4.  (Earlier failed attempt was with current 1.0.5.)
Restart laptop.
Open IDE.  Plug in 101 for the first time.  Device showed up normally in Device Manager.
Select proper port (COM5 for me) and proper board (101).  Select example file LED under CurieBle.  Click verify.  Looks good.  Click upload.  SUCCESS!  Can now see the 101 in nRF MCP, can turn LED on/off.  BLE functions now work with 5V USB charger. (but not 9V battery, guess that's not an option) When connected to laptop USB 3.0 port, the 101 now stays in COM5 the entire time, no longer cycling on/off when I try to upload.  No need to press either reset button during upload.

So the fix is either one of the software downgrades, or careful installation procedure.
Previously, I tried the dfu-utils updates but that didn't fix this problem.

I am running Ubuntu 18.04 and I had a similar problem but solved it in the end.
What worked for me was:

Update Arduino Curie driver in Boards manager to the latest version which is v 2.02 at the time of this post

Run the following command in terminal in order to grant execution rights:
 chmod +x ~/.arduino15/packages/Intel/hardware/arc32/2.0.2/scripts/create_dfu_udev_rule

Run the executable
 sudo ~/.arduino15/packages/Intel/hardware/arc32/2.0.2/scripts/create_dfu_udev_rule

Restart Arduino and try to reupload

Edit for Debian testing
At the time of this edit, all the previous steps work for the Bookworm distribution, with the latest Arduino IDE version (1.8.19) and the latest Arduino Curie driver version (2.0.5). Just remind to adapt the previous path according to the driver version.

I posted a fix here:
https://forum.arduino.cc/index.php?action=profile;area=showposts;u=1472279
I was really looking forward that this will be the fix for all Arduino 101 Error

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

Oh yes sure I will just copy and paste the steps here

I was really persistent to look for ways on how to fix the Arduino/Genuino 101 Timeout Error, I searched different forums and read a lot of suggestions on how to fix the error, but still all failed, I know some of the 101 users already bricked their 101 or other just left it behind.
We are all aware that the Arduino 101 is already discontinued and even support is already stopped, Hence this little but powerful microcontroller is still out there and probably used by the some. Anyhow, to be straight to the point I finally I discovered the fix for the error.
Notice that when you insert your 101 to the USB plug it will read and install the device, checking it in the device manager will show the Arduino/Genuino 101 in "Other Devices" and a new COMPort (COMX) is added, then you install the Arduino IDE (regardless of the version), then install the Arduino 101 Board thru "Board Manager", the manager will install the Arduino 101 but it will not notify you that the driver for Arduino 101 is not installed due to error. So in short we are assuming that the driver for Arduino 101 is successfully installed. This is where the error lies. The software driver "dpinst-amd64" is not digitally signed and Windows is blocking to install unsigned drivers.
So what's the fix?
The fix here is still to install the "dpinst-amd64" since it is the driver needed to recognize your 101, the trick here is you need to install it in other way, not in your regular PC operation. You need to access the "disable signature enforcement" under the startup options (not safe mode). This startup mode will enable you to install unsigned drivers (I trust this Intel Curie driver since it was downloaded with the board). After installation restart your PC to its regular startup and plug-in again your Arduino/Genuino 101, this time the PC will now recognize the microcontroller and you can now upload sketches without the time out error.
For a step by step procedure:

Access Update and Security>Recovery>Advanced Startup
Your computer will eventually restart and will bring you to the Advanced Startup, access Troubleshoot>Startup Settings. Your PC will restart again and options for the startup will display, choose number 7 "disable signature enforcement"
Your PC will start. Locate "dpinst-amd64.exe" in C:>Users>YOUR USERNAME>AppData>Local>Arduino15>packages>Intel>hardware>arc32>2.0.4(latest version)>drivers>dpinst-amd64
During installation a message will prompt if you want to install the unsigned driver, just click install.
After installation restart your PC and your Arduino/Genuino 101 is good to go.
To confirm that your Arduino/Genuino 101 is installed go to Device Manager and you will see that the Arduino/Genuino 101 is not anymore in the Other Devices.

I hope this will help. :D I will try to make a video about this fix. :D
Thanks!
Regards,
Raf

It's already documented in the arduino.cc, but I will just add here as reference:

Linux only: some distributions need to be configured to perform the
  upload. After installing the core, execute
sudo ~/.arduino15/packages/Intel/tools/arduino101load/1.6.4+1.18/scripts/create_dfu_udev_rule

inside a shell to gain upload permissions.

Reference: Upload Procedure


text:
How to program AVR in Mac OS X?
In our college we are using a module developed by IIT Bombay (called FIREBIRD V[ver 5]). It has ATmega2560 and ATmega8 microcontrollers (master and slave) with bootloader.
The staff uses AVR Studio for programming. But since AVR Studio is supported only on Windows (and I have a Mac), I was looking for AVR programming in Mac. I downloaded Crosspack AVR. But I don't know how to proceed after this point. Also I downloaded TextWrangler (because I was told auto-suggestion is not available in TextEdit).
Also I have downloaded the Arduino IDE, and I don't know what is required or how to configure it to program AVR microcontrollers.
I searched on the web and nothing is clear (mostly they all depend on something to do with terminal and the command line).
I don't have Xcode installed in my Mac (I saw a relatively easy tutorial on how to set up Xcode for this purpose) and the file is 4GB. I am trying to work around using Xcode, but if it's the only nice way do let me know!
Pertinent suggestions would be helpful.

Does the board use ISP or a serial protocol for programming?

It uses serial peripheral interfacing @IgnacioVazquez-Abrams

Then I wouldn't use ISP as the accepted answer suggests.

any suggestions... maybe the hard way!? because anyways it'll be good if i know them

Do you have a link to any documentation for the board?

https://github.com/akshar100/eyantra-firebird-resources/blob/master/Fire%20Bird%20V%20ATMEGA2560%20Robots%202010-12-29/Manuals%20and%20Application%20notes/Manuals/Fire%20Bird%20V%20ATMEGA2560%20Omnidirectional%20Robot/Fire%20Bird%20V%20ATMEGA2560%20Omnidirectional%20Robot%202010-12-26.pdf                 the omnidirectional bot is the one we're using now. I don't think you'll find enough there. I have a pdf about the software part of the robot. I don't know where to find them on the internet.

The software manual was located in a parent directory. Unfortunately nothing states what protocol it uses, so I'm going to have to dig deeper. The non-Arduino clock rate of the board means that you can't select an existing entry though...

Hah. Installing it shows AVROSP.EXE. That means either AVR109 or AVR910, both of which are supported by avrdude.

crossavr has avrdude right? so how do i go about setting it up?

No clue. I've never used crossavr. I'd look at using the Arduino IDE (1.6.x), although you need a file or two in order to make it work with the board. I think I have all the info I need, now to put it together...

anythg that'll make it work is fine.. :-)

First, install and get familiar with version 1.6.x of the Arduino IDE. Then, under the sketchbook directory, within hardware/nex/avr/ (create the directories if they don't exist) create the following files:
boards.txt:
# NEX Robotics Fire Bird V
# Only ATmega2560@14.7456MHz supported for now

nexfirebirdv2560m14.name=Fire Bird V ATMEGA2560 @ 14.7456 MHz
nexfirebirdv2560m14.upload.tool=avrdude
nexfirebirdv2560m14.upload.protocol=avr109
nexfirebirdv2560m14.upload.maximum_size=129024
nexfirebirdv2560m14.upload.maximum_data_size=8192
nexfirebirdv2560m14.upload.speed=115200
nexfirebirdv2560m14.bootloader.low_fuses=0xFF
nexfirebirdv2560m14.bootloader.high_fuses=0xDA
nexfirebirdv2560m14.bootloader.extended_fuses=0xFD
nexfirebirdv2560m14.build.mcu=atmega2560
nexfirebirdv2560m14.build.f_cpu=14745600L
nexfirebirdv2560m14.build.core=arduino:arduino
# This is not the real variant, but it will get the board running
nexfirebirdv2560m14.build.variant=arduino:mega

platform.txt:
name=NEX Robotics Fire Bird V
version=0.0.0

I have verified that an empty sketch will build, but do not have the hardware to test uploading. The upload.protocol value may need to be changed to avr910 or arduino if the current value doesn't work. Make sure to restart the IDE after any changes to the configuration files.
Further improvements that can be done include:

A real variant for the specific board
Support for the on-board ATmega8 (for now just use one of the slave firmwares uploaded with avrdude)
Support for the other AVR boards
Support for the 8051 and ARM boards

If you don't want to use the Terminal and the command line, the Arduino IDE is your best option. Get yourself an AVR programmer (or an Arduino Uno to serve as programmer, with the ArduinoISP sketch uploaded), and code on it.

Then connect your Arduino to your module via SPI. Select the correct processor and port.

You can now upload the sketch:


text:
How do I get the Itead 3G shield to work?
I've tried a pretty standard code but the Serial Monitor yields zero response.
Using a standard Arduino Uno (tried a second one as well, just to be sure) and am now trying the second shield with this code:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

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

}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

There is nothing coming back whatsoever in the serial monitor (yep, I checked the baud rate and tried several others).
Any ideas?
What should I be seeing if anything?

What should I be seeing if anything?

Usually, a GSM module will not send (unsollicited) messages. Everything it sends will be an response to an received message.
Try sending AT (with a new line/carriage return (depending on the GSM module)) to the GSM module, it will send something like AT OK or just OK
And you didn't set the pin directions (output/input), might be doen by the serial libraries, but beter be safe if you're not sure.
Also check your wiring (jumpers on UART multiplexer in this case?) and share it with us, Rx/Tx wiring often gets messed up :)
If your GSM module has a USB connection, you might even test it with a terminal (taking out the Arduino in the middle, thus any wiring/code between.)
I also suggest you change the name of the serial connection to the GSM to something like gsmSerial rather than mySerial (which could be anything).
Be sure the 3G shield has enough power (amperes), otherwise they might reset when attempting to make an connection.
(Put the external supply in the Arduino, rather than USB powered)

I have one, and I haven't figured out how to get it to accept input, but have received responses.  Here are some things to try:

Make sure you have your jumpers set for D2 and D3.  Just telling software serial to look at 2 and 3 doesn't mean your board is jumpered that way.

Also, remember that Tx for the board = Rx on the arduino and in your code.  Software serial is (rx, tx), so (2,3) means your board will be jumpered with tx on 2 and rx on 3.

There are four LEDs on the board.  If all four aren't lit, the board is powered down, and won't do anything.

First, make sure your power switch is set right - "VCC Switch", by
the USB connector, is set to the power level of your board.  I'm
using an Uno at 5V, so for me that's set to 5V.
It's best to provide power through your barrel connector on your Arduino and connection through the USB.  GSM modules are power hogs.
With all of that plugged in, your board should show two lights, the first and third.
Now hit the "PWR" button.  The second light will come on dimly, then stronger.  Now the module has power.
Finally, the fourth light will come on when the module has detected network. At that point, the 5216 will start sending you messages.

You need to make sure your baudrate is set properly.  Anything less than a Mega can't handle communication at 115200, which is the default for the module.  At best, you'll set both Serial and SoftwareSerial for 115200 baud, and you'll get mostly correct characters from the board, but an occasional bad character.
Here are some great instructions for changing the default baudrate at Github from some JeanBritz

One caveat to those instructions: make sure you have your Itead board powered by the Uno before plugging into the mini USB.

Here's a bit of light at the end of the tunnel for you -


text:
Arduino Servo Free Rotation
I have a project where I use 22 servos. I attach all 22 of the servos in the setup and in the loop, I use myservo.write() command to make a particular servo move to a particular position.
The problem here is that, all the other servos become stiff at this point of time, even though I am not writing any value to those servos. By stiff I mean that the servo is holding at a particular random value. Which for most of the 22 servos is at or near 90°.
My question is how can I make a particular servo move, while allowing all the other servos to freely rotate. I think that when I attach a servo the program prevents the free rotation of the servo.
I was wondering if the signal to one of the servos is leaking to other servos because of an issue with wiring, but this is not the case. The other servos become stiff only when I attach them to the pins which have been "attached" as a servo in the program.

When you attach a servo the Arduino starts generating the PWM waveform for its currently selected angle. When you write to the servo you just change the current angle and the waveform changes to match. That waveform is constantly being generated from the moment the servo is attached, and will always be generated.  That is how servos work.  They are not really designed to be back-driven by the load turning the cogs - it is the role of the servo to do the driving, not to be driven.
Depending on the servo you might actually damage the mechanics by driving it backwards like that.
The only way you can stop the servo from being actively driven is to detach the pin from the servo system so that it doesn't think there is a servo there any more.


text:
Basic C++ programming, how to pass constructor argument into class?
I'm having some programming problems.
So here's what's happening:
In my .ino file, I have a tft variable which holds the connection to a LCD. I want to make a class which can either automatically access that tft class contained in the .ino, or pass it into the constructor when it's created; so basically:
// assuming this is the .ino:

TFT_ILI9163C tft = TFT_ILI9163C(cs, dc, rst);

MenuClass *menu = MenuClass();
menu->init("Example", tft); // this should work and "menu" should now have access to the "tft" variable

Here's my Menu.cpp:
// Menu class

#include "Menu.h"
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <TFT_ILI9163C.h>

String menName = "Unnamed";

void MenuClass::init(const String name)
{
    menName = name;
}

String MenuClass::getName() {
    return menName;
}

void MenuClass::draw() {
    tft.setCursor(2, 2);
    tft.print(menName);
}

MenuClass Menu;

Which argument is tft supposed to be passed as?

Assuming you want to require every instance of MenuClass should be associated with a TFT_ILI9163C display object, you could use something like this:
// MenuClass.h

class TFT_ILI9163C; // declare a class name which is defined in TFT_ILI9163C.h

class MenuClass
{
  private:
    // read-only private member initialized by constructor
    // (the m_ prefix is commonly used to denote class member values)
    TFT_ILI9163C* m_tft;

  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft) : m_tft(pTft) {};

  private:
    // private storage for the Name property
    String m_Name;
  public:
    // read the Name property
    String getName() {
      return m_Name;
    };
  public:
    // write the Name property
    void setName(String value) {
      m_Name = value;
    };

  public:
    void draw() {
      // the m_tft member is a reference to the display class
      m_tft->setCursor(2, 2);
      m_tft->print(m_Name);
    };
}
MenuClass Menu;

Note that there is only one constructor, and it requires a pointer to the TFT_ILI9163C display. The body of the constructor : m_tft(pTft) {}; initializes the private member m_tft with the constructor argument pTft, so  MenuClass member functions invoke TFT functions as m_tft->fn(args);  Since there is no "void constructor" MenuClass(void), m_tft is effectively guaranteed to point to a valid TFT_ILI9163C instance.
Since it looks like you were using menName kind of like a class property, I rewrote that in the more commonly used m_propertyname style. Your MenuClass::init() was behaving like a name property setter; I'm not sure whether menu initialization requires anything else. This simple example has class MenuClass defined entirely inside the header file.
Usage is pretty similar to your example code, except now the MenuClass constructor requires a pointer to a previously constructed TFT_ILI9163C display instance:
// Main application
#include <TFT_ILI9163C.h>
#include "MenuClass.h"
// ... etc ...

// the TFT_ILI9163C display instance
TFT_ILI9163C tft = TFT_ILI9163C(cs, dc, rst);

// an example menu that draws on the display
MenuClass *menuFoo = new MenuClass(&tft); // use new to get pointer to new class instance
// MenuClass *menuFoo = MenuClass(&tft); // cannot convert 'MenuClass' to 'MenuClass*' in initialization

void setup() {
  // an example menu that draws on the display
  menuFoo->setName("Example");
  menuFoo->draw();
}

If you wanted to pass the constructor an initial Name property value as well as the tft display pointer, you could define the constructor as
  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft, String name) : m_tft(pTft), m_Name(name) {};

You could even go a step further, and give the name argument a default value:
  public:
    // constructor
    MenuClass(TFT_ILI9163C* pTft, String name = "Unnamed") : m_tft(pTft), m_Name(name) {};

So with this modification, the expression MenuClass(&myTFT) is the same as the expression MenuClass(&myTFT, "Unnamed"), but you can still override the default value like MenuClass(&myTFT, "DoSomething").
It is also perfectly legal to put statements inside the { } block of the constructor, but in this example all of the work is accomplished by the :memberName(value) constructor syntax.
Edit: MenuClass *menuFoo = new MenuClass(&tft); thanks @BrettAM

MenuClass *menuFoo = MenuClass(&tft); looks fishy to me, does that actually compile? It looks like you mean MenuClass menuFoo(&tft); or MenuClass *menuFoo = new MenuClass(&tft);


text:
Can I use my phone's charger to connect arduino M0 pro R3 with computer?
I found out that the arduino M0 pro R3 needs either micro HDMI or micro USB.
Since I don't have any micro USB or HDMI adapters, can I use the Samsung galaxy USB/micro adapter to connect?

If the Samsung cable has a micro-usb on one end, and a usb-a on the other side, then I don't see why not.

@Gerben I actually tried it, and I did get a successful upload. But the power is 5 volts, and 1.5 amps. Will that be enough? And just to add, can I use a 3 amp, 12 volt Ac/DC adaptor? Or will it fry my arduino?

You just want to power it, not connect it to a PC? A regular USB port only supplies upto 500mA, so 1.5A is plenty.

@Gerben And will my arduino be fried if I use a 12 volt, 3 amp AC/DC adaptor as an external power supply?

What board are you using? The R3 doesn't make sense for the M0, and in the tag you refer to a pro-mini.

@Gerben My arduino has text saying the board is an M0 R3. It is the arduino.org brand. Should I tag this question as arduino-zero?

The allowed input voltage range for this pin is 6-20 V. source. So your 12v adapter is also fine.

@Gerben You can put all the details discussed in an answer for me to accept. And finally to add: Do the amps matter? What is the maximum amount that can be handled as an external source?

Echoing what Gerben said, in order to wrap up this question:

If the Samsung cable has a micro-usb on one end, and a usb-a on the other side, then I don't see why not.
You just want to power it, not connect it to a PC? A regular USB port only supplies upto 500mA, so 1.5A is plenty.
The allowed input voltage range for this pin is 6-20 V. source. So your 12v adapter is also fine.

I actually tried a month ago. Worked. Thanks ;)

Excellent. This question now has an acknowledged good answer. That's what we like!

It should be noted that "this pin" (6-20V) is the VIN pin. And not the USB port. To avoid mixing those up. Also, you won't fry a board because your supply can supply more current, the Arduino will simply use the current it needs. If your Arduino pulls more current (by attaching a motor directly) than it can handle, you might indeed harm it, or the power supply.
And, yes, acknowledging the answers pumps up the stats a little ;)


text:
Could you tell me what is wrong with this Arduino code?
void fn( int pin, int pos)
{
    Servo temp;
    temp.attach(pin);
    temp.write(pos);
    delay(15);
    temp.detach();
}

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

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

Does it work if you extract the code from the function?

Arrange your code like this:
Servo servo1, servo2;

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

void loop()
{
    int pos;

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

    // 2nd loop here

}

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

It would be helpful to briefly describe what is significant about the difference in the arrangement.

I thought the code was short enough so that the difference is obvious. But I will update my answer next year.


text:
How to wire an analog IR sensor for digital input?
How do you wire a phototransistor so that it outputs a clean digital signal in response to certain light levels?
I've wired a QRD1114 to an Arduino analog pin to detect a white or black surface. However, I want to use this sensor to detect fast movement of a black/white color strip, and since analogRead() can take up to 100µs and I'd rather use the ADC pin for other sensors, I want to rewire this so I can read the same signal with digitalRead().
In order to do this, the sensor needs to output less than 2.3V for white and more than 2.5V for black. I'm pretty close, but I'm having trouble with black. For white, the voltage drops to 0.7V, so that reads perfectly, but black still reflects a lot of IR, so it typically reads 2.3V, which still translates as a LOW value.
My sensor's circuit is a pretty basic voltage divider:

R1 is the Arduino's built-in 20k pullup. R2 is a variable resistor I've tried using to "shift" the voltage level up for the black case. Unfortunately, I've found this very difficult to calibrate. The larger I make R2, the higher the black-case voltage gets...but so does the white-case voltage. By the time I make R2 large enough so that black registers as HIGH, white also registers as high. Through trial and error, I found 25.7k ohms is the sweet spot, but the difference in voltage between the two is about 0.5V, which makes me nervous about getting false readings.
I've measured the phototransistor's resistance in each case, and for black it reads as 12.5k ohms while for white it reads as 9.7k ohms.
Given my 25.7k calibration resistance, the voltage divider should output for black:
Vout = Vin * R2/(R1 + R2)

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

and for white:
5 * (9700+25700)/(20000 + 9700+25700) = 3.1V

However, for black, my meter reads 2.3V for black and 2.0V for white.
Why do my meter measurements not match the voltage divider formula? Am I wiring this voltage divider correctly?
What can I do to get a cleaner digital output without complicating the circuit too much?

Would you consider using a comparator (op amp) too complicated?

Per datasheet, the QRD1113 / QRD1114 is a "Reflective Object Sensor", not a color sensor.  If the sensor does its job properly, you will get about the same signal for a black object as for a white object.  That said, what happens if you add an external 5KΩ – 15KΩ pullup in place of the internal pulllup?  You might also try a bridge arrangement

@jwpat7, When you're only talking about two colors, as in my case, then yes, it's very much a color sensor, and many people successfully use it for this purpose. You see the color black because a black material doesn't reflect most wavelengths... And no, a different pullup does nothing.

@Marla, Yes, that would be too complicated.

Multimeters will affect the voltage a bit. Especially if you are using such high value resistors. Better connect directly to the arduino, and have the arduino light an led, if it reads high. I'd add a potentiometer, so you can trim the values. Also, not every input has the same 2.4V "tipping point". (I'd experiment with a lower value for R1, and remove R2.)

@Gerben, I'm puzzled by this. The input impedance of most modern meters is quite high, mine is rated at '> 10 MΩ' I would think that that should make little or no difference to the voltages in this circuit. Or am I missing something?

Near the bottom of:
https://learn.sparkfun.com/tutorials/qrd1114-optical-detector-hookup-guide
shows a graph of the voltage for a white surface and a black surface. If I understand your question correctly, I think you can get your desired results by controlling the distance between the sensor and the surface. For example, at 0.5mm white reads about 0.1V while black reads about 3.2V

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

Hope this helps.

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


text:
embedXcode: Link Error using an Arduino library (Servo.h) within a header file
For various reasons, I am moving from the Arduino IDE to Xcode using the embedXcode plugin. The code in question compiles and uploads fine from the Arduino IDE, so I think the issue is related to library definitions in embedXcode. The board I am using is an Arduino Mega 2560 (actually it is a Freetronics EtherMega).
The error thrown is:
Command /Applications/Xcode.app/Contents/Developer/usr/bin/make failed with exit code 2

More specifically:
    5.3-LINK                    Builds/embeddedcomputing.elf

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

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

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

APP_LIBS_LIST = Wire Servo SoftwareSerial
USER_LIBS_LIST = NewPing Time DS3232RTC HB25MotorControl
Any suggestions on how to fix this error and get my code to build in Xcode would be greatly appreciated.

Did you add the Servo library to the set of files to compile?

I tried including Servo.h everywhere it might be needed. I'm aware of the Arduino IDE issue with libraries within libraries, but that isn't the case here. The code compiles ok within the Arduino IDE. Thanks for the suggestion though, I do think the issue is related to having a library within nested header files.

The header file is not the library. Get the files that have the actual code in them and compile and link them.

I used to use embedXcode, and I remember that if it asks you for donations and you decline, it deletes some files in your project that are needed to build.  I got around this by deleting the file called embedXcode_check or something like that.

I ended up contacting the developer of the embedXcode plugin. He was very helpful and provided the fix within a day. The cause of the issue is apparently the Arduino IDE has changed its library structure in the latest release.
The next version of embedXcode (release 4.1.4.) will include a fix for this, however if you can't wait until then you need to open ArduinoAVR_165.mk (located in the Makefiles group in Xcode) in your project and add the following line:
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/$(BUILD_CORE),$(APP_LIBS_LIST)))

After you add this line, the file should look like this:
# Two locations for Arduino libraries
#
APP_LIB_PATH = $(APPLICATION_PATH)/libraries
APP_LIB_PATH += $(APPLICATION_PATH)/hardware/arduino/$(BUILD_CORE)/libraries

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

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


text:
Class is not tracking changes to a private field
I have a program where a device registers itself with a command object. The command object is losing track of the registrations. The following program repeats "0 devices registered" even though when it initializes it displays "Devices registered 1". My guess is that I am accidentally creating 2 copies of the command object.
This is the main sketch
#include "command.h"
#include "widget.h"

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

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

command.h
#include "Arduino.h"

#ifndef Command_h
#define Command_h

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

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

#endif

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

#define DEVICES_MAX 9

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

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

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

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

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

  private:
};

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

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

It is all about calling conventions and argument binding. The code is using call-by-value when it should be call-by-reference.
This is call-by-value (the incoming command is not updated, a copy is passed as parameter):
void Widget::init(Command _command)
...
widget.init(command);

This is call-by-reference (a pointer to command is passed as parameter):
void Widget::init(Command* _command)
{
   __command->registerDevice(...);
}
...
widget.init(&command);

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

Cheers!

Thank you so much, great Christmas present! The compiler complained about "widget.init(&command)" when I changed it to "widget.init(command)" it worked.

Typical cut-paste-error :). Thanks!


text:
avrdude: stk500_recv(): programmer is not responding + avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x47
So I'm following a beginners arduino book and I made a blinking program and now I've coded another program but when I try to upload it, avrdude(whatever that is) gives me the errors in the title and repeats them 10 times.
I have tried this so far:

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

My guess is that since it worked the first time, my blinking program must be clogging up the space in my arduino.How can I fix this problem. Or if my guess is right, how can I get the blinking program out of arduino and go home to my bots folder?
My IDE is arduino 1.6.7 and my port is CPU1. and lots of people mention tools>serial port but there isn't a "serial port" button on my IDE.

Since there are no accepted or up-voted answers to this rather old question I'm going to link to my post here about problems with uploading.

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

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

There is a gap between my reset pins. How do I mold  them together?

Just search a little bit around Google.
A simple solution is pressing the restart button after the program is compiled, then, upload it.
Or restart the Arduino while the Arduino is uploading the program.
If the problem remains, try to burn again the bootloader of your arduino.

"Searching around a little bit arround on google" is not particularly helpful, as googling is probably what led the OP to SE in the first place! ;-) If you could provide a useful link or two (which you have done), along with a quoted summary of the info provided in each link (in the case of future link death) that would be great, or better still, if you have encountered this issue yourself, feel free to provide your own solution (which you also have done)... :-)

You're probably trying to connect through the wrong port.
I had this problem due to the mac suddenly making the /dev/cu.USB port option unavailable for selection through the arduino software interface under tools/port, and then not knowing what I was doing I just tried to connect through the wrong port and got this error.
After rebooted the mac, voila the /dev/cu.USB port option was suddenly available again under tools/port, we selected it and were able to successfully upload again.
I don't know why the mac or arduino software does this, my sense is that  something must get confused during upload sometimes, especially if you disconnect and reconnect the usb for some reasons, or turn on the 9v power on the arduino board while uploading.