Question completely rewritten
Trying to assess an Arduino project feasibility. New to Arduino... but did a lot of controller programming (assembly), Roboteq (C) and Phidgets (C++) , using various kinds of motors and sensors ; and reading the Arduino documentation makes me feel confident interfacing and programming shouldn't be an issue.
However, before investing time (and some money) in the project, I thought it'd be better to ask here if Arduino is the right choice, considering
- a non-latching Hall sensor is to be connected to Analog 0,
analogRead()
to return a [0,1023] value, used as a proximity sensor. This should be straight forward.
Question →
- while the Arduino runs my program, and is still connected to the PC (USB), is it possible to synchronously or asynchronously send commands from the PC to the Arduino. I.e. can the Arduino poll if there is something coming from USB (synchronous), or is there a way for the PC via USB to have Arduino do something (asynchronously)?
Thank you.
1 Answer 1
It's perfectly doable. As Chris Stratton puts it, it's all about implementing non-blocking serial communication:
- whenever you receive a character, you store it in a buffer
- whenever you have a complete command in the buffer, you process it and reset the buffer
For a line-oriented protocol, it may look something like:
/* Process incoming characters if any. */
while (Serial.available()) {
static char buffer[BUF_LENGTH]; // incoming command
static int length = 0; // command length
int data = Serial.read();
if (data == '\r') { // complete command
buffer[length] = '0円'; // terminate the string
if (length)
exec_command(buffer); // process
length = 0; // reset buffer
}
else if (length < BUF_LENGTH - 1)
buffer[length++] = data; // buffer incoming character
}
For a more complete example, you may want to take a look at this simple Arduino command line interpreter. You connect a terminal emulator to the Arduino at 9600/8N1, type the "help" command and it displays:
mode <pin> <mode>: pinMode()
read <pin>: digitalRead()
aread <pin>: analogRead()
write <pin> <value>: digitalWrite()
awrite <pin> <value>: analogWrite()
echo <value>: set echo off (0) or on (1)
You can use it as a template, replace existing commands or add new ones
(the interpreter is just a long if ... else if ...
) and – since
it's all non-blocking – add whatever you want to loop()
.
millis()
insteaddelay()
or else doing multiple stuff at the same time won't work or be buggy. With that, you would be able to ask more specific questions.