text:
ESP8266 & websockets
At the moment, I'm using various operating systems and devices like the Raspberry pi to control lights and other stuff over websockets. I use websockets since they added the support on Chrome. I write a lot of Javascript stuff for fun. Websockets allow you to communicate with another server without the need of reloading a page. It's a lot better than Ajax. Once the connection is open with a web server data can travel both ways. No unnecessary headers to send. No unnecessary requests. You just send only the data you want, this in both directions. AND FAST, DAMN FAST.
For example I use Javascript's requestAnimationframe to send RGB values (based on music frequency) to lamps connected to the network. requestAnimationframe executes approximately at 60 Hz. But that's not the highest speed, I also created some "web controllers" to control servos and other stuff with touch and mouse events. In that case it probably touches transmission frequencies of 200-300 data packets (normally I use JSON- encoded strings) or more per second.
Websocket servers have also broadcast which allows you for example to control multiple RGB lamps based on the music you play from basically every modern device that has a browser. I don't use "normal" sockets because of the simple fact that there is no support for sockets in a standard web browser. So I would need to create a custom iOS app, custom Windows app, custom Android app. I said that we know that websockets are made for a fast multi-user / multi-device / bidirectional communication. And it should be really fast or it's useless.
Lately I have a lot of fun with electronics and MCUs, so I made even more lamps and stuff controlled from Arduinos, ATtinys and other microcontrollers. I'm new to C++ but since I write Javascript code since the previous century I just have to slightly modify old Javascript functions to run in the Arduino IDE.
But for sure I'm not ready to write a perfect library for an MCU, so I need to use what I find online.
Apparently there are not many people into websockets. I tested 2-3 Arduino websockets libraries and couldn't get them to work properly.
The last one I tested(Links2004) works but I can't send a 4 decimal string faster than 2 times per second or it crashes.
All I did was to add this code for testing:
void onWebsocketMessage(uint8_t * payload) {
 analogWrite(13,atoi((const char *)payload));
}

Where payload is the data received.
Problems that could slow down/crash everything:

My code. Does atoi take too much to execute?
My code. Is the (const char *) cast filling memory?
The lib itself?

I know that the CPU memory or whatever else is not the problem because of this video:
https://www.youtube.com/watch?v=8ISbmQTbjDI
He gets realtime stats from the controller at 200-600 Hz.
While it's supercool and I could just install that "custom firmware" I prefer to stay in the Arduino IDE for now.
How to fix websockets on the ESP8266 device using Arduino IDE?
Or maybe can I extract only the websocket part from that firmware (CNLohr's Video)?
Suggest another lib?
I posted here because I use the Arduino IDE. And the ESP8266 has also been part of the Arduino world for a while. And maybe some not so popular Arduino-based websockets work also on the ESP8266.
Wouldn't it be nice to control your ws2812b strip with a web interface showing the preview like this?
http://jsfiddle.net/dgws3usa/5/

EDIT
links2004 @ github

The network should be fine. It's a relatively expensive Cisco/Linksys N router at 20cm/8inch away from the ESP8266 module.
Luckily the module I'm using is one of the modules listed in the Arduino IDE, the MOD-WIFI-ESP8266-DEV, but I have another one with fewer GPIOs.
I just noticed now that I programmed it at 80 Mhz instead of 160 Mhz.
The program I uploaded consists only of the basic websockets server example with in addition just the code posted above.
If atoi is the problem/is slow, what are other ways to convert the received array to a string?
I use both the latest versions of the Arduino ESP8266 port and the arduinoWebSockets. At least I guess so. I followed the install instructions one day before I asked this question.
By crash I mean, while moving the range slider, if updating in realtime with addEventListener('input',function,false) at some point (after 1 sec/ 3-4 messages send/received) it stops sending or receiving data. By the way, the video you posted seems to work properly with a lot more code. Also that guy updates in realtime with oninput vs 'onchange', which would only update when the user releases the slider.
I think for now I can't use Serial.setDebugOutput(true); as I didn't get the serial communication working. I'm using a cheap CH340G to program the chip.

Japanese post.

I'm doing exatly the same thing but in a much simpler way. No web server, no ping pongs, no serial stuff, I don't use complex functions to elaborate the web server's data. Altough his example works.
He is doing, code-wise, a lot more than I do.
for(i=0; i<4; i++) {
  mask[i] = client.read();
}
byte m_data[data_len];
char data_c[data_len];
Serial.print("Receive Data = ");
for(i = 0; i1-0x30);
    break;
  case 3:
    data_b = ((data_c[0]-0x30)*100) + ((data_c1-0x30)*10) + (data_c2-0x30);
    break;
  }
  LED_PWM(data_b);

My full "test" code:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <Hash.h>
ESP8266WiFiMulti WiFiMulti;
WebSocketsServer webSocket=WebSocketsServer(81);
void webSocketEvent(uint8_t num,WStype_t type,uint8_t * payload,size_t lenght) {
  switch(type) {
    case WStype_DISCONNECTED:
      break;
    case WStype_CONNECTED:
      {
      IPAddress ip=webSocket.remoteIP(num);
      }
      break;
    case WStype_TEXT:
      analogWrite(13,atoi((const char *)payload)); // MY CODE
      webSocket.broadcastTXT(payload,lenght);
      break;
    case WStype_BIN:
      hexdump(payload,lenght);
      webSocket.sendBIN(num,payload,lenght);
      break;
  }
}
void setup() {
  pinMode(13,OUTPUT); // MY CODE
  for(uint8_t t=4;t>0;t--) {
    delay(1000);
  }
  WiFiMulti.addAP("ssid","pass");
  while(WiFiMulti.run()!=WL_CONNECTED) {
    delay(100);
  }
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}
void loop() {
  webSocket.loop();
}

I normally write Javascript code. Converting a string to a number or vice-versa is much simpler. num=1; str=1+''; num=str*1; So all this binary array is relatively new for me.
Note that while I convert the binary array to an int now. In the future I need to convert that to a string which then will be parsed. Something like JSON. And so update more channels per message.
On the client side, like I said, I'm sending the data really fast. So if there is no buffer on the server side that could be a problem. Solving that is simple: requestanimationframe. Continuously check if the input changed. That allows you to send the data every 16-17ms. So 60 Hz. Not slower, Not faster. But again that should be the maximum pause between messages.

I said that I will reprogram it at 160 Mhz now and hope there are other ways to convert the received data faster and hope for updates relative to my code.

EDIT2
Right. The serial works. Reprogrammed the ESP8266 At 160 Mhz.
The error I get when when I set Serial.setDebugOutput(true); is:
LmacRxBlk:1

If you need some other information just ask.
EDIT3
Sorry for the late response.
webSocket.broadcastTXT(payload,lenght);

Broadcasting seems to be the problem. I just have a few minutes so for now I can't do the describe debug stuff... But I will do as soon as I have a little more time.
EDIT4 for Aditya Tannu
Added
#include <NeoPixelBus.h>
#define pixelCount 16
NeoPixelBus strip = NeoPixelBus(pixelCount,13);

Inside the webSocketEvent function
case WStype_TEXT:
for(uint8_t i=0;i<pixelCount;i++){
 strip.SetPixelColor(
  i,
  RgbColor(i==(atoi((const char *)payload)%pixelCount)?255:0,0,0)
  // i need to put the above outside of the loop.
  // it does not work if i do so
 );
}
strip.Show();
break;

HTML JS
var ws,form;
function msg(a){
  console.log(a);
}
window.onload=function() {
  form=document.getElementById('form');// change
  ws=new WebSocket('ws://IPNUMBER:PORT');// change
  ws.onopen=function() {
    ws.send('0');
  };
  ws.onmessage=msg;
  form.addEventListener('input',function() {
    ws.send(this.firstChild.value) // firstchild is the range
  }, false);
}

vid, I use a logic level converter from 3.3v to 5v: pca9306.
EDIT 5 for Links2004

I think I should rework the examples. It looks like most users don't
  understand it well.

Nono. At some point you need to broadcast back the actual position anyway.
Sorry. I forgot to test the debug stuff again. But we know it's the broadcast. We just need to send back data only when there is not too much traffic.

I tried to port Charles Lohr's implementation to esp8266/Arduino. An initial working version is up here: https://github.com/AdySan/ESPSocket
I'm able to get ~150Hz without any disconnections or crashes. I'll keep working on it to add more functionality and hopefully improve speed.


text:
Power maximum output power for each pin
A have Arduino Mega 2560. I found in the spec that the maximum output current for each I/O pin is 40 mA.
Can i use 40 IO in parallel? That's mean 40*40ma*5 volt = 8000 mw = 8 watt.
What about the heat?!

There are also limits on the total power of groups of pins,

The sum of all IOH, for ports J0-J7, G2, A0-A7 should not exceed
  200mA.
The sum of all IOH, for ports C0-C7, G0-G1, D0-D7, L0-L7 should not exceed 200mA.
The sum of all IOH, for ports G3-G4, B0-B7, H0-H7 should not exceed 200mA.
The sum of all IOH, for ports E0-E7, G5 should not exceed 100mA.
The sum of all IOH, for ports F0-F7, K0-K7 should not exceed 100mA.

So you are already limited to 800mA.
Secondly, you have to be careful to change all the pins at exactly the same time. Otherwise some pins will be low, and others high creating effectively a dead short. Or if you make sure the pins are inputs before changing, some pins will be on sooner, and those pins will then for a short period, handle all the current, and thus exceeding their limit for a brief moment. Which isn't that bad, but still not ideal.
So definitely don't use digitalWrite to change all the pins, one after the other.

No, you can't.  Read the rest of the specifications and you'll see why.  Also the 40mA is wrong. That is the absolute maximum. 20mA is the guaranteed limit for steady-state IO.

source: Stack Exchange

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

sort: votes


text:
I2C between Arduinos without Master
I am working on a library for some Arduinos that should talk between each other.
The aim is that I can load the same binaries onto each Arduino. The I2C ID will be set by DipSwitches.
So far everything works pretty nice but once a while everything gets stuck.
I am not asking you to resolve and debug my code, but I am not sure if i have done something completely wrong:
To make all Arduinos interchangeable I have no Master (Wire.begin()) in my I2C Bus.
I read, that the Master would be responsible for the pulse on the Clock line. As I have no Master in my setup maybe that is the reason for the instability.
Can anyone confirm that connecting some I2C Arduinos without master is something that cannot be done? (or do I have to look for some other reason)

Slaves are just waiting for a Master to ask them something. If there is no Master no slave will ever do something. Note that I2C can have multiple masters on the same bus. So either do something with that, or have the Arduinos wait a certain time (e.g. based on the id), to see if there is a master, and if not assume the role of master themselves.

You have to have a master for an I2C bus to work.  Can't you allocate one of the dip switches to define the master?
Edit to be able to remove the downvote
Nick his answer seems to imply that you do not need masters but that is wrong.
What Nick is saying is that you can swap masters over time.
But each time there is communication there is a master.
So the statement "You have to have a master for an I2C bus to work" is 100% right.
As I misunderstood this myself I downvoted this answer. I hope this edit will enable me to remove my downvote and add a upvote.

I was still investigating and found some, who had the same demands that I had: actively send data from many Arduinos to the central Arduino and not wait for the Master that pulls the information from the Slaves. Look here or there according to what they say, it is possible to setup I2C Arduinos without Master.
But my setup caused me headache. I changed the Concept and pull the data from the Slave. It only takes 2ms to pull from 10 Slaves that is fast enough

As shown in the answer below it is possible.

@jantje - I don't think the answer below says you can have a working I2C bus without a master, because you need a master to transmit.  I suppose as long as no one on the bus needs to transmit you don't need a master, but if there are no transmissions there isn't much need for the bus.

@matt - you are right. I can't remove the downvote yet (it states it is only 17 hours ago I voted :-( ) If I forget -> remind me.

Can anyone confirm that connecting some I2C Arduinos without master is something that cannot be done? (or do I have to look for some other reason)

There is no master except during transmissions. Thus it is possible to rotate the job of master if you want. You would need some way of deciding when it was a particular board's turn to be master.
I have code here on my RS485 page about how you can set up a rolling master using Serial communications. The same basic idea could be used to make a rolling I2C master.

Hi Nick, thank you for your reply, I was hoping that you find this question once.

Hi Nick, thank you for your reply, I was hoping that you find this question once. I have read a lot about I2C on your invaluable website. Yes, a rolling master would have been a solution, but due to its complexity I stayed with one dedicated master that polls data from the the slaves. It is so fast, there was no drawback in responsiveness. What I like in your rolling master approach is that the system does not depend on the ONE Mater! I should have found it earlier.

I am planning setup, where would be more Arduinos and more pasive devices (sensors - pure slaves) on the I2C bus. Each Arduino would "sit down" as slave and respond request, until it have something to say/demand. Then it stop being slave, "stands up" and start transmiting as a Master. After sending what had to be send and eventually getting all answers it igain "sits down" and became slave. So most of the time there are only slaves on the bus, sometimes there arise a Master for a moment. Arising 2 or more Masters solves the I2C protocol itself (first sending 0 get the bus)

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


text:
How does the speed work in VirtualWire Library
I'm analyzing the VirtualWire library and in it, the send messages are being sent with digitalWrite in the "send" method. However, there is a setup speed function. I'm reading that function and I see a lot of prescalers and TCCR variables. However, I'm not quite sure what these things do. Because, if it uses digitalWrite anyway to send the bits, then really is no intrabit delay, etc. Can someone please clarify this?
Sorry if question is convoluted. Happy to do any clarification. Thank you for all guidance!
EDIT: Also, how do I transmit a block of message. Something greater than a byte? I'm trying to calculate BLER of messages and software serial only transmits 1 byte at a time. While virtualWire uses low-level error detection (and i want to avoid the use of any error detection/correction).

@NickGammon any thoughts on this? Main question is actually the edit.

I think that is used for receiving. By setting the speed, it knows how often it needs to read the input pin. It does this using timer interrupts, so it will run "in the background" without interfering with the main (loop) code.
The TCCR stuff is the set the interval for the timer interrupt.

So, as far as the bit transmission is considered, it only uses digitalWrite to send it right? As opposed to how SoftwareSerial directly accesses the registers.

Also, I only see digitalWrite being called once. and not in a loop. Am i reading the code wrong? How is it being able to transmit so many bytes? Sorry if I''m completely overlooking things.

Sorry, on a second look at your post, i am slightly confused. So does that mean delays ARE or AREN'T being used during transmission? Some clarification here please? thank you!

Yes, it only uses digitalWrite (not the fastest, but very portable). Looking at the code a bit better, it seems their are using the timer interrupt to both send data, as well as receive (though not at the same time). I didn't say anything about the TX side in my question. But seeing that they also use the timer for TX, their won't need any delays. So sending data is done "in the background" as well. Just like hardware serial.


text:
Arduino nano (clone) with ethernet shield only works when I open up serial monitor

#include <EtherCard.h>

static byte mymac[] = { 0x7A,0x69,0x69,0x2D,0x30,0x31 };

byte Ethernet::buffer[500];
static uint32_t timer;

const char website[] PROGMEM = "x0201g2.cloudapp.net";

static void my_callback (byte status, word off, word len) {
  delay(1000);
}

void setup () {

  Serial.begin(57600);
  ether.begin(sizeof Ethernet::buffer, mymac, 10);

  ether.dhcpSetup();

  ether.dnsLookup(website);
}

void loop () {

  ether.packetLoop(ether.packetReceive());

  if (millis() > timer) {
    timer = millis() + 5000;
    ether.browseUrl(PSTR("/foo/"), "bar", website, my_callback);
  }
}

The way I tested this is I open up SSH terminal for x0201g2.cloudapp.net to monitor any incoming traffic.
The result is that it works fine, when I have the "serial monitor" (in Arduino IDE) open. I would see that there's a consistent stream of GET requests.
However, when I do not have the serial monitor open nothing ever happen.
Initially I had some Serial println to show response status and IP address, so I thought it might be related to the fact that the MCU's serial  controller is waiting for a handshake or some sort of ACK/NACK to happen...if that make sense.
However, that was not the case now because even after I have removed all serial print statements it is behaving in exactly the same way (except that my monitor will show up blank, but I still need to bring it up for it to work).

Also, without Serial.begin() nothing will work as well.

Could it be related to voltage level differences (Nano = 5V) and ENC28J60 wants 3.3V - this particular ethernet board doesn't seem to have a level shifter on it. But if that's true, nothing should work regardless of whether i have serial monitor open or not.. right?

Maybe it's because it's some unknown cheap clone? You should try it with a genuine one.

Look at the ATmega reset pin.

@ChrisStratton could you give more hint? Are you saying it might be because of auto reset?

Update: Tried this with Genuine Arduino Nano. Still same behavior.

@ChrisStratton could it be something to do with voltage differences at RESET pin? Could you elaborate. Thanks in advance.

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


text:
How to choose SPI type used by RF24 library from application?
I am developing a device with Ethernet shield (with Wiznet W5100) and NRF24L01+. I need to use Soft SPI due to a bug in the Wiznet chip. Next I am developing a different device with NRF24L01+ only. I want to use hardware SPI (besides other things it already contains a socket for NRF24L01+ connected to the default Arduino SPI pins).
It is very inconvenient to enable/disable #define SOFTSPI in RF24_config.h every time I want to work on the other device.
Is there a way how to choose the SPI type used by RF24 library in the application?
My current solution is to make a copy of RF24 to RF24_SoftSpi and RF24Network to RF24Network_SoftSpi. I enabled SOFTSPI in “_SoftSpi” versions (+ renamed all files, fixed includes and #ifndef statements in headers to avoid ambiguous errors).
Then in an application I just include RF24_SoftSpi instead of RF24 and RF24Network_SoftSpi instead of RF24Network to use software SPI.
With this workaround it is difficult to make updates to “_SoftSpi” libraries when a new feature is released.
Do you know of any better solution?

This might help; https://www.itead.cc/wiki/IBoard

Using this RF24 library set, I am able to use or not softspi by doing #define SOFTSPI on my sketch, there's no need to define it on the RF24_config.h, you should be able to define it on your own sketch.
EDIT:
Arduino 1.6.5
#include <SPI.h>
#include "RF24.h"
#include "printf.h"
#define SOFTSPI //Define pins RF24_config.h

/****************** User Config ***************************/
/***      Set this radio as radio number 0 or 1         ***/
bool radioNumber = 0;

/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8     */
RF24 radio(8,9);

....
....
void setup() { ... }
void loop() { ... }

thank you for your answer. Would you be so kind and add an example into your answer including Arduino IDE version you use?

See edited answer above

#define directive does not have any impact on library build. Libraries are compiled separately and do not take any directive from sketch into account. Verify your sketch with and without the #define SOFTSPI directive. Size of the result will not change, but it should by approx 2kb.

This solution does not work unless proven otherwise

Try defining Soft SPI before including the RF24 related headers.


text:
How do I resolve "avrdude: stk500_recv(): programmer is not responding"?
Whenever I try to program my Arduino UNO Rev.3, I'm seeing the following error
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00

When I plug this in, I do see a power light. There are no cables whatsoever connected other than the USB. I have another Arduino UNO which works fine when I upload the sketch (I'm using the basic blink sketch). How do I resolve this? What kind of problem can it be?

Make sure there are no wires connected to the Serial Interface (pin 0 and pin 1)

@KiraSan updated the question with more information (nothing plugged into 1 or 0).

I think you should consider using that Arduino Duo to reburn the bootloader of your Arduino UNO.

Also before doing that, make sure you selected AVR ISP as programmer, and chosen the right board.

i am also stuck with this kind of problem with my nano board....

Don't forget to try another USB cable. Also you can try to swap MCUs and try it again to figure out if it's board problem or bootloader problem...

What OS are you using?

D_Graeme solution is what worked for me (Nano, OSX). Here's a Stack Overflow question with many answers/solutions: Arduino Sketch upload issue - avrdude: stk500_recv(): programmer is not responding

After trying numerous suggestions, 2 different boards, 3 different cables on a WinXP and a Win7 machine, I finally got things working by going to "Tools -> Processors -> ATmega 328P Old Bootloader"

Although this answer would be correct for a Nano, this question is about an Uno and so your answer is off topic. We already have a question for that Nano problem: https://arduino.stackexchange.com/q/51771

For me it was the opposite: had to select nanoatmega328new on PlatformIO. Thanks dude

I'm using VS Code. Sadly, there is no "Tools" menu that I can find.

I had this problem when working with Arduino IDE and XOD running on top of it.
What I found; looked like baud rates were being set differently at different stages in the setup. I compared Windows 'device settings', arduino IDE settings and XOD settings...and they are not the same and seem to change ? ...hence the 'avrdude:stk500_**** errors!
To demonstrate
Connect an Arduino board to a PC USB socket.

On Windows 7; Control Panel\ System and Security\System\ Device Manager... then double-click on 'Ports (COM & LPT)
You should see FTDI
or
USB-SERIAL CH340(COM7) ... for a chinese serial com chip on the arduino board.
Right-click on this and check 'Properties\ Port Settings' and note  the 'Bits per second' value : e.g. 57600 ... (write it down !)
Open the arduino IDE and click on File\Preferences and tick the option ;'Show verbose output during: 'upload'.Then close the 'Preferences' screen.
Load a small program that works. e.g. File\Examples\01.Blink
In the for your arduino board setup in the Arduino IDE;
Tools\Board ... such as Arduino Nano
Tools\Processor ... such as ATmega328P
Tools\Port:COM7 for example ... make sure a tick is selected.
Tools\Get Board Info ... will show info from the arduino serial chip (a good sign your usb cable works!)
On the IDE toolbar select;

'Verify' and shortly it should show 'Done Compiling'
Click 'Upload' and the Blink program should load into the arduino chip.

Now here is the interesting observation; The 'verbose message at the bottom of the IDE screen will indicate what 'Overriding Baud Rate : XXXXX' is being used! Write this number down next to the value you found on the Windows devices setting.
Now, if you are a XOD man, leave the arduino IDE running and run XOD.
Open the XOD IDE and open (Deploy) say the 01-hello program and load it into your arduino board.
Select'welcome-xod' and select 01-hello program on left-side menu.
Select 'Deploy\Upload to Arduino ...'
select 'Board model:'  and 'Serial port:' ... eg COM7
Scroll up in the 'Deployment ' window and there will be another value labeled 'Overriding Baud Rate : e.g.115200'

I HAVE FOUND THESE BAUD RATE SETTINGS CHANGE INEXPLICABLY !
I hope my observations will throw some light on your problem of erratic uploads.

Thanks Lionelb! What I had to do was go to Tools and change Port to COM3 instead of COM1, which was in use for a serial port on my system. This was after reading your solution and checking Control Panel\ System and Security\System\ Device Manager.. I did not happen to have an issue with the bits per second, but that is helpful too.

Thanks worked for me. After File\Preferences and ticking the option ;'Show verbose output during: 'upload'. I only needed to set the bits per second in the device manager for the used com.port.

To upload the program again I needed to change the baud rate to 9600 (after initially 57600)

Have you already tried this?
https://stackoverflow.com/a/20735393/5507619

I had this problem with a Crowduino, running the Arduino IDE on OSX.
  The solution for me was to switch on verbose output during upload (in
  the arduino IDE preferences pane).
Then, when uploading, you can see avrdude sending three packets
  avrdude: Send: 0 [30]   [20] (with corresponding RX flashes on the
  board) right before the avrdude: ser_recv(): programmer is not
  responding error.
The trick is to hit the reset button on the board immediately before
  these three packets are sent. Then the program will be uploaded
  successfully.

I had periodically encountered this as well and was stumped after I had tried all the recommended solutions I could find. In my particular case it turned out to be the cable I was using.

I was having the same problem, however I was able to solve as follows,

rebooting my computer
or, changing the cable, basically switching between 2 USB cables (may be it just needed to unplug the USB and plug it in again).
or, resetting the COM port

closing the Arduino IDE
disabling the COM port
enabling the COM port
opening the Arduino IDE

For me it was a matter of -B 10 instead of -b xxxx. So:
sudo ~/arduino-1.8.12/hardware/tools/avr/bin/avrdude -P /dev/ttyACM0 -B 10 -c arduino -p m328p -C ~/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf -U eeprom:r:eeprom.hex:r

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


text:
How to use a microSD card reader with SCK instead of CLK?
I've bought this microSD reader/writer: http://www.ebay.com/itm/131132034753
I've found only one tutorial, where the pins are similar to my pins, but in the example there is a CLK instead of SCK: https://learn.sparkfun.com/tutorials/microsd-shield-and-sd-breakout-hookup-guide
The pins on my MicroSD reader are:

CS
SCK
MOSI
MISO
VCC
GND

SCK is actually a clock signal. So basically, they are the same thing here.

SCK stands for SPI ClocK
CLK stands for SPI CLocK
Two different acronyms for the same thing.

It's common practice for speakers/writers to use the generic term: "clock" (CLK) for various different situations. This clearly being a serial interface we don't need to specifically say Serial cloCK each time the signal mentioned, as it's more of a mouthful than saying "clock".
In this case consider "CLK" and "SCK" as fully interchangeable.


text:
Popen command restarts arduino
So I am trying to make a Mac OSX program with Cocoa that will be able to control my Arduino via serial. I currently have the C command
popen("echo 7 > /dev/cu.usbmodem1411", "r");

to try to send the number 7 over serial to the Arduino. I know that the path     /dev/cu.usbmodem1411 is correct because the Arduino is responding, however it seems to "crash" or simply restart whenever this command is received from the Mac. Sorry this may be a question for StackOverflow, but I thought I would start here.

Nope, doesnt seem to do the trick

Are you sure you are sending "the number 7"? I don't know how echo on the Mac works, but are you sending a string with the character '7' in or ASCII 7 or integer 7.  And how are you reading it at the other end?

@Matt I'm actually not sure, is there a better way to do this? I was attempting to send an integer 7

@woakley5 I would guess that you are sending ASCII character 7.  Can you use SoftSerial on the Arduino, and change you program to echo the data received from the Mac.  Echo the byte values received, not the characters, because if you print 7 it ring the bell :)

Despite the poster's denial, this is in fact a duplicate of the reset-on-open issue, and especially now that they seem to have abandoned the question, closing it as a duplicate (as it originally should have been) is the only way we are going to stop it from being periodically churned back up.

@Matt Echo on mac won't send ascii char code like that...

I think the problem is more going to be that you don't have a serial connection to the arduino. ie, if you look in the Arduino IDE, you assign a serial port to the application. When you upload your sketch, a connection is made, the arduino resets (by design) and your sketch is uploaded.
What it appears you are doing here is opening a new connection and sending the character (which is ASCII) which in turn sends the arduino into reboot to look out for a sketch being uploaded.
I'm not familiar with popen and maybe you can use it and keep the connection open and even monitor the data stream, but I would say instead of writing directly to the device as you've done, use an application that will initialise the port properly (ie open it and leave it open) so that you can continue to use/monitor it.
A quick google search has brought up Mike's PBX Cookbook which has some good info about it. I've personally used minicom (a guide for installing minicom) and CoolTerm, I have used Screen but it was so long ago I don't remember why I moved on.
edit: I just followed the link submitted by the first commenter (sorry name not available in the edit screen), and although you've responded with "that's not it", it actually is, you just haven't realised it since your popen command is actually opening the port and triggering the RTS mentioned in that post

Automatic activation of the modem control signals (which trigger the reset) is something which the host operating system can be configured to do or not do.


text:
How can i connect the Mics-5132 to Arduino Uno (Carbon Monoxide Sensor)

hi. i don't know how can i connect Mics-5132 CO Sensor to my arduino.
plz help

That is a very skimpy data sheet for the MiCS-5132 .  (Shame on manufacturer for not including isolation information between heater and resistor output).
Connect 3.2 volts (3.3 volts is ok) to pins 1 and 3 (heater). Keep in mind the heater will draw about 32 mA.
Pins 2 and 4 are the output.  The output is a resistor, whose value changes with the degree of detected gases. And the resistance is about 160 k ohms.
Wire a resistor (call it R1) from VCC (positive power) to your input. Start out with R1 = 150k  (anything from 120K to 180K). .
Wire the sensor (pin2) to your input (use an input that can do A/D conversion).  Wire the other side of the sensor (pin 4) to your board ground.
This makes a resistor voltage divider to your input pin. Your input pin should be an A/D converter.  The A/D converter input should return a value dependent upon the sensor resistance.
Experiment with different values for R1, to get the input range that you desire.


text:
Drawing amperage with Arduino code
I'd like to preface this by saying I'm a complete beginner, but I have learned a ton already on this project, and I feel like I'm almost there.
I'm using an Arduino Uno and an Adafruit motor shield. I am working on a project for mechanical engineering and I need lots of amps for lots of torque for my mechanism. I'm including my code although I know it doesn't work, I haven't had the chance to debug it yet, and I'm really not sure if I'm on the right track.
So I know that it's possible to draw more amperage than is strictly allowed from the Arduino. What I don't know for sure is how to code it. Attached is my preliminary attempt.. I kind of assumed that the maximum speed would be the maximum allowable speed of the motor, regardless of the Arduino's capabilities, and scaled the output MAXampDrawSpeed as a function of that. To be specific, my motor can draw up to 20 amps, which would be too much for the Arduino to handle, so I scaled it down accordingly, with 255 being that maximum 20 amp output. I'm not sure if I'm on the right track there.
So the other problem is - the TA for my class made a simplified code reference file, sort of predefining a lot of the things that I manually defined in my code (or tried to at least). I didn't realize this, and when I asked him a question, he sort of shot me down and said "you should use my reference code" -- but his code doesn't compile for me. I had some problems with libraries (I fixed them!), but this isn't a library. It's a reference file, like the tabs up at the top. But it won't even compile for me. My feeling is that I may have annoyed him with my many many stupid questions up until this point and he's just kind of like "girl, get it together"... So the question there is -- am I almost there with my track or should I figure out what's wrong with his code and try to fix it his way so that I can ask him questions without being such a bother to him? And also is that likely to be a hindrance on drawing the extra amperage that I really really want? I am prepared to use heat dissipation methods as are necessary, and any advice you could give me there would also be appreciated.
If you need any more information, about my mechanism or anything I'd be glad to share that as well. I'm parallel mounting one motor to the four dc motor mounts on my Arduino in order to draw maximum current in that way as well. I have two switches controlling the output, one of the switches will engage the program for the maximum distance competition and the other for the accuracy competition.
So again, this code isn't right. I haven't even started on debugging it, because I didn't want to waste my time. Maybe you'll be able to follow my logic. I know there aren't many notes. If you need me to add notes for clarity I would also be glad to take the time to do that.
Thanks!
#include <Stepper.h>
#include <AccelStepper.h>
#include <Servo.h>
#include <Adafruit_MotorShield.h>
#include <Wire.h>
#include "Arduino.h"

#define STEP_TYPE_1   SINGLE
#define STEP_TYPE_2    SINGLE
#define STEPS_1    200
#define STEPS_2    200

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
Adafruit_DCMotor *DC4 = AFMS.getMotor(4);
Servo Servo1;

void setup() {
  digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
  int i = analogRead(A0); //Reads the value on the analog pin and saves     this as variable "i"
  AFMS.begin(); //Initializes the motorshield board
  int motorPin1 = 1;
  int motorPin2 = 2;
  int motorPin3 = 3;

  pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
  digitalWrite(A0,HIGH);
  pinMode(A1, INPUT);
  digitalWrite(A1,HIGH);
  pinMode(A1, INPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  Servo1.attach(9);
}

void loop()  {
  int distancepin = 0; //Just integer quantities, i like to have too     many of them
  int accuracypin = 0;
  int inPin1 = 0; //switch pin values
  int inPin2 = 0;
  int MAXampDrawTime = 75;
  int MAXampDrawSpeed = 178;
  int NORMampDrawTime = 225;
  int NORMampDrawSpeed = 61.2;
  int DrawTime = MAXampDrawTime+NORMampDrawTime;
  int ServoTime = 450;
  long previousMillis =0;
  long intervalMAXamps = 100;
  long intervalNORMamps = 400;
  DC1->setSpeed(MAXampDrawSpeed);
  DC2->setSpeed(MAXampDrawSpeed);
  DC3->setSpeed(MAXampDrawSpeed);
  DC4->setSpeed(MAXampDrawSpeed);
  inPin1 = digitalRead(A0);
  inPin2 = digitalRead(A1);
  if (inPin1 == HIGH){
    unsigned long time_zero = millis();
    unsigned long current_time = millis();
    digitalWrite(1,HIGH); //turn motor on to maximum draw amperage
    digitalWrite(2,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(4,HIGH);
    while((millis()-time_zero)<(400000)){
      if( millis() >= (time_zero+NORMampDrawTime)){
      DC1->setSpeed(NORMampDrawSpeed); //set motor on to normal draw     amperage
      DC2->setSpeed(NORMampDrawSpeed);
      DC3->setSpeed(NORMampDrawSpeed);
      DC4->setSpeed(NORMampDrawSpeed);
      digitalWrite(1,HIGH); //turn motor on to normal draw amperage
      digitalWrite(2,HIGH);
      digitalWrite(3,HIGH);
      digitalWrite(4,HIGH);
    }
    if ( millis() >= (time_zero+DrawTime)); {
      digitalWrite(1,0); //turn off motors
      digitalWrite(2,0);
      digitalWrite(3,0);
      digitalWrite(4,0);
    }
    if (millis() >= (time_zero+ServoTime));{
      Servo1.write(0);
      delay(400);
      Servo1.write(90);
    }
  }
}
if (inPin2 = HIGH);{
  int MAXampDrawTime = 75;
  int MAXampDrawSpeed = 59;
  int NORMampDrawTime = 225;
  int NORMampDrawSpeed = 20;
  int DrawTime = MAXampDrawTime+NORMampDrawTime;
  int ServoTime = 250;
  unsigned long previousMillis =0;
  unsigned long intervalHIamps = 100;
  unsigned long intervalNORMALamps = 400;
  DC1->setSpeed(MAXampDrawSpeed);
  DC2->setSpeed(MAXampDrawSpeed);
  DC3->setSpeed(MAXampDrawSpeed);
  DC4->setSpeed(MAXampDrawSpeed);

  unsigned long time_zero = millis();
  unsigned long current_time = millis();
  digitalWrite(1,HIGH);
  digitalWrite(2,HIGH);
  digitalWrite(3,HIGH);
  digitalWrite(4,HIGH);
  while((millis()-time_zero)<(500)){
  if( millis() >= (time_zero+MAXampDrawTime)){
    DC1->setSpeed(NORMampDrawSpeed);
    DC2->setSpeed(NORMampDrawSpeed);
    DC3->setSpeed(NORMampDrawSpeed);
    DC4->setSpeed(NORMampDrawSpeed);
    digitalWrite(1,HIGH);
    digitalWrite(2,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(4,HIGH);
  } else( millis() >= (time_zero+DrawTime)); {
    digitalWrite(1,0);
    digitalWrite(2,0);
    digitalWrite(3,0);
    digitalWrite(4,0);
  }
  if (millis() >= (time_zero+ServoTime));{
    int  time_check = millis();
    while (millis() - time_check < 400000) {
      inPin1 = digitalRead(A0);
      if (inPin1 == HIGH ) {
        Servo1.write(0);
        delay(400);
        Servo1.write(90);
      }
    }
  }
}
}}

If you exceed the limits of the equipment you run the risk of damaging it.  Is it not possible to use an alternative power supply for the motor, and use the Arduino just as a controller.

Firstly your formatting is horrible, but that's probably just the this editor, if it isn't please fix it.
In loop() you are wasting time if you are re declaring constants, move them outside the loop.
Why have you got 4 on switches?  Could you not gang them altogether? Join the wires and use just one pin?
you are repeating blocks of code, break these out into functions, this means less code to debug. I.e. SetMotorSpeed.
If (inPin2 = HIGH)

This will always be true, because an assignment is C\C++ always returns true, you meant ==
You TA is being paid to help you, don't be afraid to p##s them off, it's there job to get p'd off at students, and their choice.  At least you are doing it by asking questions not d##king around.  That said the most likely cause of you problems with his example is missing libraries or IDE version differences.  Or even library versions, if you add the first 5 errors as a comment I might be able to point you in the right direction.

I'm going to echo what Matt said but you have way too many constants declared like variables.
A constant in C should be done like this
#define MYCONSTANT 666

right at the top of your code and outside of any setup loop or main function
Also think about the integer types you are using remember that Arduinos are 8 bit processors only use longs (32bit) where you really really have too and especially do not declare a constant as a long or int the way you have inside your loop.
This
int NORMampDrawSpeed = 61.2;

is just wrong you are saying that an int is a float, which it cannot be.
I personally avoid using floats altogether in Arduinos but if you must then declare it as a float or a constant (if it is a constant)
float NORMampDrawSpeed = 61.2;

or
#define NORMampDrawSpeed 61.2

be very careful when doing arithmetic with floats and ints because it will always return a float unless specifically typecast
better still since your new to programming just don't use them
And yes as Matt said write your own functions for stuff you need to do a lot such as
void setMotors( byte on_off ){
    for( uint8_t i=1; i <= 4; i++){
        digitalWrite(i,on_off);
    }
}

declare this function above the setup function an use it to turn all your motors on or off (1 or 0) like
setMotors(1);

Sorry but I have to disagree, constants should be done as
static const int MyConstant = 666;
And they should have the smallest scope possible, i.e. as close to the point of use as you can.
But that's just style, so it doesn't matter which way Team One goes as long as she is consistent.

Well Ok what you call style is just wasteful IMO. Do it like that and it uses up 1 or more RAM locations which cannot be optimised use a define and the pre-processor inserts a value into the program memory which would have been taken anyway by your const. So do it that way and you lose RAM and program memory.

You don't have to take my word for it either see  here link

No, your right, to much time spent on Window programming with unlimited resources.  (I still like the look of my way better though :) )

You reeeally don't want to draw current through your controller board.  It's best to use a transistor power circuit, or 741 op-amp, or relay.  Keep your power delivery separate from your control system.


text:
is it possible to convert a 328 design to use a 32U4?
I have several projects that use simple 328 based arduinos that I built myself, similar to the familiar "arduino on a breadboard" projects that I'm sure everybody has seen. They have just the bare minimum, no ftdi, etc.
Is it possible to drop in the 32U4 without modifying the circuits, or would I have to do a bunch of work to the circuits to get them to work with the 32U4 chips, and if so what are the general steps?

Just had a quick look at the datasheets, and the main difference I see physically is the 32u4 is 44 pin package and the 328 is either 32 or 28 pin.
Also the 32U4 seems to have a lot more peripherals.
So based on that yes you will have to modify your circuit. Atmel are fairly consistant with ports and what their alternate functions are though.
eg SPI on portB, uart on portD
But you are just going to have to compare the pinouts on the datasheets see how they differ. And adjust pin connections accordingly.
Datasheets are easy to find. Good Luck!


text:
Why are Arduino clones cheap?
You can buy Arduino Nano v3 clones from Alibaba at the cost of roughly $2-$3.
I have calculated the cost for fabricating and all the parts in the BOM for Arduino Nano V3, and it ended up costing around $10 to $12 (depending on where you fabricate the board, buy the components and purchasing volume - assuming less than 100 units).
However, how are Chinese clone manufacturers able to slash the price so much it's only ~1/10 of the BOM cost.
Could it purely be due to economy of scale, lower fixed costs (cheap labor), low quality parts (How do you define low quality parts)? Or are there other factors at play as well?

Most costs are cut via labor price. China is much much much cheaper than EU or USA.

All the factors mentioned in the question apply to make the cost so low.  However, with an exception or two as noted in the next paragraph, “low quality parts” is not much of a factor, as explained in two paragraphs after that.
Possible low quality parts include the USB mini-B socket, crystals or resonators, and the reset switch.  The socket and switch contain metal shapes that can be well made or badly (and more cheaply) made.  Those badly made will function but may have shorter lives and higher failure rates.  For example, the USB cable fit may be loose, or the switch may fall apart.  Crystal or resonator accuracy and stability can be poor while still allowing a Nano clone to appear to function ok.
However, SMT (surface mount technology) or SMD (surface mount device) parts on the board cannot be made significantly more cheaply than can good parts.  SMD LEDs, resistors, diodes, voltage regulators, and capacitors come off of automated assembly lines with little or no manual intervention.  See, eg, ceramic capacitor manufacturing at wikipedia.  Parts are automatically packaged into sealed reels of parts suitable for use on an automatic pick-and-place machine that populates PCBs.  In short, the dozen 0603-size SMD LEDs, resistors, and caps, and the nine other passive or small-scale-integration SMD parts on the board will cost about the same coming off a bad manufacturing line as from a good line, so there is little profit to be made producing bad parts.  The 20-odd passive parts probably cost a couple of cents, at manufacturing scale.
Active SMD parts like voltage regulators, the ATmega328P, and the 32U4 or CH340, likewise come off automated manufacturing lines.  As these parts are more expensive, there is more economic incentive for cheating, and from time to time fake parts get sold and used.  In the past (and perhaps still) there have been manufactories that specialize in removing labeling on the tops of cheap or non-functional chips, and putting accurately detailed fake labels for expensive chips on instead. (For example, NCP5318 buck regulators relabeled as ATmega328s.)  In short, most of the active SMD parts on a Nano either are genuine and work or obvious fakes that don't work and earn their sellers bad reputations or jail.
The CH340g USB-to-serial chip  vs. ATmega32U4 USB issue is more complicated.  Ie, some may think of the CH340 as a lower quality part than a 32U4.  The CH340 may need a different USB driver than the 32U4 and may not support 57600 BPS serial in some cases. 1, 2.  The ATmega32U4 seems to be available on Alibaba for $0.10 to $.20 in moderate quantities.  I think the CH340g is made only in China and is somewhat cheaper than the ATmega32U4, so its contribution to the BOM total cost may be a few cents.
The PCB probably costs 5 to 10 cents, and assembly is free except for amortized costs of pick and place machines and an IR reflow system with a conveyor.  Boards probably are processed (components placed and soldered automatically) in panels of several dozen units, tested automatically, and then separated for packaging.
Summary: Inexpensive parts and automated processing hold down the per-board costs, moreso than cutting corners on component quality.  Corners may get cut on assembly quality and on quality assurance inspections.

There are quite a few places where fabs can cut corners. Safety of the workers is one of them. Using a cheaper chip may mean just that. Also support for customers of such ICs is often shoddy.

And PCB factory uses a fair bit of water; look at this part of the process. So water pollution is another way to cut costs.

@RespawnedFluff, those comments are true, and might be part of the reason for PCBs costing under 6 cents per square inch in China, so a Nano PCB is under a dime.

@RespawnedFluff, as for support to customers, I don't know how much support you would expect from a more expensive chip. The chip manufacturer didn't sell (directly) to you, and you only bought one. I don't think Atmel would be particularly interested if you or I have a question about them.

@AMADANONInc.: That is true that as individual consumer you cannot expect much in the way of personalized attention from a big corp, however documentation and drivers are part of what I consider support. And if you visit EE.SE you'll questions about more or less obscure chips that people bought but can't figure out how to use... because the documentation is either completely lacking or perfunctory/incomprehensible.


text:
Is it possible to make a mathematical function generator using Arduino?
I want to build a function generator but not the ones which outputs square wave or sawtooth ect. I will input a discrete function lets say f(n) = e^n for n=0 to n=100 and the output array will be outputs as voltage samples creating a e^x like signal on a scope?
Is this possible?

If you attach some kind of DAC to it - why not?

but doesnt Arduino have already its own DAC?

No, why would it? Before assuming something, check the specs.

sorry Im not into micro controllers much. Isnt Arduino's analog output a DAC? if not whats that?

If you refer the analogWrite function - it is setting PWM output.

oh ok now I got it thanks. what would you recommend as a DAC converter in this case? im not into DAC hardware.

You can generate arbitrary waveforms using either the built-in PWM and a low-pass filter or an external DAC.
You won't get more than 16-bits in PWM ( or AFAIK non-audio DAC with arduino libraries ), so your e^N function will be below your resolution for most of the cycle.
Alternatively, generate a saw-tooth and use an op-amp exponential function

no I just gave an e^n as an example. I want to make one which can output any given simple function.

You can't generate arbitrary waveform using PWM, unless you have some kind of PWM-to-waveform circuitry. And the bitness of DAC is depending on DAC only, and can be as high as specified by the DAC itself.

@EugeneSh.  Add an appropriate low pass filter and PWM becomes a low-quality DAC.  If you can find a greater than 16 bit, non-audio, DAC with an arduino library, post a link.

I would say that you CAN generate arbitrary waveforms using PWM. All you need is a reconstruction filter. All 1 bit DA (sigma delta) converters basically use PWM. BUT the PWM signal from an Arduino is very low in frequency (around 400 Hz) and only 256 levels (8 bit) so very crude. You could make a half decent 10 Hz arbitrary waveform though. But note the 10 Hz, not very usefull !

Filter = circuitry. Why audio is a constraint?

Audio DACs are usually limited to a sample rate of around 200 kHz. It could be sufficient depending on what arbitrary frequency you want to generate.

whats the thing anout 16 bit? why ui that a limit?

Perhaps it's not easy (or impossible?) to find any off-the shelf gen purpose DAC with higher than 16-bits resolution. But here is an App note of a 20-bit DAC concept: http://cds.linear.com/docs/en/application-note/an86f.pdf

@EugeneSh. I think the average Arduino user has enough of a challenge to a 12 or at best a 14 bit DAC to its rated spec, higher resolution DACs are just more expensive. 20 and even 16 bit DAC's are a healthy challenge for EE pro's, let alone for hobbyists.

@jippie I agree. Just theorizing :)

@EugeneSh. As long as, in your theorising, you realise that Arduino level hardware is generally not going to outperform a 5mV to 10mV noise figure. So anything beyond 12bit with +/-5LSB accuracy at 5V reference is wasted money anyway.

@Asmyldof Why should I care of Arduino hardware, if I have some kind of I2C controlled DAC?

@EugeneSh. Because the comment was towards "Arduino level Hardware". If the OP is going to buy a DAC board ("not really into DAC hardware") and hook it up in the general way, that'll easily be 10mV coupled noise, if not more.

@user16307 PWM on ATMega uses the timers, the highest resolution one being 16 bit. As the others have noted, you probably will hit noise issues before then, but the point was more that when thinking about generating such-and-such a waveform, if a 16 bit DAC won't give you anything 90% of the time, your waveform is probably not realistic on any home-made hardware.

Arduino DUE has a built-in DAC (has two in fact) and so you can do arbitrary function generation fairly easily by just going over some arbitrary table (that sampled the function) and output that with analogWrite to the DAC channel[s]; details in this arduino.cc tutorial. They only show sine/triangle/square waves there, but if you look at Waveforms.h at the end of that tutorial you can put arbitrary shapes in there.
By the way this technique of waveform generation of using a lookup table and a DAC is abbreviated DDS for Direct Digital Synthesizer.
Here's a more conceptual tutorial on DDS (not involving arduino):
http://www.ni.com/white-paper/5516/en/
The DACs built-in Arduino DUE have 12-bit resolution by the way, i.e. 4096 discrete output levels. IF you need better than that, an external DAC is required, which you could connect by TWI/SPI etc.
You can get a poor man's DAC on the Arduino UNO or Leonardo by PWMing with analogWrite on the GPIO pins (as suggested in the other answer), but you need understand low pass filter fundamentals to get that done.

... or create an R-2R ladder on any number of IO pins you want.

@Majenko: yes, that can surely can be done but it can well turn into a project by itself: e.g http://pcarduino.blogspot.com/2013/11/arduino-r-2r-ladder-audio-dac.html


text:
Unstable reading from Raspberry Pi
I'm trying to send a signal from Raspberry Pi GPIO to Arduino. I made a sketch that basically reads the state of the digital read, but the reading are very unstable. I understand that there is a floated voltage and the obvious solution is to configure the pullup resistor and connect the input to ground, but my goal is to read the incoming signal.
I'm using Arduino Mega 2560 and Raspberry Pi 2B.
I hope this info is enough!

Please show your schematic.

It is just GPIO 5 conected to A3 of Arduino Mega.

If GPIO5 is the only thing connected and the Arduino/Rpi are on seperate power supplies then you are certainly missing a common ground reference if you want them to talk directly.

Thank you guys for your answers! Now,  what should I do?

Connect the grounds together.

Thank you! I know this was a silly question, buy I really apreciate your help! Have a nice day!

Did that comment resolve your problem? If it did it would be nice to create an answer so that others will see this as a resolved question.

You might want to check the details on the answer of Majenko (https://hackingmajenkoblog.wordpress.com/2016/02/01/making-accurate-adc-readings-on-the-arduino/#more-12)

As Majenko commented, you need to not only connect the data wires together but also the ground wire (from the Arduino to the Pi).

... the reading are very unstable ...

Without a consistent "ground reference" the readings would indeed be unstable.

Occasionally you run into situations where connecting grounds causes problems in which case a dual supply buffer or isolator can be used

@crasic that's a very interesting point (maybe not in this case, but) you might want to elaborate it in your own answer or by editing Nick's answer. In what cases should it be used, why and how?


text:
Serial Communication Problem Using Eclipse
Please help
I have created an Arduino program that will switch the pins when I send a char. It works fine with serial monitor, but the problems come when I send chars with Eclipse using RXTX serial communication. When I click the button to send the char, at first click it does not switch the Arduino pins; it just senses the Rx and Tx LED but the second time it switches on. But when I tried to switch the second LED it first turns off the first LED although that was not my aim, and then it switches the intended LED. Here is my Arduino code.
const int lamp=2;
const int fan=3;
const int pump=4;
const int fridge=5;
char val;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(lamp,OUTPUT);
  pinMode(fan,OUTPUT);
  pinMode(pump,OUTPUT);
  pinMode(fridge,OUTPUT);
}
void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available()) {
    val=Serial.read();
    if(val=='a') {
      digitalWrite(lamp,HIGH);
      Serial.print(val);
      delay(100);
    } else if(val=='b') {
      digitalWrite(lamp,LOW);
      Serial.print(val);
      delay(100);
    } else if(val=='c') {
      digitalWrite(fan,HIGH);
      Serial.print(val);
      delay(100);
    } else if(val=='d') {
      digitalWrite(fan,LOW);
      Serial.print(val);
      delay(100);
    } else if(val=='e') {
      digitalWrite(pump,HIGH);
      Serial.print(val);
      delay(100);
    } else if(val=='f') {
      digitalWrite(pump,LOW);
      Serial.print(val);
      delay(100);
    } else if(val=='g') {
      digitalWrite(fridge,HIGH);
      Serial.print(val);
      delay(100);
    } else if(val=='h') {
      digitalWrite(fridge,LOW);
      Serial.print(val);
      delay(100);
    }
  } else {
    int sensorValue = analogRead(A0);
    Serial.println(sensorValue/10);
    delay(100);
  }
}

Here is a part of my Java code
public boolean identifyport() throws PortInUseException, IOException, TooManyListenersException {
  this.setVisible(true);
  try {
    Enum=CommPortIdentifier.getPortIdentifiers();
    while(Enum.hasMoreElements())
      portname=(CommPortIdentifier)Enum.nextElement();
      if(portname.getPortType()==CommPortIdentifier.PORT_SERIAL)
        port=portname.open(this.getClass().getName(), 2000);
      serialport=(SerialPort)port;
      serialport.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_2,SerialPort.PARITY_NONE);
      input=((CommPort) serialport).getInputStream();
      output=((CommPort)serialport).getOutputStream();
      serialreader=new BufferedReader(new InputStreamReader(input));
      serialport.addEventListener(this);
      serialport.notifyOnDataAvailable(true);
      progressBar.setBackground(Color.GREEN);
      portlist.addItem(portname.getName());
      progressBar.setValue(i);
      slider_3.setValue(value);
      Thread.sleep(1000);
      prg();
    } catch (UnsupportedCommOperationException e1) {
      // TODO Auto-generated catch block
      JOptionPane.showMessageDialog(contentPane, "Check USB cable connection", "No port available ", 0);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      JOptionPane.showMessageDialog(null, "Port status", "Please connect the device....!!!!", day, null);
    }
    return rootPaneCheckingEnabled;
  }
  @Override public void serialEvent(SerialPortEvent e) {
    // TODO Auto-generated method stub
    if(e.getEventType()==SerialPortEvent.DATA_AVAILABLE){
      try {
        serial=  serialreader.read();
      } catch(Exception e1) {
        e1.printStackTrace();
      }
    }
  }
  public void writedata(int v1) {
    try {
      output.write(v1);
      output.hashCode();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

*And this is part of the switch button;*
Button button_1 = new Button("switch");
button_1.setFont(new Font("Tahoma", Font.BOLD, 13));
button_1.setBounds(10, 10, 117, 42);
panel_3.add(button_1);
button_1.addActionListener(new ActionListener() {
  int count=0;
  public void actionPerformed(ActionEvent e) {
    writedata(v1);
    if(count==0) {
      canvas.setBackground(Color.RED);
      canvas.setForeground(Color.GREEN);
      v1='b';
      count++;
    } else {
      canvas.setBackground(Color.YELLOW);
      canvas.setForeground(Color.GREEN);
      v1='a';
      count--;
    }
  }
});

Sorry I can not write everything because there is so much code.

use pastbin.com to give us all the java code so anyone can test it.

Thanks my friends, I had already solved the problem, the problem was this....
I made the method that ran after pressing each button, which sent the data at particular button, it seems the data interfered each other but I do not know why, but I had deleted that method and I used to send data using the object I created at each button.
Button button_1 = new Button("switch");
    button_1.setFont(new Font("Tahoma", Font.BOLD, 13));
    button_1.setBounds(10, 10, 117, 42);
    panel_3.add(button_1);
    button_1.addActionListener(new ActionListener() {
            int count=0;
        public void actionPerformed(ActionEvent e) {
            if(count==0){
                canvas.setBackground(Color.RED);
                canvas.setForeground(Color.GREEN);

                char v2 = 'a';
                try {
                    output.write(v2);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            count++;
            }
            else{
                canvas.setBackground(Color.YELLOW);
                canvas.setForeground(Color.GREEN);
                char v1 = 'b';
                try {
                    output.write(v1);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                count--;
        }

        }

Now it worked fine....!!!!.

The java code you wrote should send just 'a' and 'b' so you should see just lamp turning on and off.
Move writedata invocation just before count++ and count-- statements to solve your "first time". The problem could be the initialization of v1.
Into writedata method why do you call hashcode on the output stream? Maybe flush?


text:
Ideal settings for regulated power using Arduino Uno VIN?
Is there a downside to providing a lot of amps to Arduino UNO's VIN? Is there any advantage to only supplying a limited amount of amps? I have a regulated power supply and I'm curious what I should set it to when going through the 5v port?
Also, should I stick with 5 volts? I've seen some tutorials say if powering the board through VIN it should ideally be much more than that?
Is there a spec sheet of sort that tells you this?

https://www.arduino.cc/en/Main/ArduinoBoardUno Input Voltage (recommended)  7-12V

@Gerben so you can put you 12 V in through the 5 V, VIN pin?

You can put 12V only in the Vin pin. Putting it in the 5v pin will probably make smoke.

Honestly, it doesn't matter how much power (amps) you make available, it will only draw what it needs.
However, there is definitely something to be said for limiting how much power you provide.  If something in your circuit is miswired or otherwise shorts out, limiting the circuit to something reasonable (wisely including a fuse in your design as well) means that you won't have some enormous current suddenly passing through burning stuff out and possibly injuring someone. :)
As far as what to provide in terms of volts and amps, the data sheet for your particular arduino is the place to go.  As long as you are providing that you are in good shape.

From https://www.arduino.cc/en/Reference/Board :

The input voltage to the Arduino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin. Note that different boards accept different input voltages ranges, please see the documentation for your board.

For specific values, visit https://www.arduino.cc/en/Main/Products?from=Main.Hardware and select your board, and look down to where it says "Input voltage" - there's a "recommended" and "limit", each being a range. Note that some power sources will fluctuate (e.g. 4 AA batteries are 6 volts, possible slightly higher when brand new, but will drop down if there is a high drain, or as they get used up. 4 AA batteries will not provide 6v for long).
As for current (measured in amps or milliamps), if the power supply cannot supply what is used by the board, it will overheat; if it provides more than is required, then it will work 100% perfectly well (so long as you don't have a short circuit). The current an Arduino on it's own will draw will vary depending on the board, Nick Gammon measured an Arduino Uno Rev 3 board at 50 milliamps, but LEDs will typically draw around 20mA each; motors will draw a lot more. 1000mA = 1 amp, so Nick's Uno would draw 0.050 amps. Power supplies typically say on them how many amps (or in some cases, milliamps) they can (safely) provide.

Right, but is there any danger to supplying to many amps to the arduino if the load demands and it's available will that damage the controller in a fashion that limiting the amps from the power source wouldn't?

As I indicated in my answer, not directly.  There is no risk to your circuit if everything is designed properly and connected properly.  The only risk is if a part fails as a short or something is not correctly wired or something else happens that creates a short circuit to ground.

Also, you don't say how much is the idea to power the board though VIN?

It varies from board to board - that's why I say "for specific values, vist...."


text:
LED Control through bluetooth
I have an Android app that sends data to the arduino HC-06. It is however giving me colors i did not send to it. Eg. Red in place of green, white in place of red etc.
Here is a snippet of my android code that sends the data via bluetooth
 public void onColorChanged(int color) {
    BluetoothV2 bluetooth = new BluetoothV2();
    int r,g,b;
    r = Color.red(color);
    g = Color.green(color);
    b = Color.blue(color);
    bluetooth.Message(r+","+g+","+b);
 }

Here is a snippet of my arduino code
void loop() {

if(Serial.available()>0){

while(Serial.available()>0){
   char inChar = (char)Serial.read();
   inputString += inChar;
}
   int red = Serial.parseInt();
   int green = Serial.parseInt();
   int blue = Serial.parseInt();
   color(red,green,blue);
   inputString = "";
   Serial.println("R:"&& red &&"G:"&& green &&"B:"&& blue);
  }
}

void color (unsigned char red, unsigned char green, unsigned char blue){
   analogWrite(redPin, 255-red);
   analogWrite(greenPin, 255-green);
   analogWrite(bluePin, 255-blue);
}

Terminal data
               2,,,,,,,,,,,,,2,,5,,,,,,,,,,,,,,,,,,,,,,,,,02725,1,502725,,,,,,,,,02514,5,602515     ,5,3,,,,,025

Is the problem how i get the data though Serial.read()? Or what am i missing

When you say "terminal data" where is it coming from? What do you see in the serial monitor of the arduino IDE?

Why read characters to inputString and then parseInt()? And the Serial.println("R:"&&...) is strange that it even compiled. Try printing each value separately.

@Madivad i meant data from my serial monitor.

@MikaelPatel i was doing parseInt() to separate the commas in between the data eg data received=255,255,255. inputString is equated to that data and parseInt() the first time gets me the first value before the comma and the second time the second value after the first comma to the next comma(next character thats not of int data type). However i solved this issue. Let me post my answer.

int firstcomma = inputString.indexOf(',');
int secondcomma = inputString.indexOf(',',firstcomma+1);
String r = inputString.substring(0,firstcomma);
String g = inputString.substring(firstcomma+1,secondcomma);
String b =  inputString.substring(secondcomma+1);
red = r.toInt();
green = g.toInt();
blue = b.toInt();
Serial.print("R");
Serial.print(red);
Serial.print("G");
Serial.print(green);
Serial.print("B");
Serial.println(blue);

This solved my problems.

Maybe you can try again with something like this to check if the android part is not correct. From your terminal output it seems that you receive values higher than 255.
void onColorChanged(int red, int green, int blue) //values from 0 - 255
int r,g,b;
r= red;
g= green;
b= blue;
bluetooth.Message(r+","+g+","+b);

The receive part in your arduino code is like my code for a similar project.
Try setting your color in the arduino code like this to check if the example code from above works:
void color (int red, int green, int blue)
{
analogWrite(redPin, red);  //the higher your send value the brighter the color
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}


text:
How to transmit more than 1 byte continually?
In software serial, the write function only sends 1 byte at a time. Is there someway, some library, that i can send multiple bits/bytes, without stopping (and not using digitalWrite)? i want to be able to transmit at least 16 bits as opposed to just 8.
I know i can send 2 bytes, or even 100 bytes. But the thing i'm trying to do is, implement my own LDPC(error correction) codes on the Arduino. Therefore, i'm taking a lot of channel measurements. One of them is figuring out how the error happens during the delay between the stop bit and the next startbit. Often times, this is were synchronization problems occur. So I'm trying to track this down. Hence why, I need to send more than 8 continuous bits. In software serial, it transmits 8 bits, then transmits the stop bit. then write() restarts on the next call. Instead of this, i just want to send more bits, like 64 bits for instance, and look at the BLER on the received data. (the reason why I'm staying away from hardware serial is because i'm doing this with wireless RF modules) Do you guys have any further info regarding this? I'm very grateful! Thank you so much!
Also, it was suggested that I write my own softwareserial, but that's a pretty daunting task. I would like to avoid it, if i can.
EDIT: Let me show you my data.
So, I'm constantly transmitting the values; 123,124,125,126.
1111011
1111100
1111101
1111110

The above 4 lines repeat about 2 times. Then, suddenly, it synchronizes incorrectly, and the following 4 lines are being constantly repeated.
11110101
11111001
11101101
11110001

It never syncs back to the original 4 transmissions. Now, inside the unsynced block of 4 transmitted bytes, there are fragments of the correct transmission inside. For instance, start from the 2nd bit of the 3rd byte of the correct transmitted byte. Now, if you account for the '0' start bit, and try to matchup the bits, the correct bits are being picked up in the correct order. It's just a problem of what the receiver takes as the startbit.
As i'm typing this edit, i realized something else. What i said in the above paragraph is true, then for the unsynced block, there should be a '0' start bit in front. Now, if the messages match up exactly, and if the 0 start bit that is being transmitted is being treated as a payload, then which 0 is being treated as the startbit, because all the bits between the synced and unsynced data are matched up. However, there should be one missing 0 each time because it's being read as a startbit, not databit.
Sorry if this is convoluted. Happy to clarify any part of it. Thank you so much!!

Is it possible to just go into my write function, and just change the loop from iterating 8 times to 32, and then make the parameter take in 32, and do the according changes just in that function? I'm 99% sure changing software serial isn't that simple and that other parts of the code would be affected, but worth a shot.

figuring out how the error happens during the delay between the stop bit and the next startbit - there can be any time between the stop bit and the next start bit.

@NickGammon Hello sir, can you please take a look at my edits? thank you so much!

How much gap (in time) do have between blocks of data?

I've tried both ways. Having no delay and having some delay. With a delay, it works fine. However, my question is how the synchronization can happen the way it is. Because the right data is being shifted and I am able to do a perfect one to one mapping of how it was shifted, however, because the data being read is starting at a different point, there should be one missing 0 that's being treated as a start bit. @NickGammon

With no delay on the sending end, a slight pause at the receiving end means it misses the start bit. Then the next zero to come along appears to be the start bit, and you get the bit shifting you talk about. A small delay is probably very advisable.

Yes, the next zero to come along should be the start bit. However, that 0 is not missing. Because the startbit shouldn't be printed, but i don't see any missing zeros in the 2nd (unsynced) data. Also, I'm using the same "read without block" that we discussed in a previous post. I'm not sure if I'm being clear. So there is an exact mapping from the actual data to the unsynced one. However, when it becomes unsyncde, some new 0 bit should be treated as the startbit, in which case it should not be printed. But i don't see any misisng zero. It's as if the actual data just got shifted.  @NickGammon

I want to point out here that async serial communications relies on both ends providing a clock (there is no transmitted clock signal). Thus the sender clocks out bits at the "baud rate" (eg. 9600 bits per second) and the receiver clocks them in at the same rate.
With a start bit and 8 data bits therefore you can tolerate some difference in the clocks between sender and receiver (and there will be some difference). Effectively you could probably tolerate around a 10% difference in clock frequencies, as even if they are out by 10% the sample at the receiver will still land inside the data bit of the sender.
Now if you want to transmit 64 bits you have reduced this error margin by a factor of 8. So let's say (ball park) that you can now only tolerate a difference of 1% between sender and receiver.
You now need to be pretty sure that the clocks on the respective boards are pretty accurate. The Uno, for example, has a resonator CSTCE16M0V53-R0 which appears to have a tolerance of 0.5% and a frequency stability of 0.2%.
So, if the sender is running 0.5% slow, and the receiver 0.5% fast, you will almost certainly get errors.

However, when it becomes unsyncde, some new 0 bit should be treated as the startbit, in which case it should not be printed. But i don't see any misisng zero. It's as if the actual data just got shifted.

How will it get unsynced?  I don't think you are following how serial comms works. If you don't have any delay between bytes (or batches of bytes in your case) then it is impossible to resync, because if you miss a start bit, all the following bits will appear valid, they'll just be shifted. This is exactly what you are describing.
Really, to ensure syncing you need to have a gap between bytes (or batches-of-bytes in your case) longer than a byte might be, otherwise you can get this mis-sync happening. So if you make your batches longer, the gap has to be longer, effectively removing the slight advantage of larger batches.
Imagine you have an incoming stream of bits on the receiver:
011110101101100011110101101101101100110101100101100110101111001010101110111001010101111
1101001010100101101001010100111011111001000010111100100011011001001001001011001001010

And imagine that you missed that first start bit. Without a gap between bytes (which would appear as: 111111111) you have no way of knowing which is a start bit and which is a data bit. Valid data would have a start bit, so you don't mistake valid data for the inter-byte gap.
In other words, with 8-bit bytes, data will always be 0xxxxxxxx1 and thus a gap of 1111111111 must be the gap and not data because there is no zero there. But with any shorter gap, and if the receiver samples in the middle of byte, it certainly might think that the next 0 in the stream is a start bit (wrongly).

The question concerns transmission via radio, so serial clock differences are probably not the source of error.  Rather the poster is investigating channel noise.

@NickGammon,  hey, I've made some edits to the question to show exactly what's happening. Thank you so much for all your help, once again.

@ChrisStratton, Hey, yes, I am investigating channel noise, but it seems that the mis-synchronization ultimately does give me incorrect data as well. My goal, however, IS to analyze channel noise and implement optimal error correction code. But i'm trying to get past this incorrect synchronization problem first.

Unless you have bad crystals or diverse implementation with badly approximate divider ratios, it is relatively unlikely that there is an actual "synchronization problem" behind what you are seeing.  Rather, you are probably seeing noise in the radio channel, possibly noise which is interfering with the detection of synchronization or clock recovery.


text:
Unable to upload sketch on Mac OSX El Capitan
I recently dusted off an old Arduino Duemilanove to play with. I can connect it to my Mac laptop with the same USB cable I used previously and I'm able to monitor the serial port and see the output from the last sketch I uploaded (five years ago). Everything is unplugged from the board.
When I try to upload a new sketch, the Arduino IDE gets stuck on Uploading... indefinitely:
Using Port                    : /dev/cu.usbserial-A800eGZI
Using Programmer              : arduino
Overriding Baud Rate          : 19200

The board itself has the green PWR LED and amber TX LED on solid once the currently loaded sketch starts running. Initiating an upload causes the amber L LED to blink three times, then the RX LED blinks twice, and finally the TX LED on solid.
Here is the exact board: https://www.sparkfun.com/products/retired/666

My research into this issue produced many suggestions that have not resolved the problem...
I disabled the built-in FTDI driver:
sudo kextunload -b com.apple.driver.AppleUSBFTDI

And made sure the FTDI driver from ftdichip.com was loaded:
sudo kextload /Library/Extensions/FTDIUSBSerialDriver.kext

I tried csrutil enable --without kext against my better judgement and saw no change.
I also tried a completely separate machine -- my PC running Windows 10 -- and the upload hung there too.
I have tried timing the upload to coincide with a board reset, hoping to sneak my upload in before the current sketch starts running. I did this a lot and got no satisfaction.
I haven't given up yet; there are too many signs of life to think that it's unrecoverable. I'm looking for more suggestions on how to troubleshoot.
I have already ordered another Arduino -- hopefully I can use it to burn the bootloader on the Duemilanove.

This may be relevant: https://github.com/arduino/Arduino/issues/3928

The problem was that I selected ATMega168 when I should have selected ATMega328

Possibly the boot-loader baud rate in the IDE's boards.txt file is wrong. I have older (less than 6 years) '328p chips whose boot-loaders expect 57600 baud, but the boards.txt file in more recent Arduino IDE's try to talk to them at 115200 baud. I've had to duplicate the Arduino Uno entry in boards.txt and make one that specifies 57600 baud, to use these chips.

Thanks for your comment -- ultimately it led me to check everything again which uncovered my mistake.


text:
Reading from ps2 barcode scanner
I am trying to read from a ps2 barcode scanner (Datalogic gryphon D).
The Arduino is powered by the USB. The circuit is shown below

The pinout of the ps2 is

I have used the fritzing pin assignments when making the diagram.
I am using the code from here
#include <PS2Keyboard.h>

const int DataPin = 8;
const int IRQpin =  5;

PS2Keyboard keyboard;

void setup() {
  delay(1000);
  keyboard.begin(DataPin, IRQpin);
  Serial.begin(9600);
  Serial.println("Keyboard Test:");
}

void loop() {
  if (keyboard.available()) {

    // read the next key
    char c = keyboard.read();
    Serial.print(c);
  }
}

The scanner scans and indicates that the scan was successful. The Arduino code shows "Keyboard Test:", but none of the scans show anything. What am I doing wrong?

Pin 5 isn't an IRQ pin, is it? You want pin 2 or 3 for that...

That article doesn't include those pull-up resistors. PS I doubt you need an added power supply. The maximum current of PS2 (275 mA) is below that of USB. So even adding the few mA that the arduino uses you won't reach the 500mA limit of USB.

@Majenko I have edited the question. The pins appear to be in the wrong order because I followed fritzing rather than the physical device.

@Gerben I put in the pull-up resistors because of an article I found (but can't find again). I have removed them now but it still doesn't read. PS  I was connecting through a USB repeater cable and I think it was restricting the current. Getting rid of the repeater allows the scanner to correctly start up, but it is not stable. Most scans fail when it is powered through the Arduino.


text:
Problem with analog pins' name when trying to connect Arduino board and Processing
I am trying to use Processing with Arduino Uno board to read the change of voltage done by a potentiometer. The code is simple:
import processing.serial.*;
import cc.arduino.*;

Serial myport;
Arduino arduino;

color off = color(4, 79, 111);
color on = color(84, 145, 158);
int val=0;
float value=0;
void setup() {
  size(600, 600);
  println(Arduino.list());
  arduino = new Arduino(this, Arduino.list()[0], 57600);
  arduino.pinMode(0, Arduino.INPUT);
}

void draw() {
  stroke(on);
  value = arduino.analogRead(0);
  println(value);
  ellipse(300,300,value,value);
  delay(100);
}

My question is: For analog pins in Arduino IDE one should type A0, A1, ... but here in Processing IDE it is an error to type so. Is it possible that Processing reads the wrong pin? Because in Serial output I always get zero, however, for the same circuit in Arduino IDE the values change as I turn the potentiometer knob.
Thanks

Have you uploaded the firmata to arduino? (instructions from arduino playground - "Run Arduino, open the Examples > Firmata > StandardFirmata sketch, and upload it to the Arduino board."

Yes, I already did that. Also tried different values as the port number but still the outputs are always zero

you have a typo in code? val = arduino.analogRead(0); shouldn't it be value? Because after you only use value and never val

it was typo in the code here but in my original code it is correct.

strange... your code works ok with me. I've shorted the 3.3v to analog A0 and your code fluctuates between 679~680 in processing screenshot. if it helps, this is the software versions I'm using: Processing - 3.0.1 Arduino IDE - 1.6.6 Firmata - 2.5.0

I downloaded the new version of Firmata for Arduino and now it works. Strange! But it is solved anyway.
Thank you very much.

@Personagem it seems your comment led the author to solving his problem. You should bump it down to an answer and hopefully the OP will accept it for you :)

(as suggested in comments to bump it down)
your code works ok with me. I've shorted the 3.3v to analog A0 and your code fluctuates between 679~680 in processing

If it helps, this is the software versions I'm using: Processing - 3.0.1 Arduino IDE - 1.6.6 Firmata - 2.5.0

Just a comment that can help others is that list of ports is important in order to find the right port.


text:
How to know if arduino activated its short breaker?
today i was trying to use arduino power headers as a power source for my basic laser.
I used pin "5V" to connect it to the laser anode and the "GND" pin to the laser groung pin.
after doing this arduino turned restarted, so I removed all the connections to the laser, now the arduino is normal.
booth "5V" and "GND" pins is working normal.
does this mean that I made a short circut and arduino protected it self ?
should I do anything now ?

What's the rated current and voltage for your laser?  Laser diodes, like LEDs, typically need a constant-current controller (or a properly sized series resistor).  Eg a red LD might use about 200 mA and develop a voltage of about 2.35 V.  Putting 5 V straight into it may ruin it.

It sounds like connecting your Laser to the 5 volts power supply did draw too much current, thereby the 5 volts dropped to very low voltage.
The Arduino didn't "protect" itself.  The Arduino simply shut down because of voltage being too low. Then, upon reapplication of 5 volts the Arduino re-started as normal.
You don't mention any details about the Laser.  But if your Laser is simply a Diode, the Laser diode would draw a lot of current, resulting in the 5 volts power source giving reduced voltage.
If your Laser is a "laser module" with a built in driver, perhaps you connected the Laser backwards to the 5 volts.
EDIT 11/20/2015 :  IF you are using the Arduino UNO ,  : The  PolyFuse only protects from 500 mA overload on the USB connector.  Schematic for the UNO shows that 5 volts for USB is called "XUSB". The  PolyFuse connects from "USB VCC" to the XUSB.  When you connected your Laser to the +5 and ground, the  PolyFuse was not involved. (Unless of course you did connect to the USB 5 volts (XUSB), and didn't tell us that.
HOWEVER,  if you powered your UNO from the USB port, then the  PolyFuse WAS involved and did shut you down as others have commented.

You uses more the 500mA limit, and the PolyFuse tripped. After unplugging the polyfuse cooled down and "reset" itself.


text:
Reading Reveive Hold Register from USART in SPI Mode on Arduino Due
Sending with this function here works fine:

uint16_t usart0spiTransfer16(uint16_t spiMessage16) {
    uint16_t sdo = 0;
    byte firstByte = spiMessage16;
    byte secondByte = (spiMessage16 >> 8);
    while (((USART0->US_CSR  >> 1) & 1) == 0);
    digitalWrite(SS, LOW);
    USART0->US_THR = secondByte;                //write to USARTO Transmit Hold Register

    //this byte is returned twice
    secondByte = USART0->US_RHR;                //read from USART0 Receive Hold Register
    while (((USART0->US_CSR  >> 1) & 1) == 0);  //TXRDY: Transmitter Ready
    USART0->US_THR = firstByte;

    //trying to read a second time gives me the same value as before
    firstByte = USART0->US_RHR;

    while (((USART0->US_CSR  >> 9) & 1) == 0);
    digitalWrite(SS, HIGH);

    sdo = (firstByte << 8 ) | (secondByte & 0xFF);
    return sdo;
}

and when i wait for RXRDY after secondByte = USART0->US_RHR; with while (((USART0->US_CSR  >> 0) & 1) == 0); i will stay there forever since it does not change
how do i read the registers value for the second time?


text:
Here is my code and i keep getting this error expected primary-expression before'}' token
#include <QTRSensors.h>
#define NUM_SENSORS 8
#define TIMEOUT 2500
#define EMITTER_PIN QTR_NO_EMITTER_PIN
QTRSensorsRC qtrrc((unsigned char[]) {10,7,6, 5, 4, 2,16,14},
NUM_SENSORS, TIMEOUT, EMITTER_PIN);

unsigned int sensorValues[NUM_SENSORS];
int dirB = 12;
int speedB = 3;
int brakeB = 8;
int dirA = 13;
int speedA = 11;
int brakeA = 9;
int e=4;
int MzSensor=17;
int xp=4;

void setup() {
delay(500);
int i;
pinMode(13,OUTPUT);
digitalWrite(13,HIGH);
for (i = 0; i < 200; i++)
{
  qtrrc.calibrate();
}
digitalWrite(13,LOW);
Serial.begin(9600);
delay(100);
Serial.println("Robot");
for (i = 0; i < NUM_SENSORS; i++)
{
  Serial.print(qtrrc.calibratedMinimumOn[i]);
  Serial.print(' ');
}
Serial.println();
{
  Serial.print(qtrrc.calibratedMaximumOn[i]);
  Serial.print(' ');
}
Serial.println();
Serial.println();
delay(100);
}
void loop() {
Serial.print('ogeday');
unsigned int position = qtrrc.readLine(sensorValues);
unsigned char i;
for (i = 0; i <NUM_SENSORS; i++)
{
  Serial.print(sensorValues[i] * 10 / 1001);
  Serial.print(' ');
}
Serial.print("   ");
Serial.println(position);
delay(200);
if (digitalRead(MzSensor)==0) {
  while(digitalRead(MzSensor)==0) {
    digitalWrite (dirA, HIGH);
    analogWrite(speedA, 76);
    digitalWrite(dirB, HIGH);
    analogWrite(speedB, 76);
    xp == 5;
    Serial.println("durdu");
    delay(100);
  }
  delay(800);
  Serial.println("CIKTI");
}
else
if (position >= 3250 &&position <= 3750)
{
  if(sensorValues [1] < 500 )
  {
    e=7;
    xp=3;
  }
  if(sensorValues [8] < 500 )
  {
    e=1;
    xp=3;
  }
  if (sensorValues[3] < 500 || sensorValues[4] < 500 || sensorValues [5] <
  Serial.println("ILERI"),
  digitalWrite(dirA, HIGH),
  digitalWrite(brakeA, LOW),
  analogWrite(speedA, 72),
  digitalWrite(dirB, HIGH),
  digitalWrite(brakeB, LOW),
  analogWrite(speedB, 72),
  e=4,
  xp=3,

  delay (1),

}

 else if (position > 4050 || sensorValues [8] <500)
  {
    Serial.println("EN SAG");
    digitalWrite(dirA, LOW);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 19);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 45);
    e=1;
    xp=3;
  }
  else if (position <- 4050 &&position >- 3900)
  {
    Serial.println("SAG");
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 51);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 60);
    e=1;
    xp=3;
  }
  else if (position >= 2950 &&position <= 3100)
  {
    Serial.println("SOL");
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 60);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 51);
    e=7;
    xp=3;
  }
  else if (position < 2950 || sensorValues [1] < 300 )
  {
    Serial.println("EN SOL");
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 45);
    digitalWrite(dirB, 45);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 19);
    e=7;
    xp=3;
  }
  else if (e==7) {
    Serial.println("Cizgi SOLLL");
    if (xp!=1){
      digitalWrite(dirA, LOW);
      digitalWrite(brakeA, LOW);
      analogWrite(speedA, 30);
      digitalWrite(dirB, LOW);
      digitalWrite(brakeB, LOW);
      analogWrite(sppedB, 30);
      xp=1;
      delay(1);
    }
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 66);
    digitalWrite(dirB, LOW);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 48);
    e=7;
  }
  else if (e==1) {
    Serial.pirntln("{Cizgi SAGGG");
    if(xp!=1) {
      digitalWrite(dirA, LOW);
      digitalWrite(brakeA, LOW);
      analogWrite(speedA, 30);
      digitalWrite(dirB, LOW);
      digitalWrite(brakeB, LOW);
      xp=1;
      delay(1);
    }
    digitalWrite(dirA, LOW);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 48);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 66);
    e=1;
  }
  else if (e==4) {
    Serial.println("ILERI GIDIYOR");
    digitalWrite(dirA, HIGH);
    digitalWrite(brakeA, LOW);
    analogWrite(speedA, 30);
    digitalWrite(dirB, HIGH);
    digitalWrite(brakeB, LOW);
    analogWrite(speedB, 30);
    e=4;
  }
  //delay(300)
}

On what line? And where can we download the needed include files?

Delete extra left paren in QTRSensorsRC qtrrc((unsigned char[]) {10,7,6, 5, 4, 2,16,14},

Change delay (1), to delay (1);

In this part:
if (sensorValues[3] < 500 || sensorValues[4] < 500 || sensorValues [5] <
Serial.println("ILERI"),
digitalWrite(dirA, HIGH),
digitalWrite(brakeA, LOW),
analogWrite(speedA, 72),
digitalWrite(dirB, HIGH),
digitalWrite(brakeB, LOW),
analogWrite(speedB, 72),
e=4,
xp=3,

delay (1),

There's a lot of ',' instead of ';'. Change then to ';'.
Also, the 'if' is incomplete. Check the 'if' statement.

if (sensorValues[3] < 500 || sensorValues[4] < 500 || sensorValues [5] <
  Serial.println("ILERI"),

if() condition is not complete
; not ,

A little advice. Use functions so that your code is easy to read and easy to debug (looking for errors).
Something like :
void func(String text, boolean mDirA, boolean mBrakeA, int mSpeedA,
    boolean mDirB, boolean mBrakeB, int mSpeedB){

    Serial.println(text);
    digitalWrite(dirA, mDirA);
    digitalWrite(brakeA, mBrakeA);
    analogWrite(speedA, mSpeedA);
    digitalWrite(dirB, mDirB);
    digitalWrite(brakeB, mBrakeB);
    analogWrite(speedB, mSpeedB);

}


text:
Sending and receiving custom messages with Ardulink
I am sending custom code to Arduino with this ardulink command:
{        ArduinoControl.link.sendCustomMessage("oled");
}

Code from standard Ardulink sketch CustomMessagesChipKit.ino:
{
  if (stringComplete) {
    if(inputString.startsWith("alp://")) {
    // OK is a message I know (this is general code you can reuse)
      boolean msgRecognized = true;
      if(inputString.substring(6,10) == "cust") { // Custom Message
        // here you can write your own code.
        int separatorPosition = inputString.indexOf('/', 11 );
        int messageIdPosition = inputString.indexOf('?', 11 );
        String customId = inputString.substring(11,separatorPosition);
        String value = inputString.substring(separatorPosition + 1, messageIdPosition);
        if(customId == "oled") {
            //Clear the virtual buffer
            lcd.noBacklight();
            analogWrite(9,100);
            digitalWrite(13, HIGH);
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("jkhgvjgv");
        } else {
          msgRecognized = false;
          // this sketch doesn't know other messages in this case command is ko (not ok)
        }
      } else {
        msgRecognized = false;
        // this sketch doesn't know other messages in this case command is ko (not ok)
      }
      // Prepare reply message if caller supply a message id (this is general code you can reuse)
      int idPosition = inputString.indexOf("?id=");
      if(idPosition != -1) {
        String id = inputString.substring(idPosition + 4);
        // print the reply
        Serial.print("alp://rply/");
        if(msgRecognized) { // this sketch doesn't know other messages in this case command is ko (not ok)
          Serial.print("ok?id=");
        } else {
          Serial.print("ko?id=");
        }
        Serial.print(id);
        Serial.write(255); // End of Message
        Serial.flush();
      }
    }
    // clear the string:
    inputString = "";
    stringComplete = false;
  }}

As a result the LED on pin 13 is turning on after message from java program. But that is all. LCD or or LED on PWM 9 pin are not reacting at all.
Also I could not understand how to send an answer back from Arduino to Ardulink. Can you please show me an example? I would love to send and print data in Java program from  DHT11 sensor in response. I know about RawDataListener and I read the whole Ardulink site, but I did not understand that. I a newbie in programming.
When i replace
{String customId = inputString.substring(11,separatorPosition);}

with
{String customId = inputString.substring(11,15);}

than everything works. What can it be?

you can read a complete (real project) example about how to receive messages from Arduino with Ardulink from here: https://github.com/openQCM
In general you can use a listener (digital, analog, and raw) to receive messages from Arduino. A raw listener receive all messages received from Arduino, so you need to implement code to filter the messages you are interested in. Digital and Analog listeners receive events from digital and analog PINs.
The sketch in your question isn't the original sketch you can find in Ardulink distribution. That sketch was written to manage the OLED on the ChipKit shield I have. You have modified the sketch to manage your LCD.
Actually you can send successfully messages from an Ardulink based application (as Ardulink Console) to Arduino since LED on PIN 13 is turned on. So the problem maybe just on your sketch.
To FIX analogWrite on PIN 9 try to set the PIN as OUTPUT with this statement:
pinMode(9, OUTPUT);
I cannot help you with lcd library that I don't know.
If you need for some help don't hesitate to write to me.

PIN 9 is set as OUTPUT, but it still does not work. I thought it was smth with library too, but i guess it is not.

It looks like you're trying to send a custom message to arduino and have it respond. As a small add on to your code try serialCommand. It pulls in whatever you send over the command line and executes it as a command and returns whatever you need to whatever interface you gave such as softwareSerial.
https://github.com/scogswell/ArduinoSerialCommand/tree/master/examples
I offer that you could use the two together to get the results you want.
Let serialCommand listen for commands and execute them and then set up a listener in Java for any serial communication back from the unit.
That's more or less what I end up doing when it comes to bluetooth, rf24, and wifi anyway, so why not serial as well.


text:
Using embedXcode with Adafruit Trinket
I'm trying to get set up to develop for the Adafruit Trinket on a Mac running the OS X El Capitan beta (10.11.2 beta) with Xcode and embedXcode. I've got the Arduino IDE downloaded from arduino.cc installed as /Applications/ArduinoCC.app. I'm able to build and run the Blink example using the Arduino IDE and Xcode appears to also work (it knows about the Trinket, and claims to successfully load the code) but it does not blink. The red LED on pin 1 just continues to pulse at about 10 Hz as if it was waiting to for code to be loaded.
Any ideas what could be going on or how I can troubleshoot further?
Updates:

I've made the changes to avrdude.conf suggested by the folks at Adafruit to accommodate the erase timing requirements of the Trinket.
I got a response on the Adafruit forum that suggested going back to 1.6.5 as many people have been reporting problems with 1.6.6 breaking things. However, I can program the board using 1.6.6.

Maybe F_CPU is set incorrect. Try increasing the delay between turning the led on and off, and see if the led blinks slower.