The Arduino’s USB port is actually a serial port in disguise. To your computer it appears as a ‘virtual’ serial port. This is good news if you want to write custom code on your computer to talk with the Arduino, as talking to serial ports is a well-solved problem. (Unfortunately, so well-solved that there’s many ways of solving it.)

On the Arduino forum there’s been a few requests for some example C code of how to talk to Arduino. The nice thing about standard POSIX C code is that it works on every computer (Mac/Linux/PC) and doesn’t require any extra libraries (like what Java and Python need). The bad thing about C is that it can be pretty incomprehensible.

Here is arduino-serial.c, a command-line C program that shows how to send data to and receive data from an Arduino board. It attempts to be as simple as possible while being complete enough in the port configuration to let you send and receive arbitrary binary data, not just ASCII. It’s not a great example of C coding, but from it you should be able to glean enough tricks to write your own stuff.

Usage


laptop% gcc -o arduino-serial arduino-serial.c
laptop% ./arduino-serial
Usage: arduino-serial -p <serialport> [OPTIONS]

Options:
-h, --help Print this help message
-p, --port=serialport Serial port Arduino is on
-b, --baud=baudrate Baudrate (bps) of Arduino
-s, --send=data Send data to Arduino
-r, --receive Receive data from Arduino & print it out
-n --num=num Send a number as a single byte
-d --delay=millis Delay for specified milliseconds

Note: Order is important. Set '-b' before doing '-p'.
Used to make series of actions: '-d 2000 -s hello -d 100 -r'
means 'wait 2secs, send 'hello', wait 100msec, get reply'

Example Use

Send the single ASCII character “6″ to Arduino

laptop% ./arduino-serial -b 9600 -p /dev/tty.usbserial -s 6

This would cause the Arduino to blink 6 times if you’re using the serial_read_blink.pde sketch from Spooky Arduino.

Send the string “furby” to Arduino

laptop% ./arduino-serial -b 9600 -p /dev/cu.usbserial -s furby

Receive data from Arduino

laptop% ./arduino-serial -b 9600 -p /dev/cu.usbserial -r
read: 15 Hello world!

The output is what you would expect if you were running the serial_hello_world.pde sketch from Spooky Arduino.

Send ASCII string “get” to Arduino and receive result

laptop% ./arduino-serial -b 9600 -p /dev/cu.usbserial -s get -r
read: d=0

Internals

There are three interesting functions that show how to implement talking to serial ports in C:

  • int serialport_init(const char* serialport, int baud)
    — given a serial port name and a speed, return a file descriptor to the open serial port.
  • int serialport_write(int fd, const char* str)
    – write out a string on the given a serial port file descriptor
  • int serialport_read_until(int fd, char* buf, char until)
    – read from serial port into a buffer until a given character is received

You can and should write improved versions of the read and write functions that better match your application.

Update 8 Dec 2006:
Justin McBride sent in a patch because it turns out Linux’s termios.h doesn’t define B14400 & B28800. I’ve updated arduino-serial.c to include the patch, but commented out for now. No one uses those baudrates much anyway. :) If you need them, uncomment the additions out, or better yet, download Justin’s tarball that includes the changes and a Makefile to auto-detect your platform.

Update 26 Dec 2007:
Added ability to sent binary bytes with the ‘-n’ flag.
Added a delay option so you can open a port, wait a bit, then send data. This is useful when using an Arduino Diecimila which resets on serial port open.

105 Responses to “Arduino-serial: C code to talk to Arduino”

Obviously you could also use “screen” to communicate with the Arduino (or any serial device) using the following command:

screen /dev/cu.usbserial 9600

screen is bidirectional, so you can send and receive data.

Yup, totally.

I’ve only ever used screen in interactive sessions. I’m not sure how one would go about routing screen to a proram or sending binary (non-ASCII) data that is present in many Arduino designs.

I haven’t tried it, but there’s probably some way to have the “expect” command interact with screen as a simple way to get data back and forth from the Arduino in a semi-automated way. However, this is going down the territory of “many ways to solve the same problem” territory Tod mentioned.

If you do want to do this using a dynamic language, the ruby/serialport library makes it really easy in Ruby. I just put up some video and instructions for a hello world.

Todbot — Thanks for all your great posts on Arduino (especially the Spooky Arduino series), I’m in the process of learning this stuff with a little study group of other absolute beginners and they’re been totally indespensible. Keep up the great work!

Thanks, I’m glad people are finding the Spooky Arduino stuff useful. It was a blast to work on.

And, wow, Ruby can do serial ports now? That’s awesome. Okay I gotta try this out….[follows your link, watches the rad movie, looks a bit more, then 2 minutes later] Yup, works like a charm. I did:

% wget http://rubyforge.org/frs/download.php/72/ruby-serialport-0.6.tar.gz
% tar xvzf ruby-serialport-0.6.tar.gz
% cd ruby-serialport-0.6
% ruby extconf.rb
% make
% sudo make install
% emacs light.rb
% ruby light.rb

With Ruby and its friendliness towards Ajax websites and the ability to do serial ports, I can imagine some really interesting “Web2.0″-type websites that interact with the real world via Arduino.

Very useful code, thanks!

However, I’ve found that -under FC6-, sometimes the seriaport_read_until returns a error 11 (resource temporarilly unavailable) in the read() call. I think it is not a problem with the software -obviously- since a “cat

I’m trying to get the hello world program to work I’ve downloaded the modifed Justin Mcbride file (I’m using linux) compiled and ran
./arduino-serial -b 9600 -p /dev/ttyUSB0 -r

the output is then read
read:

My port is on ttyUSB0 any clues?

After some experimentation it does return hello world I just need to catch it at the right time.

Hi Todbot,

Great site, I’m loving all the Arduino content. I’m new to Arduino and I’m trying to understand a few things. In the ruby example at ComputerKraft, they have 2 files – the sketch that’s written in Processing and the light.rb file. Do you need to write a sketch in Processing when you want to use ruby? Is it possible to write a ruby script that does what the Processing sketch does? I would like to be able to just write the code once in Ruby. And last, but not least, can you do an Arduino – Ruby example as you did with C?

Thanks for all the great content!

Jose

Hi Jose,
I’m not familiar with the Ruby example at ComputerKraft so I can’t speak to it. However, you don’t need Processing for Arduino or Ruby. Processing is just one way of writing programs (in this case, Java programs) that can talk to serial ports and thus Arduino. Because Processing is so easy to use and it shares the same style GUI as the Arduino programmer, it is a common tool for showing how you can interface Arduino with a computer.

Perhaps what the ComputerKraft example is doing is creating a Processing sketch that receives network requests then forwards them on to Arduino. The Ruby program then just connects to a network socket and doesn’t need to have serial port drivers.

In the example at ComputerKraft there’s an Arduino sketch, not Processing – sorry… that receives serial requests. In essence, it is nothing more than a case function that when selected turns on the corresponding LED. The Ruby program basically takes input from the user, parses it and forwards it over to the Arduino sketch via serial.

What I’m trying to understand is this: In order to use Ruby or any other language to speak to Arduino via serial, do I need to have an Arduino sketch already running in Arduino expecting serial requests?

minicom is another great way to read/write to the arduino. I have the USB model and just set my minicom serial port to /dev/ttyUSB0. Works great in Fedora Core 6.

[...] Here is arduino-serial.c, a command-line C program that shows how to send data to and receive data from an Arduino board. It attempts to be as simple as possible while being complete enough in the port configuration to let you send and receive arbitrary binary data, not just ASCII. It’s not a great example of C coding, but from it you should be able to glean enough tricks to write your own stuff.” – Link. [...]

Hi everybody,

I am introducing in this new world called Arduino, here is my problem:

I have my arduino working and I can receive data from it using:

tail -f /dev/ttyUSB0 >> “file.txt”

After trying with the arduino_serial.c, I was not sucesfull, I guess I have the same problem that Peter had.

Using “tail” would be enough for me since I only want to receive data from it. But when I say to arduino to work at baudrates higher than 9600. “tail” is not giving the right data (Strange symbols).

My question is do you know how to set the baudrate in order to use “tail” with higher baudrates?

Anyidea will be wellcome!

Hi Javi,

To change the baudrate of serial ports, you use the “stty” command before your tail.

If you see the “roomba-tilt.pl” program on the Roomba Tilt project, you’ll see a complete invocation of stty that allows full bidirectional binary transmission.

But if all you need to do is change the speed, then:

% stty -F /dev/ttyUSB0 57600

is all you need to change the baudrate to 57600 bps.

hi there,
i’m sorry if you cover this elsewhere, but i am just getting started in trying to program in C for the avr… do you have any recommendations on resources? just looking start with a simple blinkie code so i can figure it all out. i would really appreciate it. thank you!

Hi Leah,
One of the easiest ways to get into C AVR programming is the Arduino site itself: the Tutorials, Reference, Hacking, and Playground sections are chock full of good intro material.

If you’re interested in plain vanilla AVR programming without the thin veneer of Arduino, one of the best books out there to get started is the “C Programming for Microcontrollers” available from SmileyMicros.com. It’s based around the Atmel AVR Butterly board, a tiny $20 demo board that’s a lot of fun to play with.

Once you get a bit familiar with AVR C, you’ll want to bookmark the AVR Libc page. Libc is the collection of C libraries that is the “standard” set of libraries containing all the functions you’re used to in C. In the case of AVR Libc, it’s also the libraries that help you interact with the on-chip hardware.

I can’t get open() to work, it keeps telling me the file does not exist. I can open the serial stream just fine with ’screen’ from the terminal, but this damn open() just returns an error. Any ideas?

That’s really odd. What’s the exact invocation you’re using and the exact error messages you’re seeing? If this is Linux, I’d say it’s a permission problem with the serial port device file and screen gets around it by being setuid root.

its Mac OsX Tiger, under the terminal.

I managed to access properly from my c code by using sudo

sudo ln -s /dev/tty.usbserial-* /dev/tty.arduino

although I havent read exactly what that does but im using the alias to access it and it works.

my original serial path was /dev/tty.usbserial-A10?16fZ

I’m guessing my c code just hated that ? mark.

That’s very strange. I’ve never seen a USB-to-serial driver create a virtual serial port that wasn’t just alphanumeric. Creating a symlink to a more reasonable name like you did is probably the best solution.

Aside: A symlink (“symbolic link”) is the unix way of doing aliases. The “ln -s” command creates symlinks. The “sudo” command lets you “do” things that normally a “su”per user (admin user) can only do. Creating symlink in the /dev directory is one of those things.

Again, it’s very strange to have a question-mark in the serial port name. Are you running the latest serial drivers that come with Arduino? Has anyone on the Arduino forums had a similar problem?

how would I got about upgrading the serial drivers?

Download the latest version of the Arduino software. Inside there is a directory called “drivers” containing driver installers.

ah, this is a new installation already… so maybe a way to change my arduino’s serial number?

I think /dev/tty.usbserial-A10?16fZ works from the command line beacuse bash interprets ? as a wildcard (whereas C doesn’t), so the ? is a typo (kinda like how /dev/tty.usbserial-A10*16fZ works)

Hi Tod great site. I’m new with arduino and C.
I need that the programm send binary not ascii e..g -s 65 = a and not 65. How can I change the arduino-serial.c ?
Thanks sorry for my english I hop you understand my Question
Klaus Germany Berlin

Hi Klaus,
To send the byte value 65 instead of the character ‘a’ (ascii 65), you need to do an ascii-to-integer conversion. There’s a function called “atoi()” in C that does this. There’s a more general function called “strtol()” (“string to long”) that will even parse decimal, hex, and other number formats.

I’ve updated the arduino-serial.c program above to do this with a new option ‘-n ‘.

To use it you would do something like this:

% arduino-serial -b 19200 -p /dev/USBS0 -d 2000 -n 65 -r

This will open up serial port “/dev/USBS0″ at 19200 bps, wait for 2 seconds, then send the number 65 and read back any response terminated by a newline.

Hi Tod, that’s great – I’m so thankfull! I use it to write on an LCd Screen (4 lines 40 Col) and so I can send the bytes to control it.
best wishes and an hapy new year
Klaus

[...] was looking at this link on the todbot blog. It is a utility C program that sends some serial data to your Arduino. I [...]

I am trying to write a c program that logs the data from the serial port then saves it to a file.

I have been having some trouble reading the data from the port. The port seems to be set up correctly( I get a 3 back) but when I try a read I get a -1.

Arduino monitor and cutecom can read the arduino just fine.

thanks

Ok I got some output by removing the O_NDELAY from the open.
The problem now is the data seems to be garbage.

Any thoughts?

Thanks

I don’t think removing O_NDELAY on serial port open() will affect your issues. But it will probably make it so some of your reads() never time out (I’ve not checked this with serial ports)

Does the arduino-serial.c program read data correctly for you? (it will print to the stdout, but it’s easy to change that to print to a file)

The fact that you’re reading garbage means either you’re at the wrong baudrate, wrong number of stopbits, or you’re not checking the return value from read() to see how many bytes were actually read.

Arduino features an FTDI chip to do serial communication with an USB host, but of course this limits us to use the FTDI driver, and thus forces us to install drivers and limits us to our own software. Since the USB spec does not allow bulk endpoints for low speed devices, it’s always possible that a new version of e.g. Windows does not allow them.

Here’s a Python version of arduino-serial.c:
http://lemonodor.com/archives/2008/02/arduino_serial.html

I have succeeded in my project to use Diecimila
with SimpleMessageSystem & linux, via shell scripts.
Run this now: ‘wget http://207.14.167.161/SMS1.tgz‘
It only works when my system is booted, so keep trying. Finally got the right data format from readAD-1: Comma-separated values. This imports to OpenOffice calc easily, for further analysis or graphing. Try it.

A little off topic, as this is more of a c question.

I am Very new to all of this, so please pardon what is probably a stupid question;

In your C code, you are parsing out the options sent to the app with a while statement.

Why do you have a ‘while(1) { }’ Isn’t that true by default?

and, how is this able to parse all options?

any illumination on this is greatly appreciated….

Thanks!

Christopher Lund

Hi Christopher,
Your questions aren’t stupid. In fact they get some of the less clear aspects of how people typically write C code.

The while(1){ } block is used to wrap the call to getopt_long(). Each time that function is called, it parses another chunk of the command line argument string. So the while(1){ } says “keep parsing forever”. But there is a if (opt==-1) break; that will break out of that while loop if there are no more arguments to parse.

Structuring the code this way is a way you’ll see some simple C programs written where it implies that program’s functionality is simple and controlled entirely via command-line arguments. That is, the style of the source code implies the intended use of the program. You’ll find this kind of philosophy in a lot of C code. There’s so many ways to do the same thing in C that people adopt “idioms” in how they code to hint at what they’re trying to do. I just copied it from some other code I had. :)

Another common idiom for loops which are either “infinite” or broken out of in the middle is “for(;;) { … }”. This has the advantage of having the control conditions be explicitly empty – you don’t have to look twice to check if the “1″ is a lower case letter L, for example.

This works great in Fedora Core 6.

How would implement this in Visual Studio .NET 2005 ?
The POSIX libraries are not supported.

Hi Jason, Sorry, no clue, I don’t use Windows; I thought that it had the POSIX libraries. I seem to recall seeing a Visual Basic serial port library a while back, perhaps generally usable in .NET. Try googling around for “VB serial library” or similar.

hi there
will all this things work with geexbox too?
can i implement a package to the geexbox iso to get it working?

Hey Todd. Im basically trying to read my arduino from my /dev/ttyUSB0 (which works fine with screen). I found out that it exits in the serialport_read_until() with -1 (can’t read). I find this a bit strange since my arduino is just spamming the serial, so there should be something. Any ideas? (btw the baudrate is right so its not that.)

Hi harohase,
I’m not familiar with geexbox, but it looks like Linux, so I don’t see why you couldn’t make an arduino-serial package for it.

Hi Casper,
I must admit the serialport_read_until() function is the least polished part of arduino-serial. So there might be a logic problem.

However, if you’re using an Arduino Diecimila or similar newer Arduino, you may be trying to read while the board is in reset, since on Mac OS X & Linux, opening the serial port resets the Arduino.

To deal with this, insert at least a 2-second delay before reading. Here’s an example that inserts a 5-second delay between opening the open and reading:

% ./arduino-serial -b 9600 -p /dev/ttyUSB0 -d 5000 -r

Hi everybody !

I have a strange problem.
The program is working when I have just upload the program to the arduino (with the arduino software), it’s working working very well.

But If I reboot, I try to configure the TTYUSO with this :
stty -F /dev/ttyUSB0 cs8 9600 ignbrk -brkint -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

I try to launch the program : not working :/

I launch screen : screen /dev/ttyUSB0 9600

I stop screen, launch the program : it’s working.

What’s wrong with my configuration ??

Hi Batoub,
What is the exact arduino-serial command you’re using? Are you trying to read data? If so, be sure to have at least a 2-second delay (see my previous comment) to deal with the Arduino’s reset.

It may be that screen is opening the serial port but not closing it, so by the time arduino-serial is used, it’s past the reset delay.

hi todbot
very great program :) thanx alot. i’ve wrote a little bash script for reading some strings from arduino a starting some progs… every thing works fine. the only problem is, that “top” shows a big cpu capacity… has you or somebody an idea?

here is the script:
http://de.wikiants.org/Arduino-serial#Bash_Script_.7C_Kommunikation_mit_Linux

Hi Pat,

That’s a great page, a better writeup than this one I think. :)

I think the reason why you’re seeing a lot of CPU usage for your script is that it’s spawning and killing processes as fast as possible, which is a fairly big task for an OS. Also, each time you run the arduino-serial program, it opens & closes the serial port (another potential heavyweight operation) which has the effect of resetting the newer Arduinos that have auto-upload circuitry.

You’ll probably have better luck for your application by either incorporating the arduno-serial code into another C program that does the logic your script does, or to use a scripting language like Python or Perl, which has both serial support and is a good scripting language. See some of the above comments for how to do ‘arduino-serial’ in Python.

Hello Todbot.

Oddly, whenever I send things using -s it seems to reset my Arduino board. It works fine, however, when I have serial monitor mode enabled in Arduino IDE. When I have this enabled /bin/stty’s output changes as well, leading me to think arduino-serial is not setting some things, or there are problems with using it in OS X…

With serial monitor enabled:
speed 9600 baud;
lflags: -icanon -isig -iexten -echo
iflags: -icrnl -ixon -ixany -imaxbel -brkint inpck
oflags: -opost -onlcr -oxtabs
cflags: cs8 -parenb -hupcl clocal
min time
0 20

Without:
lflags: -icanon -isig -iexten -echo
iflags: -icrnl -ixon -ixany -imaxbel -brkint
oflags: -opost -onlcr -oxtabs
cflags: cs8 -parenb

Exact command used:
./arduino-serial -p /dev/tty.usbserial-A6004pba -n 6

Hi rutro,
By design, the current Arduino’s will reset when the serial port is opened. See the “Automatic (Software) Reset” section of the Arduino Deicimila description. If you don’t want this automatic reset feature, you’ll have to hack your Arduino a bit. There’s some discussion in the forums on how to remove serial port reset.

And normally one shouldn’t open up a serial port with more than one application. The results can be undefined.

This is the sort of thing i have been looking for but i want to be able to read key presses in real time so i can use key presses to control the arduino.

Is there any way of doing this at all that anyone knows of?

Hi

Can i use the –send-data to load an arduino sketch into the device without using the arduino GUI?

Ben

Hi Ben,
No, you can’t. The bootloader protocol used to load sketches is pretty complex. Arduino actually uses the “avrdude” program to handle it. But you can load sketches from the command-line. Search around the Arduino forums and check out this page for how to do it:
http://www.arduino.cc/en/Hacking/CommandLine

My shell script package (mentioned above 2/12/08) has grown to include GUI scripts for IO & PWM control using Xdialog. It is also available 24/7 now, via ‘wget http://user.cavenet.com/rolandl/SMS1.tgz
Please check it out, it’s a good source for fixing scripting problems as mentioned above.

Well I can say that this topic has been round and round, but I learned alot from all of it. Getting back to the communication part however, I have come up with a way to communicate bi-directional with any SW language via an Arduino log file as the output and the command line Arduino-serial as the input. Using the command “tail -f /dev/ttyUSB0 >> ArduinoLogFile” you can generate any output you desire from the command “serial.println()” into a log file. Using whatever SW you want you can call command-line Arduino-serial commands to send one char codes that the Arduino can respond to in any fashion you desire, including Arduino Log file entries.

I know I have not outlined this clearly and with examples, but I just got it all working and thought I would share it. It is a hack, but it is the quickest way I could get the 2-way communication without writing much code. You can even create shares to the directories where the data is and share it over the network. It is a simple concept, but fairly powerful with little effort.

If I get more time I will create an entire write up to publish.

A big thanks!!!!!!!! to all you hackers that provided the base of information and code for me to accomplish this method.

Ok!, I got the time to document the Arduino Communcation through files, as described one post above. If anybody is interested, check out this webpage http://mrdoall.dnsalias.com/wiki/index.php/Arduino_Communications

Great little bit of code! I was unable to tail/screen the /dev/tty.usb* to see any of the data otherwise. Not sure why.

Is this code under any sort of BSD/CC license? I’d like to post a modification I made so it will read forever (or until ^C) and do stuff. Writing the instructable now. Just wanna know if I can reuse this. :)

Hi ayman,
Use the code however you like. No real license. I would like a link back if you publish it on the web. :)

Cool! You can check out the instructable (with your modified code) here:

http://www.instructables.com/id/Mac_OS_Foot_Switch_from_a_Guitar_Amp_Pedal

I added a -R flag to read forever and a little bit to exec applescripts based on what it reads.

Thanks again for the great code sample.

I wrote up a quick diff to clean up how nonstandard Bxxxxx macros are used — with this diff you can compile on any platform without having to edit the source, and all the baudrates supported by your platform will be supported by arduino-serial.

htttp://web.hexapodia.org/~adi/arduino/fix-arduino-serial-baudrates.diff

Thanks Andy! That really cleans up that section. I’ve patched the arduino-serial.c file so others can easily use it.

[...] the VonHippel module, a simple c program compiled for the arm, BUG can talk to the Arduino (in the picture, the USB cable and USB to serial [...]

Awesome! Thanks for this, will prove very useful.

I’m having trouble with it though. Using your example, I upload serial_read_blink.pde to the board and then use the command “./arduino-serial -b 9600 -p dev/tty.usbserial-A9003ZlI -d 1100 -s 6″

This is just the command you gave with an added pause as I have an Arduino Diecimila. The LED blinks as soon as I send the command, and then again at the end of the command (after 1.1 seconds I assume). There are no 6 blinks.

Any idea what the problem might be?

Hi Chris,

What you’re seeing is that when arduino-serial opens the port, it resets the Arduino, which causes a small flash on the pin13 LED, then arduino-serial sends the string (“6″ in this case), and then before the Arduino can fully response, arduino-serial exits, closing the port which causes the Arduino to reset again.

The solution to this is to add another “-d” delay after you send the string, so you can watch the Arduino do its thing:
./arduino-serial -b 9600 -p /dev/tty.usbserial -d 1100 -s 6 -d 2000

The auto-reset feature of the Diecimila is great, but on Mac OS X & Linux, opening & closing the port always resets it.

Thanks for the reply, but that doesn’t help. It just takes longer between the opening and closing flash of the LED.

Any other ideas?

hmm, that’s odd because the addition of the trailing delay does work for me. I assume you can get it to blink as you would expect when using the Arduino Serial Monitor?

The other thing to try is to increase the first delay a bit, say to 2000.

Ahh great, thanks alot. Seems the minimum pause I can get mine to respond after is 1500, a bit more than the Arduino site’s recomended one second, oh well not too bad.

Thanks very much!

hi there,
i’m sorry if you cover this elsewhere, but i am just getting started in trying to program in C for the avr… do you have any recommendations on resources? just looking start with a simple blinkie code so i can figure it all out. i would really appreciate it. thank you!

The easiest is probably to get an Arduino. Its “language” is really C for AVR.

Hi Todbot,

I am not new to Arduino, though I have some cobwebs to sjake off as it’s been over a year since we made a self-playing LP record player together. (sampled portions of record using 2 servos and simple pulley system, VERY COOL!)

Anyways, I am a senior engineering student and for my senior design project I want to communicate data from a C++ program into Arduino and use the data to have Arduino control some hardware. Have you done anything like this? Any ideas how I could do this?

Thanks in advance!
:)
p.s. keep up the great site!!

Hi Nick,
You can use C code from within C++, so you should be able to take any C serial port code (like the arduino-serial stuff above) and use it in your C++ program that talks to Arduino.

How would implement this in Visual Studio .NET 2005 ?
The POSIX libraries are not supported.

I am confused how to use the code at the top. Such as sending Furby or 6 to Arduino.

to send 6 it gave this (code?)

laptop% ./arduino-serial -b 9600 -p /dev/tty.usbserial -s 6

Would I want to write that into my C++ program word for word? I did this and was thrown errors, so not sure how to modify or use it. Thanks again for the help!

You would copy the functions in the arduino-serial source code into your C++ source file and call them from within the C++ file. But really what you should probably do, since you’re writing your own C++ code, is to Google around for “C++ serial port communication” for more native examples on how to communicate with serial ports with C++.

Hello again todbot,

So I was making progress, or so I thought, because I was using windows xp installed on a Mac. This allowed me to use the termios.h etc. that was unavailable for windows. I tried to go back on my windows machine and it threw the same erorr:

termios.h: No such file or directory.

with a couple others(related). Any idea how (if?) I can somehow import this or get around it? thanks again very much

Hi Nick,
Oh, you’re on Windows? Low-level things like serial ports are dealt with in very different ways than Unix-based OSs like Linux & Mac OS X. Most people doing serial port stuff on Windows use either Visual Basic (or .NET) or Java with the RXTX serial library. You’d likely be better off not using any of my ‘arduino-serial’ code above, as it assumes a Unix-like environment. Do a Google search for “windows serial port library” and you’ll find lots of tips.

There are ways of getting full POSIX library support in Windows, but I think it’s complex to do if you’re not used to it.

Just so people know, I was able to get this working under windows with just a little bit of playing around. The only real catch is you have to get the full POSIX support from somewhere. Cygwin is free and what I used, and in the end all you have to do is throw a single dll into the folder that your program is in, and it works just fine. I don’t have the source file that compiles fine as I ended up merging it with another program (very messy) but it works fine. Do NOT give up, keep trying and it should fall into place.

Can i use the –send-data to load an arduino sketch into the device without using the arduino GUI?

hello, I have a problem with the sensor sht. My question is worth the program sht75 applied to sht15?
thanks

Hi kazalar,
Not really, but the Arduino guys have info on how to program the Arduino from the command-line. See here:
http://arduino.cc/en/Hacking/CommandLine

Tom Morgan AND Todbot:

I downloaded Cygwin but I do not understand what you did to get the dll file in that folder. Step by step maybe?

I am on this path again because I worked for a long time using other methods for windows which were unsuccessful but this code above works fine in posix machines

Todd,

The mailman just brought my new Duemilanove, and my first download was “blink”, of course.

I was looking for something else to try quick, and found your serial_read_blink.

I just used hyperterm. After seeing “Blink!”

I tried changing:
Serial.println(“blink!”);
to Serial.println(i); to see it count up, then
Serial.println(val-i) to see it count down.

Thanks for these examples!

Hi,

I use the following command in linux to read my arduino board.
“cat < /dev/ttyUSB0″
and
“cat filename” to capture the output to a file.

Regards Stan

Hello,

i have this in my .pde (with Arduino) and send this to my microcontroler :


void loop()
{
if (Serial.available() > 0) {
intervalid = Serial.read();
if (intervalid==2) {
intervaldiffuse=Serial.read();
intervaldiffuse=(intervaldiffuse-3)*60;
}
if (intervalid==1) {
intervalstop=Serial.read();
intervalstop=(intervalstop-3)*60;
}
}

if (value == LOW) {
if (millis() – previousMillis > intervalstop) {
previousMillis = millis();
value = HIGH;
}
}
if (value == HIGH) {
if (millis() – previousMillis > intervaldiffuse) {
previousMillis = millis();
value = LOW;
}
}
digitalWrite(ledPin, value);
}

So, sending something like this with Terminal (MacOSX) :
arduino-serial -b 9600 -p /dev/tty.usbserial-A6004nYe -n 2 -n 30 n 1 -n 10
should change the blink of the LED.
But i need to send this command three times to see its effect.
the ‘n 1′ is used for ‘if (intervalid==1)’ and the ‘n 2′ for ‘if (intervalid==2)’
Any idea about my problem ?
Thanx a lot for your job.
++

Jack

Hi I tried the bash script with tail and redirected it to the logging.csv file so I could make a arduino data logger…
Be forwarned I found the scripts by searching “/dev/ttyUSB0 arduino” the problem is…

I told arduino to count and output it to the serial port at 115200 bps…
then told the bash script to open the serial port at 115200 bps.
then listen to one line of the count and print to the csv file… loop…

It was missing the same ammount of numbers from the count I think the number was around 20.

Any ideas? I hope the c program can work ok…
Any idea on how to open 2 arduinos and log from both of them?

Hi Jack,
I’m not quite sure what you mean by the “n 1″ and “n 2″ are in the above line (do you mean “-n 1″ & “-n 2″?), but I think you might need to add a 3-5 second delay, like:

% ./arduino-serial -b 9600 -p /dev/tty.usbserial -d 5000 ...

This is because opening the serial port to Arduino causes the Arduino to reset and then you have to wait for the bootloader to time out.

Hi Josh,
I’m not sure what your shell script is or what the sketch is on your Arduino, so I can’t really help debug your problem. But doing things via the shell isn’t that speedy, and 115200 is pretty speedy.

Hi your code compiled on GCC no problem no warnings etc. Now I will try editing it to just read from 2 arduino’s I have plugged into my laptops 2 serial ports. Then I will try the same thing with a powered hub afterwards.

This will be at 115200 bits per second.

Has anyone you know of tried 2 com ports open at once or more?
Any problems you know of I should be aware of?

I am working on a data logger the analog and 24 bit analog to digital converter stuff and arduino is coming together nicely.

I am really interested in Decomposition of EMG signals using arduino’s to shovel data from 4 emg channels to a .csv comma seperated value file or straight to a mysql database for a open source design of this system.

More channels will be made but 4 is as many as the arduino can shovel so that is why I am testing 2 arduino’s with my data logging setup.

Hi josh,
Have you tried this yet and are having problems, or are you just curious how to go about it? If the latter, then the main thing to look at is the “fd” variable. This is the “file descriptor” of the serial port and is returned by the open() function. It is unique for each serial port opened. And all subsequent functions take an “fd”. So if you take care to keep your “fd”s straight, it should work just fine.

If you’re running out of pins on your Arduino, I’d recommend picking up an Arduino MEGA. It has tonnes more pins than a regular Arduino.

Thanks I will try to keep the arduino’s USB0, USB1… streight I will be trying it very soon. I just want to pass my schematics on for checking to the open eeg mailing list then work on that.

./arduino-serial -b 9600 -p /dev/ttyUSB0 -r
is what I try I am using ubuntu and a Boarduino made by adafruit with a 3.. avr.
read: ? is what I get in return I am realy confused.
I tried
./arduino-serial -b 9600 -p /dev/ttyUSB0 -d 2000-r
and it worked

int ledPin = 13; // select the pin for the LED
int i=0; // simple counter to show we’re doing something

void setup() {
pinMode(ledPin,OUTPUT); // declare the LED’s pin as output
Serial.begin(115200); // connect to the serial port
}

void loop () {
Serial.print(i++);
Serial.println(” I”); // print out a hello
digitalWrite(ledPin, HIGH);
delayMicroseconds(500);
digitalWrite(ledPin, LOW);
delayMicroseconds(500);
if (i > 255){i=0;}
}
seems to do some kind of buffer over flow it turns off /dev/ttyUSB0 and does not let me back in until I restart.
the directory disapears for my script & arduino ide.

things seem to run right 1 time then the port disappears could it not be closing?

void loop () {
Serial.println(i++);

delayMicroseconds(1137);
if (i > 99){i=0;}
}

this runs in arduino ide but the c code causes the port to disapear after 1 run.

What do you mean by this exactly?
Do you mean causes the /dev/ttyUSB0 device to disappear from the “/dev/” directory?
Or do you mean the device is still present, but it cannot be opened?
Or do you mean the serial port on the Arduino becomes unavailable to the running sketch?

I have a feeling you are running into buffering issues of either the FTDI chip on the Arduino or the Linux device driver.

Normally when you’re transmitting so much data at such a high speed, you use the hardware flow control lines so you can pace your transmitting so as not to overflow any buffers. I don’t think the Arduino Serial class gives you access to those lines (or even runs them to the Arduino MCU)

One way to test if this is an Arduino or PC problem is to have two PCs or two Arduinos, and connect them together, sending data from one and receivin on the other.

I think their is a relationship with the arduino program being on using that com port.
Also I still have the 1 second light on 1 second light off delay. So I think as that decreses the buffer or lack of buffer in my c program causes problems. I herd somewhere the arduino has a print f buffer in its c code. If that fills up maby that is the problem.

I have just gotten two arduino’s not two pc’s so maby i can make them talk at eatchother. …

the serial logger you have does not output to a text file using >>.
I have this in my command line logger is the binary output. ./logger>> test.csv is their any way I can make that work? I am using ubuntu.
Will I have to write more c to open a real file or create one and fprintf to it?

I have tried your program also it does not print help to the text file ether.

Logger? I’m not sure to what you’re referring. The “arduino-serial” program isn’t a data logger. It’s not really designed to be run for long durations, just to quickly get a chunk of data from an Arduino and exit.

However, “arduino-serial” does emit its output on stdout, so it’s output can be redirected to a file as you have done.

What is this “logger” program you’re running? It’s very clearly not arduino-serial.

Hi todbot,
Thx for your answer : put a 5000 ms delay is the solution !
++

Jack

Hi todbot,
I’m using your code and everything seems to work fine except when reading back a response. It seems to only echo back the input as a response.
I type-
$arduino-serial -b 9600 -p /dev/ttyUSB0 -s ra -d 2000 -r
where ra should read back a pin value and does through serial monitor and cutecom. I’ve tried the delay in various places and no delay at all. Any idea why it would only echo back the input?

Hi Tyler,
Try putting the delay before the send. You need to wait for the Arduino to start up before sending it data. Like this:

arduino-serial -b 9600 -p /dev/ttyUSB0 -d 5000 -s ra -r

I increased the delay in case you have an older Arduino.

If that doesn’t work, then I’d need to know what the sketch is like you’re running on the Arduino before being able to help more. For instance, depending on how your sketch is set up, you might need to add a delay between sending and receiving because your PC is often faster with serial than the Arduino:

arduino-serial -b 9600 -p /dev/ttyUSB0 -d 5000 -s ra -d 200 -r

That inserts a 200msec delay between sending and receiving.

[...] original arduino-serial.c – by Tod E. Kurt. [...]

Something to say?