I have been trying to get the value of a few sensors on C# from Arduino and pass a value from C# to arduino for a motor. That is
Sensors---> Arduino ----> C#
&
C#---> Arduino --- > Motor
I am able to do these two things individually, but not together. The reason being that the serial is able to hold only one set of data at a time. Is there a solution to it, or will it be that I will have to use one arduino for sending and one arduino for receiving the data. Please help me through this situation.
It is possible, there are even several ways to do it.
The simplest one, if you don’t care about reaction time of the LED (that is, you don’t mind if it switches on or off with a 30ms delay), is to intertwine your reads and your writes. This works, because Arduino has a small buffer for the serial communication, so you don’t have to receive all the characters immediately. Consider this example:
void loop() {
Serial.print(analogRead(0));
Serial.print(",");
Serial.print(analogRead(1));
Serial.println();
delay(30);
while (Serial.available()) {
switch (Serial.read()) {
case ‘0’: digitalWrite(led, LOW); break;
case ‘1’: digitalWrite(led, HIGH); break;
}
}
}
Here, we check for new bytes in the serial stream every 30ms, and if there are any in the buffer, we act on them. Of course, if a byte gets sent just after we just checked, the next check is in 30ms, so we can have a delay. To decrease that delay, you can wait only, say, 1ms, and do the analog read not on every cycle of the loop, but instead every 30 cycles.
Another way to regulate Another way to regulate communication between two nodes is to define a protocol. A protocol defines how communication works to as much detail as you need. For this example one node is your Arduino and the other is your PC.
This protocol is a master-slave protocol, with the PC being the master. This just means that the PC regulates all communication and the Arduino only responds when requested.
The PC’s part of the protocol allows it to set the value of the led and to query the Arduino for the sensor value. All commands are terminated by a newline.
The Arduino’s part is merely to return the sensor value when requested; all responses are terminated by a newline.
Commands (typed into the serial connection):
led=on
The Arduino will turn the led on when seeing this command
led=off
The Arduino will turn the led off when seeing this command
sensor?
The Arduino will respond with the value of the sensor and then go back to listening for further commands.
This is just a trivial protocol. Often protocols have error checking and acknowledgement responses. I would suggest that you google something like Arduino protocols or internet protocols to get more information.