text:
Receiving and sending on the Arduino Duemilanove with an MAX3232 chip
I have a max3232 hooked up to the RX and TX pins of the Arduino Due.  I'm trying to write a simple program to relay messages received from USB and output as RS232 through the chip.  Here is my code:
char readbyte;

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

void loop(){

  while (Serial.available() > 0 ) {
    readbyte = Serial.read();
    Serial.print(readbyte);
  }
}

This program works when I don't have the MAX2323 hooked up (e.g. I send "123" and get "123" echoed back), but when I hook up the MAX2323, the Arduino isn't sending back.  I've written another test program that sends random data and it seems to work fine.  I'm at a lost at what is wrong with my simple program, can anyone help?
Here is the schematic:

You tag by two different boards with different serial port implementations.  Is it a Due or Deumilanove?  Also be more specific about the hardware connection.  What pins on Arduino are connected to what pins on MAX?

Please post the circuit diagram

@jdr5ca Oops, sorry I thought they were the same thing.  I have the Deumilanove, I have corrected the tags.

@geometrikal I've added the schematics to my question.  The RXD line goes to pin 0 (RX) of the Duemilanove, and the TXD goes to pin 1 (TX).  This circuit is straight from the datasheet.

I did some more testing.  I've hooked up a ft312d (usb to rs232) to the max3232, so my system now is like this:  Android tablet <--> USB to RS232 <--> MAX3232 <--> Arduino Duemilanove <--> PC via USB.  If I send commands with the tablet, the PC can receive the commands just fine, but sending commands from the PC to the tablet doesn't work.

With your final comment, the behavior is understandable.  The schematic will help

You have wired two devices to the single UART on the processor.
The TX pin (output) on the ATMEGA8 is connected to the input pins of both your MAX2323 and the FT232 chip on the Ardiuno.  That works okay because 1 output pin can easily drive 2 inputs.
The RX pin (input) on the ATMEGA8 is connected to the output pins of both your MAX and FT.  The two transceivers are both attempting to drive the single input -- this is a bad thing.  When one output pin tries to drive logic 1 and the other is driving logic 0, one of the devices will win and one will lose.  Whether any of the devices is physically damaged depends on whether one device can source enough current to damage the other.
But you haven't broken anything because of the wise series resistors, R8, you see on the schematic.  The series resistor limits the current to 5 mA even if you short the RX pin to ground.  The series resistor is what creates the unequal behavior:

The ability of the FT chip to source current and drive a logic 1 is limited. So when the FT chip tries to drive logic 1 and the MAX is output 0, a 5 V drop will be seen across R8.  The RX pin is on the MAX side, so the Arduino sees 0.
The MAX chip is not limited.  When it drives 1 and the FT is at 0 there is still 5 V across the resistor.  But the RX pin is on the MAX side and sees the 1's (data).

If you want the Arduino to receive from two devices you need to "add" the data correctly with a circuit.  There are several ways, here are two:

Use an OR gate to combine the data.  The serial bus is idle at zero.  When data comes across it is a sequence of 1 bits.  Remove R8 and connect the M8RXD side to the OR input.  Connect the MAX to the other OR input.  Connect the OR output to the RX input.
Cheap and small is "wire or'd".  Remove R8 and replace with small diode, pointing at RX.  Connect small pull down resistor (10k) from RX to ground.  Connect external MAX with diode pointing at RX.  In this arrangement, either chip will source current towards the RX ping to drive a logic 1, but neither chip can sink current to drive the logic 0.  Only the pull down resistor creates the 0.

authors: Андрей Титов


text:
Why does my dc motor immediately spin when connected to a 9v battery?
I've set up a DC motor connected to my Arduino Uno with the following layout. I'm using a 1.5V - 3V DC motor that was purchased from RadioShack.
Here is my code:
int controlPin = 9;

void setup(){
  pinMode(controlPin, OUTPUT);
  Serial.begin(9600);
  while(!Serial);
  Serial.println("Ready");
}

void loop(){
  if(Serial.available()){
    int s = Serial.parseInt();
    if(s >= 0 && s <= 255){
      Serial.println(s);
      analogWrite(controlPin, s);
    }
  }
}

If I connect the motor through the Arduino 5V pin it only hums until I set the speed s to 200 or greater. This seems odd because I'm supplying 5V.
As a next step I decided to try a 9V battery (I don't really care if I fry the motor, I just wanted to experiment). Of course this is over the recommended voltage, but I assumed if I sent a low enough signal (s) through pin 9 it might not destroy the motor. However, to my surprise, when I connected the 9V battery (as illustrated below) the motor immediately starts spinning. I measured the current and it seems to be ~150mA when connected to the 9V battery. It seems like the circuit is connected even though I'm not sending any signal from pin 9 to the transistor. If I removed any of the wires connected to ground, the motor, obviously, stops spinning. My expectation, which is apparently wrong, was that the motor wouldn't spin until I sent a signal from pin 9 to the transistor. What am I not grasping here?

Here's a picture as my diagram may be wrong based on comments below. This shows the diode reversed as suggested by Chris.

I also moved the jumper going from pin 9 to the breadboard out of the Vcc column and directly into the row with the resistor. I'm not sure if that resolves the short mentioned in comments.

If you connect the base resistor to ground instead of the Arduino, does the motor stop?  If not, you probably have either mixed up the pins of the transistor such that it is merely functioning as a diode (very easy to do - especially "pin circle" vs "pin line") or have already blown the transistor.

You should try to respect usual conventions on breadboard usage: the 2 pairs of lines one each side should be reserved for Vcc and GND. The way you wire your breadboard makes it more difficult to interpret.

Also it seems your 280 Ohm resistor is useless because shorted by the breadboard wires.

jfpoilpert - thanks. I intended for the 2 pairs of lines on each side to represent vcc and gnd. Do I need to label them as such? Also, can you further explain why the 280 Ohm is useless? I have pin 9 going to the vcc column and then a jumper going from vcc to the row containing the resistor?

Currently you don't use the Vcc line as Vcc sicne it is linked to pin 9 not to Vcc. Regarding the resistor, looking at your scheme it looks like it is wired on the same rail of the whiteboard. I you used a better tool for drawing your circuits (eg Fritzing) it would make it easier to read.

Your wiring diagram is a jumbled mess, and makes it impossible to figure out what's really going on.
My guess is that you have a mistake somewhere in your wiring.
Problems I see with your wiring diagram:

You show pin 9 from the Arduino wired to the positive rail of your breadboard. If the positive rail is connected to a 9V battery, this will likely destroy pin 9 of your Arduino.
You show the gate/base of your transistor wired to the positive rail of your breadboard. This would switch your transistor on constantly.
You show the symbol for a MOSFET transistor, but the label on it lists it as a 222A, which is an NPN BJT, not a MOSFET.
You don't show any wires connecting the left and right side rails of your breadboard.
You're using a row of your breadboard as the ground rather than the rails.

The picture you posted is too small to tell if your wiring diagram is wrong or if you actually connected things incorrectly, and the wire from your 9V battery is blocking the camera's view of key connections.
It looks like your wire from pin 9 is NOT connected to the power rail, but is instead connected to column 1 in your breadboard, which is good.
There are some strong conventions in wiring with breadboards and you should learn to follow them. The two pairs of columns of sockets on the left and right are for positive and negative supply voltage. Usually you wire them together and connect them to regulated power. Sometimes they will be used for different voltages, although you need to be really careful if you do this, since connecting to the wrong side can fry components.
It's confusing the way you've created your wiring diagram, but it looks like you have your flyback protection diode wired correctly, which is good. That's very important, as DC motors and other inductors create destructive reverse voltages as they are switched on and off, and without a flyback diode it can destroy solid state devices like ICs or even transistors.
You should re-wire your breadboard using the proper conventions, and post a corrected wiring diagram that really shows what's going on.
A picture where we can see all the wires and components clearly would also help.
Until you better learn what you are doing I would strongly advise against powering things directly from a 9V battery. When you do that, a mistake in wiring will fry your Arduino and/or any ICs you have on your breadboard.
Wire the 9V to the V-in pin on your Arduino, and then bring 5V and ground from the Arduino onto the +/- supply rails of the breadboard.
I also notice that in your code, you never set the state of controlPin in your setup method. You should add this line to your setup:
digitalWrite(controlPin, LOW);

That way the pin starts out in the OFF state, and then later on you can us an analogWrite to set it to the desired output level.

Awesome feedback! Thanks. I see how the diagram is incorrect now. I also understand how my unconventional breadboard wiring is confusing the issue. I'll clean that up. Currently, I'm supplying power to the right hand rails but not crossing it over to the left side, so I don't think I'll destroy pin 9, correct? I realize this layout is still wrong, but just verifying. Also re: MOSFET vs NPN BJT - I wasn't sure which icon to choose in Visio hence the label (I'll correct that too). Again, great feedback. Really appreciate the guidance.

Which kind of transistor are you using?

And what SW are you using to create your wiring diagrams? I use CircuitLab on the EE stack exchange (a web-based schematic editor) but haven't found a good one for use here. (I use Macs BTW)

You need to turn the transistor 180 degrees (assuming you are indeed p2n2222a).

Collector should go to the motor, Emitter should go to ground. In your photo you have those two swapped.
Also, I don't think the diode is the correct way around in that photo. That will just short out the battery, thought admittedly that would prevent the motor from spinning (-:

Swapping the emitter and collector would be unlikely to result in the transistor always being "on" (it would just make it perform poorly).  However, in a transistor package which does not put the base in the center ("pin circle" vs today's common "pin line") then it could indeed be an explanation.

@Gerben seems to be correct. I reversed the transistor and two things occurred 1.) when using 5V from the Arduino, I get much better performance. The motor starts spinning around a speed of 40 (vs ~200 previously) 2.) when using 9V the motor doesn't spin immediately. Only spins when I send a signal from pin 9. I also modified diagram and breadboard setup on the main post.

Actually, I take that back - the breakdown voltage when emitter and collector are accidentally swapped might be low enough for 9v to force it on.

Emitter - Base Breakdown Voltage is 6V. 9V power minus the voltage the motor uses (3v motor). Could be just enough. Or would the voltage at the Emitter be 9v when the transistor is off? Which would mean any voltage above 6v would make the transistor pass some current, though not much if the voltage is just above 6v? Funny thing; turning pin 9 HIGH might even turn the motor off :-).

source: Stack Exchange

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

sort: votes


text:
Two PIR sensors not working properly, help needed
I a just beginning with Arduino, I need some hellp here!!
I have added two PIR sensors to this circuit with an LCD.
Both PIR sensors are working fine and LCD is showing the correct PIR - only if a single PIR is active.
Problem-1. If the PIR1 and PIR2 gets active at the same time, and PIR1 goes off - it will still work as both PIRs are on, both LED will be on and buzzer will sound!!
In short when both sensors are active, Arduino cant sense which one went off later!!
Problem-2. second issue is the LCD is not displaying some text correctly.
If possible, it will be great if the system can display PIR1 status on line 1 and PIR2 status on line 2.
Can anyone help please to  fix the two problems and add the extra feature ?
Here is a Link of virtual circuit to see the sketch and connections.
Here is the code
#include <LiquidCrystal.h>

int ledPin = 13;                // choose the pin for the LED
int ledPinB = 12;               // choose the pin for the LED 2
int inputPin = 6;               // choose the input pin (for PIR sensor)
int inputPinB = 7;              // choose the input pin (for PIR sensor 2)
int pirState = LOW;             // we start, assuming no motion detected
int pirStateB = LOW;            // we start, assuming no motion detected PIR2
int val1 = 0;                  // variable for reading the pin status
int val2 = 0;                  // variable for reading the pin status
int pinSpeaker = 10;           // Set up a speaker on a PWM pin (digital 9, 10, or 11)

LiquidCrystal lcd(9, 8, 5, 4, 3, 2);

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(ledPinB, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input
  pinMode(inputPinB, INPUT);     // declare sensor as input
  pinMode(pinSpeaker, OUTPUT);
  Serial.begin(9600);

  lcd.setCursor(0, 0);           // Set LCD cursor position (column, row)
  lcd.print("Security");         // Print text to LCD
  lcd.setCursor(0, 1);           // Set LCD cursor position (column,row)
  lcd.print("System");           // Print text to LCD
  delay(1000);                   // wait 1s  Delay to read text
  lcd.clear();                   // clear LCD display
  lcd.setCursor(0, 0);           // Set LCD cursor position (column, row)
  lcd.print("System Booting");
  delay(1000);                   // Delay to read text
  lcd.clear();                   // Clear LCD
  lcd.setCursor(0, 0);
  lcd.print("Processing...");
  delay(1000);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Waiting For");
  lcd.setCursor(0, 1);
  lcd.print("Motion");
}

void loop(){
  val1 = digitalRead(inputPin);  // read input value
  val2 = digitalRead(inputPinB);  // read input value
  if (val1 == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // just turned on
      Serial.println("Motion detected!");
      lcd.clear() ;
      lcd.setCursor(0, 0);   // Set LCD cursor position (column 0, row 0)
      lcd.print("PIR 1 Active!!");
      // only want to print on the output change, not state
      pirState = HIGH;
    }
  }
  else if (val2 == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPinB, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirStateB == LOW) {
      // just turned on
      Serial.println("Motion detected!");
      lcd.clear() ;
      lcd.setCursor(0, 1);      // Set LCD cursor position (column 0, row 0)
      lcd.print("PIR 2 Active!!");
      // only want to print on the output change, not state
      pirStateB = HIGH;
    }
  }

  else {
      digitalWrite(ledPin, LOW); // turn LED OFF
      digitalWrite(ledPinB, LOW); // turn LED OFF
      playTone(0, 0);
      delay(300);
      if (pirState == HIGH){
      // just turned off
      Serial.println("Motion ended!");
      lcd.clear() ;
      lcd.setCursor(3, 0);
      lcd.print("Waiting For");
      lcd.setCursor(3, 1);
      lcd.print("Motion.");      // only want to print on the output change, not state
      // only want to print on the output change, not state
      pirState = LOW;
    }
  }
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;
    while (elapsed_time < duration) {
        digitalWrite(pinSpeaker,HIGH);
        delayMicroseconds(period / 2);
        digitalWrite(pinSpeaker, LOW);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
    }
}

Your problem is with the entire structure of your program. Pretty much everything is dependent on something else not having happened. Instead you need to make things more independent.
You should separate out your PIR sensor code into discrete chunks. One sensor isn't dependent on the other one having triggered or not, so there is no call to "link" them with an "else if". Also naming variables better will help understand the flow of code easier.
uint8_t savedStatePIR1 = LOW;
uint8_t savedStatePIR2 = LOW;

bool motionDetectedPIR1 = false;
bool motionDetectedPIR2 = false;

void loop() {
    uint8_t currentStatePIR1 = digitalRead(inputPinPIR1);
    uint8_t currentStatePIR2 = digitalRead(inputPinPIR2);
    bool haveChanged = false;

    if (currentStatePIR1 != savedStatePIR1) {
        savedStatePIR1 = currentStatePIR1);
        haveChaged = true;
        if (currentStatePIR1 == HIGH) { // Activated
            motionDetectedPIR1 = true;
        } else { // Deactivated
            motionDetectedPIR1 = false;
        }
    }

    // Exact duplicate with PIR1 changed to PIR2
    if (currentStatePIR2 != savedStatePIR2) {
        savedStatePIR2 = currentStatePIR2);
        haveChanged = true;
        if (currentStatePIR2 == HIGH) { // Activated
            motionDetectedPIR2 = true;
        } else { // Deactivated
            motionDetectedPIR2 = false;
        }
    }

    // Now, if either state changed this iteration through loop()
    // update the LEDs and the display, and play a tone if you
    // need to. Note that there is already a tone() function so
    // you really don't need to write your own.
    if (haveChanged) { // Something changed, so update things.
            digitalWrite(ledPin, motionDetectedPIR1);
            digitalWrite(ledPinB, motionDetectedPIR2);
            lcd.clear();

            if (motionDetectedPIR1 || motionDetectedPIR2) {
                tone(pinSpeaker, 300, 160);
                if (motionDetectedPIR1) {
                    lcd.setCursor(0, 0);
                    lcd.print("PIR 1 Active!!");
                }
                if (motionDetectedPIR2) {
                    lcd.setCursor(0, 1);
                    lcd.print("PIR 2 Active!!");
                }
            } else {
                lcd.setCursor(3, 0);
                lcd.print("Waiting For");
                lcd.setCursor(3, 1);
                lcd.print("Motion.");
            }
        }
    }
}

Note: this code isn't tested at all (it'll be full of errors). The basic principle, though, is:

First look for motion in PIR 1 and record if there is or not.
Repeat for the second PIR.
If there has been any change in state then (and only then) update the outputs.

Thanks for the reply, but I have no Idea were to paste this code!!

You don't paste code. You read code, learn how it works, then write your own.

OK, I will try .

,Tried it and failed, if you have time plz try to give me a full sketch. I will not be doing lots of Arduino project often, so it will not be that useful for me to learn Arduino in days...

You didn't try for very long did you?  Try harder.  You'll get it.  This isn't a place to get someone to write your code for you for free.

@Delta_G 1, I did tried atleast an hour on the script Majenko posted, but I don't know much about Arduino programming. It is not easy for me. Also, I have other things to do, time is precious and I will not be doing Arduino project in a daily basis in the future, so I think a copy paste will work me . ;-)
Please check the code I posted as an answer and tell me if there is anything wrong - it works, but I haven't tested it with a real Arduino.

So your time is too valuable to be spent trying to learn how to do what you want to do, but my time is just free to go debug your code for you while you put in almost no effort at all?  I think not.  Have a little bit of respect.

Thanks for the reply @Majenko, But as I said in the question, I am just a beginner. I couldn't figure out how to use it. I did change the pin number, but I dont know what is "haveChanged". So I did changed the code I already have and it seems to be working virtually. But it does take time to respond sometimes, may be in real world conditions, it will be better ?
Here is the link to virtual demo, please check and tell me if it is going to work.https://circuits.io/circuits/5142920-two-pir-project-1-0
Did spend some time, and made this code.
#include <LiquidCrystal.h>
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 5;

int NpirPin = 2;    //the digital pin connected to the PIR sensor's output
int SpirPin = 3;
int NledPin = 13;
int SledPin = 12;
int buzzerPin = 10;

LiquidCrystal lcd(9, 8, 7, 6, 5, 4);                          // initialize the library with the numbers of the interface pins

//SETUP
void setup(){
  Serial.begin(9600);
  pinMode(NpirPin, INPUT);
  pinMode(SpirPin, INPUT);
  pinMode(NledPin, OUTPUT);
  pinMode(SledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  digitalWrite(NpirPin, LOW);
  digitalWrite(SpirPin, LOW);
  digitalWrite(buzzerPin, LOW);
  lcd.begin(16, 2);
  lcd.setCursor(3, 0);
  lcd.print("Waiting For");
  lcd.setCursor(3, 1);
  lcd.print("Motion....");

  //give the sensor some time to calibrate
  Serial.print("calibrating sensors ");
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(500);
      }
    Serial.println(" done");
    Serial.println("SENSORS ACTIVE");
    delay(50);
  }
 ////////////////////////////
//LOOP
void loop(){

     if(digitalRead(NpirPin) == HIGH){
       digitalWrite(NledPin, HIGH);   //the led visualizes the sensors output pin state
       playTone(300, 300);
       delay(150);
         Serial.println("---");
         Serial.print("motion at NORTH");
        lcd.clear() ;
      lcd.setCursor(0, 0);                                           // Set LCD cursor position (column 0, row 0)
      lcd.print("PIR1 Active!");
         delay(500);
       }

     else if(digitalRead(NpirPin) == LOW){
       delay (300);
       digitalWrite(NledPin, LOW);
       digitalWrite(buzzerPin,LOW);}

     if(digitalRead(SpirPin) == HIGH){
       digitalWrite(SledPin, HIGH);   //the led visualizes the sensors output pin state
       playTone(300, 300);
       delay(150);
         Serial.println("---");
         Serial.print("motion at SOUTH");
        lcd.clear() ;
      lcd.setCursor(0, 0);                                           // Set LCD cursor position (column 0, row 0)
      lcd.print("PIR2 Active!");
         delay(150);
       }

     else if(digitalRead(SpirPin) == LOW){
       delay (300);
       digitalWrite(SledPin, LOW);
       digitalWrite(buzzerPin,LOW);}

}

// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;
    while (elapsed_time < duration) {
        digitalWrite(buzzerPin,HIGH);
        delayMicroseconds(period / 2);
        digitalWrite(buzzerPin, LOW);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
    }
}

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


text:
How does Arduino IDE 'Get Board Info'?
I want my C# application to automatically select the correct COM port by way of a string equality check against a 'GetInfo'-type request to the Arduino board.
I know the Arduino IDE can get info from the board;
Tools > GetBoardInfo

But I don't know how to get it using a sketch or if it is even possible for that matter.
Is this something that can be read from the board, or is it a USB-thing. If it's a USB thing, I'd have to get the info from GetUSBDevices.DeviceID or whatever, then get the serial port used by the USB Device, which would probably work, but I'd rather do it all via a serialPort.

I think you want the USB vendor and device IDs.  That is likly how operating-systems pick drivers for different USB devices.  But you may want more if you have several similar USB (for example FTDI chips) connected to the same operating-system/computer.  I assume that is why you are asking about the "Arduino board information"?

if you change the com port for a board in windows, it will persist, then you don't need to search

@LookAlterno I don't know, it's a question Arduino users seem to come across at some point. I'm not bothered if it gets closed, but I genuinely think it's a helpful question for Arduino users specifically, as it has good viewing numbers on here. At it's core, it's an Arduino question, even if the answer is more generalized. It's up to the com and any precedence though.

Looking at the source code of the Arduino IDE on github, it looks like they call an executable (listComPorts.exe). So I would guess you can't get that info through serial.
Here's a C# app using WMI that can get port, vid, and pid:
namespace PortTest
{
    class Program
    {
        // Helper function to handle regex search
        static string regex(string pattern, string text)
        {
            Regex re = new Regex(pattern);
            Match m = re.Match(text);
            if (m.Success)
            {
                return m.Value;
            }
            else
            {
                return null;
            }
        }

        static void Main(string[] args)
        {
            // Use WMI to get info
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"");

            // Search all serial ports
            foreach (ManagementObject queryObj in searcher.Get())
            {
                // Parse the data
                if (null != queryObj["Name"])
                {
                    Console.WriteLine("Port = " + regex(@"(\(COM\d+\))", queryObj["Name"].ToString()));
                }
                //PNPDeviceID = USB\VID_1A86&PID_7523\5&1A63D808&0&2
                if (null != queryObj["PNPDeviceID"])
                {
                    Console.WriteLine("VID = " + regex("VID_([0-9a-fA-F]+)", queryObj["PNPDeviceID"].ToString()));
                    Console.WriteLine("PID = " + regex("PID_([0-9a-fA-F]+)", queryObj["PNPDeviceID"].ToString()));
                }
            }
            Console.WriteLine("Done");
            int c = Console.Read();
        }
    }
}

From there, it looks like it searches an online database for more info. See: getBoardWithMatchingVidPidFromCloud() function.

IMHO Since Arduino IDE 1.6.8 listComPorts is no longer part of the arduino IDE

@jantje They may be using JNI now, but I'm guessing the underlying process is the same. Platform.java has 2 native functions resolveDeviceAttachedToNative and listSerialsNative but I can't find the source for them.

edit: I  misunderstood your comment. I think this is the code https://github.com/arduino/Arduino/blob/master/arduino-core/src/processing/app/Platform.java#L231 they are using resolveDeviceAttachedToNative

I have looked into this many times and it looks like it is this https://github.com/arduino/libserialport but then again it doesn't

Thanks Johnny; I was actually looking into using WMI to get the info, so it's nice to see it laid out just how I need it :)))) This will work on any version of windows, right?

@jantje If that's what they are using it uses lower level calls than WMI to get the data. Since Java's serial port handling is not very good, it would make sense to use that.

@n00dles It should. WMI has been around since Win2K.

Please look here https://todbot.com/blog/2012/03/02/listcomports-windows-command-line-tool-for-usb-to-serial/
The article is right about what you are seeking.
Thanks to @Johnny Mopp, searching "listComPorts" keyword helped me.
Quote from that article:

How it works
The C and the VBS versions both utilize the WMI
infrastructure that’s been around since Windows 2000 to query the
machine about its configured PnP devices. The WMI is a huge data
structure of just about any information in Windows. Except, it seems,
good information about COM ports. While there is a “Win32_SerialPort”
table in WMI, that only contains information about hardware serial
ports, not USB-to-serial adapters. Instead, these two tools look at
the “Win32_PnPEntity” table. While this table does list USB-to-serial
adapters, it does not contain a proper mapping of the adapter’s USB or
PnP ID to COM port. Instead, these tools do a string search on the
“Caption” field for the string “(COMn)” where “n” is a number. It’s an
incredible hack but seems to work.


text:
Ken Sherriff Arduino Version Tv-Be-Gone
I am trying to make Ken Sherriff's version of the TV-Be-Gone with the Arduino using the updated v1.2 software.  He uses this setup:
His Setup

My Setup
I used the Arduino Nano with same MCU (Atmel ATmega328) as Uno but changed a few other things also. For power I supplied 9v to the vin pin but supplied the transistor with 5v from the 5v pin. I used this Instructable by the same person.  The only major change was I used a PN2222A transistor instead of 2N4401.

Problem
My problem is that even though when I push the button the infrared light blinks for a while sending the different codes my receiver won't pick it up. I checked my receiver with other remotes and it works and I tried at close and far range. My receiver just blinks if it senses any infrared command regardless of what type of remote but it doesn't work with my Arduino TV-Be-Gone. I haven't tried it with a real TV yet but would like for it to work before I try it on a real one.


text:
WiFi module ESP8266 + Arduino Uno
I'm trying to connect a WiFi module, ESP8266-01 to an Arduino Uno. But, as I've understood, this module will only work with 3.3 V. Since all of the data pins use 5 V, one of the solutions is to use a voltage regulator, such as LM2596.
My questions are:

Does anyone know if there already exists a tutorial that describes the way this WiFi module can be connected to an Arduino Uno?
For a simple server, would I need to use several voltage regulators (since there are quite many pins)?
Since Rx is the receiver, it would not need a voltage regulator because that pin can handle up to 5 volts?
Is there any need for an external power source, such as a cell?

One example - replacing a voltage regulator, https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion

Does anyone know if there already exists a tutorial that describes the way this WiFi module can be connected to an Arduino Uno? - I Googled ESP8266 arduino and got over half a million hits, so yes, I believe you could find information about it.

Since all of the data pins use 5 V, one of the solutions is to use a voltage regulator, such as LM2596.

You do not want a voltage regulator you need a level shifter.
You can buy them cheaply or make them up with a transistor or MOSFET.
I gather the ESP8266 has a Tx (transmit) to the Arduino. You probably don't need to level-shift that, as the Arduino Uno will interpret 3V upwards as a HIGH. For the Rx (receive) from the Arduino you need to level-shift the data pin (possibly a voltage-divider might work) since the 5V from the Arduino needs to be converted down to 3.3V.
The ESP8266 Vcc and CH_PD can go to the Arduino 3.3V pin.
Disclaimer - I haven't done this, I am summarizing what I read on various web pages. Read some of the answers on the pages you get when you do a Google search for more details.

References

Voltage divider - Wikipedia
Level shifter - StackExchange
SparkFun Logic Level Converter - Bi-Directional
4-channel I2C-safe Bi-directional Logic Level Converter - Adafruit
Bi-directional level shifter for I²C-bus and other systems - PDF
ESP8266 Community Forum

Thank you for your answer! I have two more questions: Wouldn't it work to use the voltage regulator as described in https://www.youtube.com/watch?v=XdGFzLANsd4? Is it possible to output 3.3V using an analog pin (marked with ~)? The voltage regulator I was thinking to use is: http://www.kjell.com/sortiment/el/elektronik/arduino/moduler/lm2596-spanningsregulator-p87896.

He appears (for some strange reason) to be using a separate regulator to supply power to the ESP8266 - ignoring the fact that the Arduino has a 3.3V pin which does just that. He also connects Tx/Rx without any level shifting which is wrong. In particular, sending to the ESP8266 should be via a level shifter, or at least a voltage divider.

Check out the ESP-Link project over on Github. It has a pretty decent implementation of communicating with an Arduino via UART. As mentioned in another comment you will need a 5v-3.3v level shifter. But if you want to make things a little less messy you could just get a 3.3v Arduino mini for probably around the same price as the level shifter. Esp-link is built with the esp-open-sdk so you will have to spend some time setting up the toolchain if you haven't already.
I'm working on a project right now using a Moteino + ESP-12E and it's working great. However I'm planning on porting the RFM69 library and removing the Arduino portion completely. I would recommend doing the same if you can. The link below shows how to use the ESP with a port-expander (using SPI) so you can have more GPIO with the ESP.
https://github.com/MetalPhreak/ESP8266_MCP23S17

If you want a simplest solution, you can just connect your 5V pin of Arduino to the 3.3V external power supply. It will work just fine on 3.3V and all of its GPIO pins will be 3.3V too.
Warning: You must be careful because if you plug your Arduino to the USB wire, you will instantly get the 5V on all the pins, so you will burn your ESP. So you will have to disconnect ESP during programming.
The easiest (and safe) way for me in this scenario is to just use a standalone ATMEGA328P-PU chip on a breadboard and connect it manually. You just have to plug in 4 capacitors, a 16M oscillator and a resistor and upload sketch using a programmer (like USBasp) and "Upload using a programmer" button. You can then safely run everything on 3.3V because the programmer has a jumper and can work on 3.3V too and you don't have to use ANY level shifters and or voltage dividers. In my case they were not even working (I don't know why). You connect such "environment" once on a breadboard and you can safely work with it later. Let me know if you need more info on this.
Warning: If you work with SPI bus (MISO, MOSI, SCK), like an SD card reader for example, then you must secure the SPI lines of the device (card reader) with resistors, because you may also burn your chip if 2 opposite signals are directed to the same line by 2 separate devices. I've burned my 328P like this once.
Warning: Don't use a programmer for supplying power to your circuit. It can work for programming, but when your ESP starts connecting to WiFi it will require much more power than the programmer can provide! In best scenario it will just not work and hang up or reset.


text:
Simulate a FTDI using an Arduino UNO
I'm looking to directly program an ESP8266 WiFi Module with out using a FTDI (USB-Serial interface) as suggested in this excelent tutorial. The real purpose is to have access to the GPIO ports of the module.
I heard (from this page) that one can use an Arduino UNO as an intermediate interface for burning the bootloader onto an AVR (e.g. ATmega168 or ATmega328). That is, using the ArduinoISP code example in the IDE.
Is it possible to use an Arduino UNO as temporal bridge to program the ESP8266? Can anyone please suggest some tutorial? Thanks

I can't comment on the other answers, but I wonder if the 16U2 output are safe for the ESP, i.e. 3.3V levels?

The simplest way is to unplug the ATMega328P from the board (or otherwise disable it) and just use the ATMega16U2 by connecting the ESP8266 to pins 0 and 1 of the Uno.  No programming required at all then - the ESP8266 just takes the place of the ATMega328P.
If you really want to "pass it through" the ATMega328P then you will need to make a transparent pipe for the serial data.  That would involve nominating two more pins on the Uno to be a new serial connection, and using SoftwareSerial to interface with those pins.  Then you have a simple loop which reads from one port and writes to the other, and the same in reverse of course.  Make sure you have the baud rates right.  I don't know how well SoftwareSerial would perform at the (commonly) 115200 baud the ESP8266 works at.
EDIT: (Interfacing to a 3.3-V system)
Since the ESP8266 works at 3.3V, while the ATMEGA16U2 is powered at 5V, you might need to adapt the level of the ATMEGA16U2's TXD line (which is connected to the "RX" input line of the ATMEGA328P/Arduino Uno Board), to 3.3V.
To do this, connect a  1.5 kOhm resistor between the RX pin and ground. In fact, the connection between ATMEGA16U2 and ATMEGA328P is done using an 1kOhm series resistor. This, together with the 1.5k Ohm resistor, will create a resistor divider, which converts the 5V output to 3V.
See schematics below.


text:
Amforth on Arduino UNO
I'm having trouble with flashing amforth on my Arduino UNO.
I'm using an Arduino as ISP to write amforth.
Here's what I do:

Upload the code on the Arduino programmer and set Baudrate to 19200
Wire the Arduinos this way -> Wiring
Run avrdude -P /dev/ttyUSB* -c avrisp -b 19200 -p m328p -e -U flash:w:uno.hex:i -U eeprom:w:uno.eep.hex:i -U efuse:w:0x05:m -U hfuse:w:0xD9:m -U lfuse:w:0xFF:m

Sometimes it fails to set efuse,  but if I give the command just for it, even if it says "efuse changed, it was 5, not is 0xfd, do you want to change it back?" and I say no, I get the message with the correct fuses.
I log onto the amforth Arduino with the python shell, but my stack is constantly ??? -13 and different numbers. I found out -13 is error code for not found, but... not found what?
What does it mean? What am I missing?

I have to say that I'm new at this things, I recently studied Forth and discovered that I can use it on my Arduino, and I wanted to try.

By the way, the Arduino is not original.
 The chip is ATmega 328p
EDIT:
I downloaded amforth from here
Initially I followed [first guide] (different wiring but I've read around it's the same) and then "clarified my doubts" with another one from sparkfun.
(no link used because maximum for me is 2 links per post at the moment, I'll write it in the comments)

I tried with versions 6.1 and 6.0, then I decided to try with 5.9 (the one from the first guide) and now I'm running that (at least it allows me to pop elements from the stack).

update: everything seems to work fine, I just get error -13 when I print the stack content

The 0xfd part is easily explained. The extended fuse on that chip only uses the first 3 bits, and the rest read back as 1 for future compatibility. That is, not matter what you set them to, you get back 1s for 5 of the bits. ie. 11111xxx. So, 5 is 00000101 and reads back as 11111101 (0xFD).

Please edit your question to state where amforth comes from. That saves a search, and even if we search for it, we may find a different one to the one you are trying.

first guide second guide

I programmed by Uno using your first guide and it seems to work OK.
amforth 6.1 ATmega
8P Forthduino

For example, using the serial monitor, I entered:
6 7 * .

It printed:
42  ok
>

Then  entered the ASCII table example:
\ print a ascii table
: .ascii
base @
$7f $20 do
    i emit
    decimal  ." , dec: " i .
    hex      ." , hex: " i .
    8 base ! ." , oct: " i .
    2 base ! ." , bin: " i .
    cr
loop
base !
;

Then when I invoked it with ".ascii" it printed the table:
> .ascii
 , dec: 32 , hex: 20 , oct: 40 , bin: 100000
!, dec: 33 , hex: 21 , oct: 41 , bin: 100001
", dec: 34 , hex: 22 , oct: 42 , bin: 100010
#, dec: 35 , hex: 23 , oct: 43 , bin: 100011
$, dec: 36 , hex: 24 , oct: 44 , bin: 100100
%, dec: 37 , hex: 25 , oct: 45 , bin: 100101
&, dec: 38 , hex: 26 , oct: 46 , bin: 100110
', dec: 39 , hex: 27 , oct: 47 , bin: 100111
(, dec: 40 , hex: 28 , oct: 50 , bin: 101000
), dec: 41 , hex: 29 , oct: 51 , bin: 101001
*, dec: 42 , hex: 2A , oct: 52 , bin: 101010
+, dec: 43 , hex: 2B , oct: 53 , bin: 101011
,, dec: 44 , hex: 2C , oct: 54 , bin: 101100
-, dec: 45 , hex: 2D , oct: 55 , bin: 101101
., dec: 46 , hex: 2E , oct: 56 , bin: 101110
/, dec: 47 , hex: 2F , oct: 57 , bin: 101111
0, dec: 48 , hex: 30 , oct: 60 , bin: 110000
1, dec: 49 , hex: 31 , oct: 61 , bin: 110001
2, dec: 50 , hex: 32 , oct: 62 , bin: 110010
3, dec: 51 , hex: 33 , oct: 63 , bin: 110011
4, dec: 52 , hex: 34 , oct: 64 , bin: 110100
5, dec: 53 , hex: 35 , oct: 65 , bin: 110101
6, dec: 54 , hex: 36 , oct: 66 , bin: 110110
7, dec: 55 , hex: 37 , oct: 67 , bin: 110111
8, dec: 56 , hex: 38 , oct: 70 , bin: 111000
9, dec: 57 , hex: 39 , oct: 71 , bin: 111001
:, dec: 58 , hex: 3A , oct: 72 , bin: 111010
;, dec: 59 , hex: 3B , oct: 73 , bin: 111011
<, dec: 60 , hex: 3C , oct: 74 , bin: 111100
=, dec: 61 , hex: 3D , oct: 75 , bin: 111101
>, dec: 62 , hex: 3E , oct: 76 , bin: 111110
?, dec: 63 , hex: 3F , oct: 77 , bin: 111111
@, dec: 64 , hex: 40 , oct: 100 , bin: 1000000
A, dec: 65 , hex: 41 , oct: 101 , bin: 1000001
B, dec: 66 , hex: 42 , oct: 102 , bin: 1000010
C, dec: 67 , hex: 43 , oct: 103 , bin: 1000011
D, dec: 68 , hex: 44 , oct: 104 , bin: 1000100
E, dec: 69 , hex: 45 , oct: 105 , bin: 1000101
F, dec: 70 , hex: 46 , oct: 106 , bin: 1000110
G, dec: 71 , hex: 47 , oct: 107 , bin: 1000111
H, dec: 72 , hex: 48 , oct: 110 , bin: 1001000
I, dec: 73 , hex: 49 , oct: 111 , bin: 1001001
J, dec: 74 , hex: 4A , oct: 112 , bin: 1001010
K, dec: 75 , hex: 4B , oct: 113 , bin: 1001011
L, dec: 76 , hex: 4C , oct: 114 , bin: 1001100
M, dec: 77 , hex: 4D , oct: 115 , bin: 1001101
N, dec: 78 , hex: 4E , oct: 116 , bin: 1001110
O, dec: 79 , hex: 4F , oct: 117 , bin: 1001111
P, dec: 80 , hex: 50 , oct: 120 , bin: 1010000
Q, dec: 81 , hex: 51 , oct: 121 , bin: 1010001
R, dec: 82 , hex: 52 , oct: 122 , bin: 1010010
S, dec: 83 , hex: 53 , oct: 123 , bin: 1010011
T, dec: 84 , hex: 54 , oct: 124 , bin: 1010100
U, dec: 85 , hex: 55 , oct: 125 , bin: 1010101
V, dec: 86 , hex: 56 , oct: 126 , bin: 1010110
W, dec: 87 , hex: 57 , oct: 127 , bin: 1010111
X, dec: 88 , hex: 58 , oct: 130 , bin: 1011000
Y, dec: 89 , hex: 59 , oct: 131 , bin: 1011001
Z, dec: 90 , hex: 5A , oct: 132 , bin: 1011010
[, dec: 91 , hex: 5B , oct: 133 , bin: 1011011
\, dec: 92 , hex: 5C , oct: 134 , bin: 1011100
], dec: 93 , hex: 5D , oct: 135 , bin: 1011101
^, dec: 94 , hex: 5E , oct: 136 , bin: 1011110
_, dec: 95 , hex: 5F , oct: 137 , bin: 1011111
`, dec: 96 , hex: 60 , oct: 140 , bin: 1100000
a, dec: 97 , hex: 61 , oct: 141 , bin: 1100001
b, dec: 98 , hex: 62 , oct: 142 , bin: 1100010
c, dec: 99 , hex: 63 , oct: 143 , bin: 1100011
d, dec: 100 , hex: 64 , oct: 144 , bin: 1100100
e, dec: 101 , hex: 65 , oct: 145 , bin: 1100101
f, dec: 102 , hex: 66 , oct: 146 , bin: 1100110
g, dec: 103 , hex: 67 , oct: 147 , bin: 1100111
h, dec: 104 , hex: 68 , oct: 150 , bin: 1101000
i, dec: 105 , hex: 69 , oct: 151 , bin: 1101001
j, dec: 106 , hex: 6A , oct: 152 , bin: 1101010
k, dec: 107 , hex: 6B , oct: 153 , bin: 1101011
l, dec: 108 , hex: 6C , oct: 154 , bin: 1101100
m, dec: 109 , hex: 6D , oct: 155 , bin: 1101101
n, dec: 110 , hex: 6E , oct: 156 , bin: 1101110
o, dec: 111 , hex: 6F , oct: 157 , bin: 1101111
p, dec: 112 , hex: 70 , oct: 160 , bin: 1110000
q, dec: 113 , hex: 71 , oct: 161 , bin: 1110001
r, dec: 114 , hex: 72 , oct: 162 , bin: 1110010
s, dec: 115 , hex: 73 , oct: 163 , bin: 1110011
t, dec: 116 , hex: 74 , oct: 164 , bin: 1110100
u, dec: 117 , hex: 75 , oct: 165 , bin: 1110101
v, dec: 118 , hex: 76 , oct: 166 , bin: 1110110
w, dec: 119 , hex: 77 , oct: 167 , bin: 1110111
x, dec: 120 , hex: 78 , oct: 170 , bin: 1111000
y, dec: 121 , hex: 79 , oct: 171 , bin: 1111001
z, dec: 122 , hex: 7A , oct: 172 , bin: 1111010
{, dec: 123 , hex: 7B , oct: 173 , bin: 1111011
|, dec: 124 , hex: 7C , oct: 174 , bin: 1111100
}, dec: 125 , hex: 7D , oct: 175 , bin: 1111101
~, dec: 126 , hex: 7E , oct: 176 , bin: 1111110
 ok
>

I suspect your issue is you are not using it the way it is supposed to be used. Can you show the exact commands you type which cause the error?

(Edited to add)
After fairly extensive investigation of the source, I think that .s is not necessarily implemented for the Uno .hex file.
I found one suggested implementation here:
: .s  ( -- )\ stack picture listing order
depth
begin dup while dup pick . 1- repeat
drop
;

Running that it seems to work OK:
> 1 2 3 4 .s
1 2 3 4  ok

The .s word is implemented in the file dot-s.asm where you can see exactly how they did it (it's not the same as the Forth version above).

You mean Forth commands, right? I've tried pushing and popping things from stack. Using amforth 5.9 I pushed values to stack, and popping with .  was fine. I tried printing some strings and defining simple words, no problems. The problem is when I use .s to print the stack. That gives me the error. I haven't tried with other commands. Now I'm not near my computer, I hope that I can retry flashing 6.1 and do some other tests...

Yes, Forth commands/statements, whatever they are called.

Well, I told them in the previous comment lol. Tomorrow I can run some other tests (even if it's going to be hard, I'll be all day in university..), if not tomorrow, surely the day after. But I think that the problem is just .s . All the things I tried that do not involve printing stack worked fine.. By the way I did not use the serial monitor but the python shell shipped with amforth. The only edit I made to the script was to change /dev/amforth serial port parameter in a function to /dev/ttyUSB0 (the first did not exist, so I changed to the latter, that exists)

If you type "words" you get a list of words. ".s" is not amongst them. According to the documentation The default configuration includes most but not all words..

See amended reply - you can implement your own .s in Forth.

Wow, I've really missed the link between -13 and not found. I assumed that .s was sort of "the basic word" but thinking about it yeah, it's not really necessary. I tried that implementation of .s and works like a charm.
I have one more question: I noticed my previous words are saved permanently, is there a way to wipe the dictionary without rewriting the bootloader? The only thing that comes in my mind is the -e option for avrdude, but it erases the whole thing, am I right?

I was wondering that myself. It was rather cool that new words stay added to the dictionary, but I don't know how to remove them. For example I accidentally added 3 x .ascii before I realized. (Only when I typed words did I find out).

@NickGammon -- There is sometimes a "forget" command. And that also involves somehow marking where you want forget to go back to. But generally, I just make a mess of things with multiple definitions and all, keeping track of what I want to become permanent, add that to some kind of automatically loaded file, and hit reset.

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


text:
Serial.begin(): Why not always use 28800?
In a lot of the sample code online people add the line Serial.begin(9600) in the setup block.
When I look up what Serial.begin() is on the official documentation, it says that it controls the bit per second data transfer.
So the obvious question is, why not use 28800, the highest transfer rate? Why do people settle for 9600? What is the limitation here?

FYI the highest an arduino plugged into USB supports is actually 115200, and 57600 is often the second most common baud you see.

Why do people settle?

People settle because it is more than fast enough.  The most common use is just to print some stuff on a terminal for debuggin.  9600 baud is 960 characters per second, or 12 x 80 character lines per second.  How fast can you read? :)
If your program is using the serial port for bulk data transfer, you would choose not to settle.

What is the limitation...

The limits on serial are high.  Directly you can use 115200 baud in your programs and it will just work.  The Arduino terminal will allow a max of 115200, but other programs such as RealTerm would let you run higher.
Hardware serial will run to 1 M baud.  If you read around you will see people have used up to 1 M by directly controlling the UART.  You might get benefit of high baud rates for uses such as transmitting via a bluetooth chip.  If you are using the hardware serial interface to exchange from chip to chip with just a short distance, then 1 M baud is completely feasible.  Think of all the SPI and I2C devices that operate just fine at 1 MHz clock rate.
Over larger distances, you will start to have problems with noise when using logic level (plain 0 to 5V) signalling.  To use larger distances, you would add a transceiver to provide robust signalling, commonly RS-232 and less commonly RS-485.  With RS-232 you could run a mega bit at distances of 10's of feet.
The microprocessor clock speed will be the real limit.  With a hardware UART, the processor must load one byte to the UART every 10 bits (for N81).  So when you get to 1 M baud it will be a challenge for the 16 MHz processor to keep the UART supplied with data.  A new byte will be sent every 160 clock ticks, which is very few lines of code.  For a short burst of data, you might achieve that rate.  The message is, the processor will run out of speed before the UART is the limit.
Note, this all applies to HardwareSerial, software serial is very different.

Please note 2M is archivable with hw serial, but arduino's implementation seems too slow and send a lot of garbage. See atmega328p ds to find the magic bit to double your speed. Also add that 9800 baud is a very old standard, and a lot of sensors use that value as standard, even if can be configured for more, like xbee, gps, and more. Also serial over usb use auto-baudrate negotiation witch may override selected baudate, but i think is not used by arduino (but it may be on leonardo)

9600 8N1 is also a de-facto default setting. Many devices with a serial interface are delivered with this setting and need to be configured if another speed (or databits, parity bit, stop bit) is required.

"it is more than fast enough" - Good answer, but I somewhat disagree with this point. Most debug output implementations are blocking, so it is very desirable to make the debug output as fast as possible to prevent excessive changes in code execution time.

If you're doing bulk data transfer, Ideally you'd be using SPI, right?

In addition to all the interesting answers, it worth mentioning that setting the serial speed to XXX bits/s does not necessary imply XXX bits/s on the hardware.
Clocks -- even quartz based -- are imperfect and subject to drift. In addition, as the serial clock is usually generated through a power-of-two pre-divisor and (integer) counter, all value cannot be accurately obtained given a base clock frequency. With the help of the start/stop bits, asynchronous serial communication may be tolerant to some clock drift. But this has limits.
For example, if your ATmega328PA is running at 1MHz, you can achieve 9600b/s at 0.2% of error. But at 14400b/s the error is -3.5% (actually communicating at 13900b/s). And at 28800b/s, the error is +8.5% (actually communicating at 31200b/s). All those figures are from ATmega48PA-88PA-168PA-328PA datasheet, p200.
This is not an issue when two identical devices communicate together (as there are in fact communicating at the same speed). It might be an issue when communicating between different devices.
Increasing the base frequency does not necessary improve significantly the accuracy. For example, running the same ATmega328PA as above at 2MHz does not really give better results as those are mostly due to rounding errors. But running it 1.8432MHz give very accurate bps from 2400b/s up to 57.6kHz.

Also, the Arduino Uno does not use a quartz oscillator for the main microcontroller. This introduces an additional 0.5% error, at least for the second serial port (I am not sure about the first).

Back in the mists of time, the "gold standard" for remote keyboards (using a a telephone modem, and teletypes, if you remember those) was 9600 baud, initially achievable only over a dedicated phone line. Time moves on, slowly; technology advances, rapidly; and memory moves even more slowly than time (it seems). We can routinely communicate, at least over a several meters, at a couple of orders of magnitude faster than 9600 baud. What was once considered a gold standard is no longer gold, but still thought of as standard.
tl;dr: It's history, not technology.

I think it is a kind of tradition to use a transfer rate that is not the slowest one (300) but also not one that could eventually cause problems in some setups (28800 or even 115200). The PC serial port (most often a FTDI232 USB adapter) can cope with higher rates but your DIY hardware may not. So 9600 bps has established itself as some kind of standard transfer rate for code examples.

I think the main reason people use 9600 most of the time is that it's the default baud rate in the Arduino IDE. Also, faster data rates could also be unreliable if the serial signal has to travel a long way - although I have no idea why this was selected as an optimum speed.


text:
What is commonly done to stop a servo after reaching desired position?
When I started Arduino, I did not expect that everything must be contained in an infinite loop. I thought I could just write something like: motor start -> motor stop. But in actuality, what I get is motor start -> motor stop -> motor start -> ... forever and ever.
What is commonly done to stop a servo after it is in a desired position? Do I use servo.write(desired position) to keep it from turning? Do I detach the output wire?
What are some of the risks involved?

Could also be that you've got a continuous rotation servo, where 0 is full speed in one direction, 90 is stop, and 180 full speed in the other direction.

You do not "stop" a servo.
A servo is always running.  In a general sense, the servo is a control loop that takes as input a position target and applies force to hold at the requested target.  If you want the target to be maintained, then the servo must be running.
A servo motor contains electronics that are internally turning a DC motor on and off as necessary to hold the target position.  If the target does not match the current position, it turns on the motor to turn until the two match.  Once the output shaft reaches what you requested, the electronics inside the servo motor turn the motor "off".  Off meaning the DC motor is drawing little or no current.  The servo control loop is always running comparing the shaft position to a target.
If you powered off the entire servo motor, the position is not under control and could move.  For many applications if you unplugged the wires, the gears and motors apply enough friction that it would not turn.  But in general, you do not count on friction to make things work.
Do I use...Servo.Write(desired position) to keep it from turning?

Yes.  To tell a servo to stay at one position, you can just keep sending it the same target.
But you do not have to Write() again and again.  If you want, you can keep track of what the last setting was and apply only when you have a change.   For example, you can code like this:
if(position_target != position_last_set) {
  Servo.Write(position_target);
  position_last_set = position_target;
}

Regardless of your code, under the hood, Servo is constantly transmitting the position target to the servo motor.

A servo can use a considerable amount of current trying to hold position when a rotational load is applied to the output shaft.

A normal servo doesn't have a "go" function, it only has positional control. That is, whether you run servo.write(90) forever or once, the servo will go to 90 and continue to actively keep that position until you write another position. The only way to turn a servo  off is:
servo.detach();

For a normal DC motor, you will need to turn it on then off and then have kind of state tracking in the loop to never turn it on again, using a variable or millis() etc.
Of course, if you want something to only run once, put it in setup() (maybe within a loop in setup for simple tasks).
Also, you can simulate ending the program by entering an infinite loop with while(true){} or for(;;){}.

Yes, the problem seems to be with the misfit of the arduino loop paradigm with the application rather than anything specific to do with the servo - and the solution could indeed be preventing the arduino main loop from looping by putting another infinite loop to trap execution before the end of it.  Or, in a more complicated system, by watching for some external condition and performing a sequence of operations only once in response to that.

Feh, I don't see what's misfit about it. If you want it to stop you have options as above. And why bother with a microcontroller if you're just going to do one simple thing and stop? What does it do then? Run down the battery?

myservo.detach(); is what you are looking for. Moving it to a location than detaching. This is good when you want to use it to control a servo and not have it continue to take power like when using a battery.  Here is a example.
#include <Servo.h>
Servo myservo;  // create servo object to control a servo

void setup() {
  myservo.attach(9);
  // attaches the servo on pin 9 to the servo object
}

void loop() {
  myservo.attach(9);
  // attaches the servo on pin 9 to the servo object
  delay(15);
  myservo.write(1);
  // sets the servo position according to the scaled value
  delay(1000);
  // waits for it to get to the position
  myservo.detach();
  delay(1000);
  myservo.attach(9);
  // attaches the servo on pin 9 to the servo object
  delay(15);
  myservo.write(179);
  // sets the servo position according to the scaled value
  delay(1000); // waits for it to get to the position
  myservo.detach();
  delay(1000);

do you have to delay before detach? i haven't done that and never have problems with the servo reaching the position. thus im guessing once the servo pwm signal is sent it is sent and you can move on.

The word servo has a vague definition and can encompass many types of subcomponents. If you want no-power position holding using an electromagnetic motor, then there are four options:

High viscosity grease
Dash pot
Very high gear ratio
magnetic brake shoe / brake band

EDIT: There are some additional possibilities, but it's sort of an effect of some motor designs:

Permanent magnet pole holding torque, or detent torque
Permanent magnet drag torque

The high viscosity grease and dash pot have similar functions; providing a high static friction to resist motion, which then breaks away into movement. (A dash pot is essentially a toothed gear inside a toothed wall container, and which is permanently filled with a high viscosity fluid.)
However both of these will add to the motor load, and when they get hot they tend to become thin and runny and lose holding ability.

A high gear ratio increases the torque required to back-spin the motor. Though note, if any gearbox could have a perfectly frictionless lubricant, no amount of gear reduction could stop back-spinning.
So really this is similar to the thick grease and dash pot, but gear reduction allows just the normal thin lubrication to have enough static breakaway friction, to stop back-spinning.

A magnetic brake gives you active control over the static breakaway friction, and can allow for very high holding ability vs intermittent load spikes on the output shaft. Typically with the power off, a spring engages the brake to hold position with no power.
Note, there are two different kinds of braking: static position holding, and deceleration of a moving mechanism.
The second type both dumps heat into the brake pads and friction plate, and wears down the pads and friction plate. If the brake overheats, the pads usually disintegrate, and the brake now won't hold position.
Unless we're talking about large machinery, usually servo brakes are simple designs without replaceable parts. When the brake fails, you pull the whole thing off and replace it ... including possibly the entire servomotor and gearbox too.
For long service life with magnetic braking, you need to actively decelerate the load using the servo, and then once it has stopped moving, then engage the brake to just do the job of holding position.

Using a magnetic brake for no-power static load holding only, will look like this:

Power up motor, get current position, and begin actively holding position.
Energize brake to release it
Accelerate and move to new position
Decelerate motor and hold end position
Remove power from brake to engage it
Turn off power to motor

The motor is powered up and goes into position holding first, so that the load doesn't suddenly slip in either direction, in the instant between the brake being released and the servomotor then becoming active.

EDIT #1: For some permanent magnet motors, even with the power off there is a resistance to rotation because in certain positions, the magnets and the pole pieces more closely attract to each other, known as detent torque.
This pole positioning is like a low-energy valley and it takes a bit of force to overcome the magnetic attraction and move the rotor in either direction using an external torque.
You can feel this in some brushless fans and stepper motors, where if you rotate the shaft unpowered, it resists continuous motion, and there seem to be high resistance points that the rotor does not want to cross. When spun, the rotor rapidly slows, and may fall into a back-forth oscillation as it settles into one of the magnetic attractive wells.
This can be used to resist external torques without a brake, but making use if it requires stopping the rotor in one of the magnetic wells rather than a specific position you may want. But if combined with a gearbox, the exact specific stopping position may not matter too critically, and there may be a number of wells next to each other where the rotor can stop that provide an acceptable end-effector alignment.

EDIT #2: Permanent magnet drag torque is an effect of shorting all the power wires together. When this is done it takes considerably more force to rotate the shaft than with the stepper coil wires disconnected from each other.
This is because with the coil wires all connected together, when the rotor turns it acts as a generator and current flows through the coils. This current flow creates what is known as counter electromotive force (CEMF), which counters the magnetic field of the permanent magnet.
This CEMF can provide additional resistance against rotation when the servo is unpowered. Although CEMF won't prevent motion, it can help resist continued motion and provide instant deceleration when intermittent load spikes are applied that try to move the unpowered servo.

All of the above is also generally true for linear motor servos. Those don't have gear reduction, but the motion carriage can be lubed with thick grease, be equipped with a dash pot, and have position holding magnetic brakes.

I had the same problem.
I figured out that simply adding myservo.write(90); delay(4000); helps to stop motor.
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // twelve servo objects can be created on most boards

int pos =0;    // variable to store the servo position

void setup()
{

  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()

{
  myservo.write(180);
    delay(8000); ////stops motor for 8 seconds
  for(pos = 180; pos>=90; pos-=1)// goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15); // waits 15ms for the servo to reach the position

  }

    myservo.write(90);
    delay(4000); //stops motor for 4 seconds
  for(pos = 90; pos <= 180; pos +=1) // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);      // waits 15ms for the servo to reach the position

  }

}

i had the same problem i figure out that simply adding myservo.write(90);
delay(4000); //stops motor for 4 seconds   this helps to stops motor

This is a very brief explanation regarding servos.
The type of servo system that you are proposing is a none positional open loop system and is generaly used for accurate movement rate (controlled speed) . The loop in this case is usually a tachogenerator which sends a voltage (which is proportional to the motor speed) to a comparator which compares the tachogenerator voltage to the required adjustable voltage , the output of the comparator then regulates the motor speed, hence the required speed . this type of servo system will continue to run at the constant speed until  A the comparator signal is set to zero or B the motive power is reremoved from the moter ( switched off)   ----Point to point servo control , on the other hand ,, generally uses a position command which is verified with a signal from an encoder at which point the servo will stop until another command is issued from the stack ( EG. another position location or a dwell command (wait) or other )  the most common way to do this is to use gcode which has the ability to give full control of your servo system . If there is no encoding device then accurate servo position control is very difficult if not impossible.

A servo, by nature, is used to hold a position in the presence of disturbances trying to disturb that position. If you just need to move a mechanism that won't try to (or can't) back-drive the motor, your application ay be better served by a geared motor with a shaft encoder or position switches.

Hobby servos are mostly used because they are cheap and abstract out the problem and are not disturbed by typical loads.  Applications with forces that can backdrive the normal variety may be approaching overloading them anyway (some of the high performance servos have internals wguch  are more easily backdriven when off - even by the weight of control surfaces on large models).

@ChrisStratton: I know that the hobby servo can offer a block-box solution in a lot of cases, but my point is that a servo is always active, and if that is undesirable, as implied in the question, another technique may have an advantage.

No, a hobby servo is not always active - if it is not passively sitting in its deadband (comparator satisfied so motor off) or moving to a distinct new position, it has probably been misapplied.  Continued audible action means that either the servo is faulty (common in the $3 class), the linkage binding, or the load excessive.


text:
Difference between PWM and regular output port for servos?
I have been controlling my servomotors for a while now only using pin 0. After some research, it has became apparent to me that the ports with ~ are the PWM pins.
I thought that all pins sent out PWM signals, therefore the motor was able to move back and forth. Now I'm really confused as to how the motor was able to turn without using a ~ pin like pin 5.
Can someone explain why I should or should not use PWM signal when controlling a motor?

Servos does not use PWM, it uses PPM:

PWM = Pulse width modulation, The pulse start at 0ms, and is high for the percentage of the time compared to the percentage of the voltage you want, 5v signal, if you want 1v, the pulse is 20ms High and 80ms Low.
PPM = Pulse position modulation, The pulse length is always 5ms High and 95ms low, but the interesting part is if high starts after 5ms or 50ms (or any other).

So PWM is to lower voltage, PPM is a signal pulse.
This means that no matter what port you are using on the arduino you are able to control a servo since you only need High or Low, and not a lower voltage.
What you need to be aware of in this case is on the arduino is a PPM signal is using up a timer. The arduino has 3 timers where of 2 is available, one is used internally. Though there is code where you can attach up to 3 servos on the same internal timer.

Just 2 links describing this better than i did:

http://www.endurance-rc.com/ppmtut.php
http://forum.arduino.cc/index.php/topic,14146.0.html

PWM doesn't change voltage. It just changes the duty cycle. If you setup the timer correctly you might be able to have it do PPM (pulse position modulation). But you would only be able to control one serve per timer.

@Gerben sure PWM does not change voltage, but the effect of a 50% duty cycle of a 5v battery is roughly the same as just attaching a 2.5 volt battery, and to be exact you want to add a filter behind it to get the lowered voltage. But since i don't know my target audience i try to make it as basic as possible.

@Gerben Also edited wrong term, thanks for the correction.

-1. Your description of PWM vs PPM is correct, but you're wrong when you say servo control is PPM. It's PWM. Typically you'd vary the pulse width between 1ms and 2ms to control between fully left and fully right. See for instance this image.

@JorisGroosman Just fyi, it appears that servos and recievers (and flight controllers) comes in both PWM and PPM. so it appears we are both right.


text:
Serial.println(): Where is the text printed?
When I used Serial.println() in the code I naively believed I would see the characters that I sent displayed on that little black area just under the interface (just like a terminal).
#include <Servo.h>

int moveServo;

Servo myservo;

void setup()
{
  myservo.attach(0);
  Serial.println("      Hello Earth");
  Serial.println();
}

void loop() {
}

Can someone tell me just where Hello Earth would be displayed?

The IDE on your computer has a menu item under the tools menu called "Serial Monitor." On my Mac, at least, it is indeed a black area under the source editor for the current sketch.
It won't work unless you call the Serial.begin() function in your setup method before the first Serial.print()/println()/write() function call.
Something like this:
//Set up the serial port @ 9600 baud for display back to the computer
Serial.begin(9600);
delay(25);
Serial.println("Hello world!":);

You can open the serial console in the Arduino IDE by pressing ctrl-shift-M (as in Monitor) or selecting it in the menu.
Also, to use the serial interface, you have to initialize it using Serial.begin(9600); in setup() before calling any other function which writes to it. You can use any other baud rate - but this is the default in the Arduino IDE, if you change it, you should change it in the IDE too.


text:
Problems controlling servos using proximity sensor
I've just started using Arduino and I need to make a code to simulate the behavior of a lizard, meaning that if you come close to it, it moves away from you.
I'm using a "Arduino duemilanove" that my university lend me, I was told that it was an alternative version of Arduino Uno.
Both of the servos says "Tower Pro, mg996r, digihi-speed"
Looking different codes I made one which I think is correct. Also, I checked for each servo motor (I'm using two) and the proximity sensor running codes for everyone of them alone, if they worked well and they did but with this code, they supposed to move when you are closer than a meter but they don't stop spinning.
If anyone could help me with this, it would be great.
Here is the code:
#define Servo1 9
#define Servo2 11
#define trigPin 10
#define echoPin A0

#include <Servo.h>

Servo servo1;
Servo servo2;

int pos = 0;    // variable to store the servo position

void setup() {
  Serial.begin (9600);
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(Servo1, OUTPUT);
  pinMode(Servo2, OUTPUT);
  servo1.attach(9);
  servo2.attach(11);

}

void loop(){
  long duracion, distancia; // variables

  /* Hacer el disparo */
  digitalWrite(10, LOW);
  delayMicroseconds(2);
  digitalWrite(10, HIGH);  // Flanco ascendente
  delayMicroseconds(10);        // Duracion del pulso
  digitalWrite(10, LOW);  // Flanco descendente

  /* Recepcion del eco de respuesta */
  duracion = pulseIn(A0, HIGH);

  /* Calculo de la distancia efectiva */
  distancia = (duracion/2) / 29.1;

  if (distancia<100){
    for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
    {                                  // in steps of 1 degree
      servo1.write(pos);    // tell servo to go to position in variable 'pos'
      servo2.write(pos);
      delay(15);                       // waits 15ms for the servo to reach the                 position
    }
    for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
    {
      servo1.write(pos);              // tell servo to go to position in variable                 'pos'
      servo2.write(pos);
      delay(15);                       // waits 15ms for the servo to reach the position
    }

  }
  else{
  }
}

print distance to the serial port monitor and check it gets above 100

Your loops to move both servos last 179 x 2 x 15 ms = 5.4 seconds, which means every time distance is less than 1 meter, your servos will move during 5.4 seconds. Also note that pulseIn will return 0 if the sensor does not detect any obstacle within its range 5the range depends on the sensor you use, but it is typically 3 to 4 meters).

If your servos "keep spinning" then they have been modified from normal positioning mode to instead be continuous rotation.  That means that there's only a specific narrow PWM input width which will cause them to stop.  Typically it is adjustable with a potentiometer through a hole in the case.  Otherwise, change the value of your "stop" condition PWM output width in your code.

I am new to servos as well, but I do have two coding thoughts. The servos I have used in the past have started in the halfway position. That would mean the "pos" variable would start off trying to go from the starting 90 position to the 0 value in 15ms. Not enough time before the next for loop. I could see that causing some weird spinning while the servos try to get to the intended position. So..
int pos = 90; // Start servo position.

And secondly, the "distancia" could just always be less than 100. I would try finding a max distance value to compare to vs a hard coded value.
void loop() {...
long duracion, distancia; // variables
boolean isMoveTrigger = false; // Movement trigger.

/* Calculo de la distancia efectiva */
distancia = (duracion/2) / 29.1;

// Store a maximum value.
if (distancia > maxDistance) {
    maxDistance = distancia;
}

// Wait to get a starting maximum distance value.
if (countDown > 0) {
    countDown--;
} else {
    if (distancia > 0) {
      int distancePercentage = (maxDistance * 100) / distancia; // A 0-100 percentage of the maximum value.
      // Then trigger the movement when less than this percentage.
      isMoveTrigger = distancePercentage < 50;
    }
}
if (isMoveTrigger) {
    for(pos = 0; pos < 180; pos += 1) ...

As an extra tip, from my experience do not power the servos from the same power supply as the sensors. I built a similar project to you and it didn't work as expected. I then powered the servos directly from the battery (6v) and the sensors and arduino from a regulated 5v supply taken from the battery.
The servos can cause power spikes that mess with the sensor readings.


text:
Voltage Regulator getting too hot
I have an Arduino mega that is being used to control relays and ultrasonic sensors.  The relays that I am using is a 4 DPDT Signal Relay Module Model: D-256 Series and the other is a 4 channel Single pole Relay for Arduino. I am only using 3 channels of each relay. At any given time I only output to 2 channels from each relay at a time. I tested the relay to ensure they worked with the Arduino and they ran fine.
Once I connected the Ultrasonic sensors to the board as well, the board would not power and the voltage regulator got extremely hot. I would assume the total current draw was too high from the outputs and VCC of the Arduino.
I think that if I take my 9V battery and run it through a voltage regulator 7805 then I can run the VCC power of the relays with the battery instead of the VCC from the Arduino. This would result in me only running a VCC to the 4 ultrasonic sensors, the triggers for the ultrasonics from the Arduino, and the output signals fora maximum of 2 channels per relay board resulting in 4 relays. Most of the time it is only 2 relays.
Would I be able to power the relay boards VCC with the 9V running through a 5v regulator instead of the arduino so that I can reduce the current running through the Arduino?

yes, that will work as you think. you'd be better of with a buck regulator though. a lot better off...

What could be going on here apart from what @JRobert has suggested, is, LM7805 could be generating a lot of heat loss.
4 X Ultrasonic sensors (SR HC-04) would draw 60mA.
2 X Relays (SRD-05VDC-SL-C) would draw 71.4 X 2 i.e 142.8mA.(Depends on from where you signal it)
The Arduino mega would draw anywhere between 200 - 500 mA.(even more)
The amount loss you will have is (9-5)V * (202.8 + 250)mA
i.e. around 2 Watts. This is a lot of heat. I'm not even sure the LM7805 would be able to handle it.
Solution: use a switching regulator like the one mentioned here: https://electronics.stackexchange.com/questions/21131/efficient-low-power-regulation-i-e-9-5-volts

This is what I was thinking. The relays and sensors pulled in pulled too much current through the voltage regulator. My current setup that I have and it seemed to work was put a 9V battery that runs through a regulator to power the VCC of the relays. I also have a seperate battery pack that runs the Arduino. Now the only things that run out of the output terminals from the Arduino are the sensors and the output signals for the relays.By removing the VCC load from the Arduino, I am no longer overloading the voltage regulator on the board. It stayed cool while I was running yesterday

It sounds like a power-to-ground short circuit, either a fault in the Ultrasonic sensor or in the connection to the Arduino.
Check your connections, and if you have an Ohm-meter, check the resistance between the sensor's power and ground pins.
Current consumption is a function of the device being powered, not of the power-supply, unless the supply lacks the capacity to provide as much current as the device needs.
Note that 9v batteries (the small brick aka a "transistor battery") is not well suited to supplying much current and probably will not power your Mega, or not for long, anyway. They are much better suited for long-term powering of very low current devices, such as a smoke detector.

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


text:
ultrasonic phased array
I have the following code for Arduino mega to output 40 kHz square waves at the analog pins. I need to apply specific phase delays for the signals at each pin though and am struggling to find out how to do this. Any help would be appreciated.
Thanks!
byte TP = 0b10101010; // Every other port receives the inverted signal

void setup() {

DDRF = 0b11111111; // Set all analog ports to be outputs
DDRK = 0b11111111; // Set all analog ports to be outputs
// Initialize Timer1

noInterrupts(); // Disable interrupts

TCCR1A = 0;

TCCR1B = 0;

TCNT1 = 0;

OCR1A = 200; // Set compare register (16MHz / 200 = 80kHz square wave -> 40kHz full wave)

TCCR1B |= (1 << WGM12); // CTC mode

TCCR1B |= (1 << CS10); // Set prescaler to 1 ==> no prescaling

TIMSK1 |= (1 << OCIE1A); // Enable compare timer interrupt

interrupts(); // Enable interrupts

}

ISR(TIMER1_COMPA_vect) {

PORTF = TP; // Send the value of TP to the outputs
PORTK = TP;
TP = ~TP; // Invert TP for the next run

}

void loop() {

// Nothing left to do here :)

}

Do you need multiple pins with linear growing phase delay?

Hi Chris :) I need multiple pins with different phase delays.

I suspect that you can't do that. The square wave output on AVR-based Arduinos is pretty crude, and relies on interrupt-driven counters and dividers to generate the outputs. I doubt if the hardware has enough precision to manage outputs with different phases. You might need to use external signal generator hardware for this.

hi Duncan :) thanks for the response. I am outputting the signals to the analog pins though not the PWM.

What phase delays do you need? Are they constant or variable? Will the program eventually grow and have something in loop() Could you use different pins?

I will calculate the phase delays in MATLAB depending on the desired focal point and apply the phases in the arduino code accordingly. yes it could have something in loop!  I could use different pins. open to suggestions. I have not used arduino before so am new to it :)


text:
High Speed Thermocouple Readings
I'm currently attempting to take readings from 10 thermocouples using an Arduino Mega. I've been using MAX31850 1Wire Thermocouple Modules (with the Adafruit breakout) to perform the readings, but their response time has been very slow (~500ms each). I'm not sure if most of this latency is coming from the IC, or from the communications protocol, or perhaps even the DallasTemperature library.
For my application, I need to be able to read all 10 thermocouples in at most 250 ms (and faster would be better) and so I can afford up to 25ms per thermocouple. I would also like to be measuring with a precision of about 1-2 F.
I assume I will probably have to use a different amplifier, and I've seen recommendations online of using an external ADC to achieve higher speeds, which I would be happy to do, but I don't understand why that would make a substantial difference on speed since the onboard ADC can already sample at about 1/10 ms.
I would greatly appreciate any recommendations on how to achieve these speeds.

From Table 6 on page 22 of the data sheet for MAX31850 1Wire Thermocouple Modules, it appears that about 30 bytes of data are sent per reading (5 command bytes, 9 scratchpad data bytes, 2 x 8 module-id bytes).  At an apparent minimum of 60 μs per bit, those 30 bytes will take about 15 ms; at times of say 100 μs per bit, they would take about 24 ms.
Each reading also sends 3 each reset and presence-detect signals, adding up to a few milliseconds, and each reading requires a conversion time tCONV of typically 72 ms, per the last entry on page 4 in the Thermal Characteristics table.
Thus, it looks like the MAX31850 will take at least 87 ms per reading, if your units are all on the same 1Wire bus and you code things efficiently.  (Single units on a bus can use a slightly simpler protocol, which might reduce communication times to perhaps a third as much, but the typical tCONV would still dominate the time per reading.)
You might consider attaching an inexpensive Arduino Nano, Micro, or Mini to each of your MAX31850 units.  Each of those could communicate with its own MAX31850, allowing all the MAX31850s to convert simultaneously.  The small Arduinos could send results to the Mega by I2C or serial, in assigned time slots or upon request from the Mega.

That's an interesting idea. A pro mini would only cost $10, and I could probably get away with 1 for every two thermocouples.I'm not sure why the reading is taking so long. I'm also looking into the idea of trying to take the reading asynchronously.

1-wire transmission takes ~100us/1bit so 1ms/byte. so unless the adc is that slow, it shouldn't take you anywhere close to 500ms to take 1 reading, even if you factor in the overhead / reset.
there are dedicated chips but as you mentioned putting an amplifier (instrumentation amps for example) isn't that difficult. simpler with chips with built-in PGA + differential adc. My favorite here are some of the AVR chips (ATtiny85 or ATmega32U for example). But lots of Freescale / STM32F3 chips also work, so long as you are willing to dive into their and roll your own. Lots of fun.

Yeah, I was surprised by the latencies as well. I think that it's how long the module is taking to perform the reading, not the 1wire. Thanks

The onboard ADC of the Arduino Mega 2560 is only 10 bits. An external ADC in a thermocouple chip with a fast SPI interface is probably the best solution.
The Adafruit MAX31855 module seems to be able to do that.
The MAX31855 has a 14 bit ADC and a 5 MHZ SPI interface.
It needs a conversion time of 70ms. I think that is normal for these chips. I did not read the datasheet well enough how to get a value without waiting for it.

Thanks for the find. Reading asynchronously without waiting would also help a lot. I'll look into the libraries I'm using now to see if I can implement that idea. Thanks.


text:
Sainsmart Omron 12V optocoupled 2 channel relay problem
I know that there are plenty of questions related to relays, but I have to ask. I am trying to sort out the issue and spend hours reading but cannot make progress.
I have SainSmart 2-Channel 12V Relay Module for Arduino and wired it according to picture.

Arduino UNO R3 board is powered from 12V plug external power supply. I take that 12V to power JD-VCC on relay (from VIN). Arduino 5V is used to power optocoupler circuitry.
I want to use to power 12/24/220V devices (on picture I wired 6V battery for troubleshooting).
So, when I set PIN7 to LOW i would expect that fan spins up. LED on relay goes RED, so I expect it is sign that relay is activated. However, fan does not power on.
When I bring PIN7 to HIGH, I hear click; LED goes OFF. I assume it deactivated relay. All the time I have 6V on voltmeter.
What I am doing wrong?
I really tried to find answer around, but either I do not see or it is not so obvious.
Thank you,

Are the relays 12V or 5V?

So the fan never goes on?

It should be 12V, on relay is written G5LA-14 12V DC. No, the fan never goes ON.

I am trying to post image of relay, could not find option. First time user.
Now I have to go for few hours.

Did you disconnect the jumper between JD-VCC and VCC?

Yes, i removed jumper. The same behavior. I understood that JD-VCC connects 5V power source from Arduino to coil, so no external power needed.

Yes, i removed jumper. Instead I connected 12V. The same behavior. I understood that JD-VCC connects 5V power source from Arduino to coil. I tried various things for hours and hours. And cannot get it. On the other hand I have dumb 5V relay that works fine when inserted.
The problem is that I will have more power lines; 3.3/5V exclusuvely for Arduino and sensors (TTL & CMOS levels) no high currents. 12V mostly for some actuators and 220V for pumps, lightning. Using optocoupled relays I can isolate them all. At 12V I will have 4 x 900W modified server power supplies to drive actuators.

This is location where I read about JD-VCC and in general terms how to do it:
http://electronics.stackexchange.com/questions/18908/not-sure-how-to-
wire-my-5vdc-to-120vac-arduino-relay-board

Do you confirm you hear a click? If so, please detach the wiresfrom the 3-screws-connector and check continuity with and without the relay engaged, in order to understand which is the common. Then put the voltmeter at the fan terminals, and check the voltage. Check also the 12V voltage (it may drop when you try to engage the relay)

And sorry for the necroposting, did not realize it was a 2-years-old post ;)

Lets troubleshoot this circuit:

The circuit diagram you put in your question shows a wire creating a short across the relay coil. Check this, as this will definitely stop your fan from spinning. However, I assume this is an error in the diagram.
The picture on the website shows a jumper link between VCC and JD-VCC. Make sure this is removed.
Check that the fan works when you power it directly from the 6V battery. The fan may work only at a higher voltage or run off of AC voltage. Also, the battery could be flat - measure its voltage when it is under a small load.
Drive the input circuitry directly off of 5V. That is connect VCC to 5V and then directly connect IN1 to GND. Open circuit the IN1 input to turn it off. Check that this direct driving opens and closes the relay contacts.
Check the 12V supply. Does the voltage drop significantly when the relay pulls in or out? Does it have enough current? "Each [relay] needs 15-20mA Driver Current" Measure it using your DMM in ammeter mode.
Check your wiring is correct. It sounds simple, but you will be surprised by how many times the wiring is the cause of the problem.
Measure the resistance of the relay contacts in both the open and closed states. Arcing or poor manufacturing can be causes for the contacts to not function as intended.

Add a comment if there is something I have forgotten...

Remove the wire from the collector of your transistor and 12VDC, it should work fine.  It is possible you blown the opto coupler and transistor.

First of all the schematic is the one of the board, not one of his circuit, so it is just an error in the drawing, not on the circuit. Then if he did really short it the effect would be to blow (maybe) the transistor, not the optocoupler..

Looking at what I assume is the same module on the Sainsmart website it looks like the relays are 5V. That means the 12V you have pumped into them has made the Magic Smoke™ escape.
Throw them away, buy some new ones, and next time don't put in more than twice the voltage it needs.

I tried 5V using JD-VCC jumper, but did not work. Not sure whether I did hear clicks when releasing relay. Then I read somewhere that JD-VCC can be used to provide supply to relay and completely isolate coil form GPIO (maybe even here but in Raspy thread).   Which is exactly why I bought them, optocoupler. I checked relay module and it is OMRON G5LA-14 12 V. So, I connected it. I do not know how they can make 12V for coil from 5V i send from Arduino.   There is no credible user guide, so in a mean time I burned out brand new Mega 2560 for this. Such a pity.

Still, I am happy. I tried 12V, but I planned to manage 220V devices using these relays. When I saw that there is no plenty documentation I decided not to risk.

Ok, so if that module has 12V relays on it then it's not the same one I am looking at.  Is this the actual module? http://www.sainsmart.com/arduino/arduino-components/relays/omron-12v-2-channel-relay-opto-couple-for-arduino-uno-r3-raspberry-pi-arm.html If so then you have called it the wrong thing which caused confusion.

It is actualy this one.
http://www.sainsmart.com/arduino/arduino-components/omron-12v-2-channel-relay-opto-couple-for-arduino-uno-r3-raspberry-pi-arm.html

@politkom Ok, so I have helped you out and edited your question for you so it has the proper information in it.  You might want to look at the schematic - it is meaningless with that module since it doesn't tell us what the jumpers on that board are supposed to do. If you can't find the real schematic then I suggest you grab your digital multimeter and trace it through and draw the schematic yourself.

This is real schema downloaded from Sainsmart site. I just added external connections.

That schematic is the same one as used on the 5V modules, not the 12V modules. It is not correct for the 12V ones since it doesn't show the full circuit.


text:
Do ultrasonic sensors sense through transparent materials?
Do ultrasonic sensors sense through transparent materials?
In my case, I have to read if there's something inside a transparent acrylic bottle.

No, ultrasonic sensors will work only in gas environments (typically, in air atmosphere).

Only through materials which are transparent to ultrasound. I think rubber or polyurethane work. See for example the material that covers the reverse sensors in cars. @jfpoilpret I don't think they will work in e.g. helium gas.

The issue is not transparency to ultrasound (sound will travel within hard plastic for some distance quite well), but rather presenting the same impedance at the ultrasonic frequency as the intervening air does.  Since most solids do not, the majority of incident energy reflects off the discontinuity, and only a small amount transfers through.

I'm assuming you mean a "normal" sensor, like this:

Ultrasonic sensors work by sending out sound waves. Obviously, sound waves don't care whether a material is transparent or opaque, so they are blocked just as easily by acrylic as by a brick wall.
Side note: If you look on the front of an ultrasonic sensor, you will notice that it is covered by a screen, not glass or plastic. This is why.

Which means that it would sense through grids, meshes, nets or veils, and may even sense through thin but opaque fabrics. Fabrics can cause strange readings because they do not provide a solid enough block. Visible light opacity has nothing  to do with it.

Ultrasonic sensors detect echoes of high frequency sounds bouncing off of a boundary between  air and some other substance.
As others have pointed out, the light transmission properties of an object (transparency to light) has nothing to do with its transparency to ultrasonic sound waves.
It's possible to project ultrasonic sounds through solids or liquids, but that's not what these sensors are designed to do.
Trying to send ultrasonic pulses through an acrylic bottle will no doubt mess up the signals. Try pointing one of these sensors at an acrylic bottle in a controlled environment (fixed distance, mounted firmly and the same way each time, a solid back-stop at a fairly large, fixed distance behind the bottle to avoid varying echoes from behind the bottle) and check the distance measurement with the bottle full and empty. If you detect a difference in readings, then use those 2 different distance values for full and empty. (But make sure your production environment is the same as your test environment, including the area around and behind the bottle you're measuring)

Wanting to use HC-SR04 to measure water level, but protect the SR04 from moisture I tried covering with cling film, the most minimal film I could find. No - the sensor sees it and reports 1cm distance.  So these sensors have to be left exposed - probably won't last long at top of my water tank.

I'm unsure how useful answering a question (that has received multiple answers) from 2014 with something that's much more of a comment is. I think there are much more applicable sensors for this

Well, you can visualize babies in a womb using ultrasonic sensors. So why should it be a problem to "hear" inside a bottle? Maybe not with the sensors you can afford, and maybe not with an arduino, but basically it is possible, even if the bottle is not transparent.
if the bottle is open, and the content is liquid, a simple approach could be implementing a kind of ultrasonic range finder. This can be done with comparatively cheap hardware.

Ultrasonic sensors sense the reflection off an impedance discontinuity.  For the "in-air" type of sensor most likely being discussed, that would be the transition between air and a solid or liquid surface, and their receivers typically only report the first major reflection.  For a medical sensor, the sensor is coupled to the body with gel to improve the impedance match, and a much more sophisticated receiving system picks up partial reflections (at multiple depths, from multiple directions) off of density variation of tissues and fluid within the body.

@Chris Stratton: Sure! But the question was generally about "ultrasonic sensors", and not what's "most likely" used. Nevertheless my answer includes a solution for the "most likely" sensor, thus a downvote is not justified in my opinion. But... feel free!

I did not downvote your answer, though I do think it's main point remains a based on a lack of understanding.