FredVaz
FredVaz

Reputation: 533

How can send bytes for arduino?

I have developed an app that sends a String/command by socket to another PC app server and that sends a String to an Arduino via the Serial port.

The problem is: how can I send bytes to Arduino?

The C# of the app server that sends the String via the serial port:

using System;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.IO.Ports;

public class senddata
{
    private void Form1_Load(object sender, System.EventArgs e)
    {
        // Define a Porta Serial

        serialPort1.PortName = textBox2.Text;
        serialPort1.BaudRate = 9600;
        serialPort1.Open();
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        serialPort1.Write("1");  // 1 is a String     
    }
} 

The C++ code running on the Arduino:

#include <Servo.h>

Servo servo;
int pos;

void setup()
{
    servo.attach(9);
    Serial.begin(9600);
    pinMode(13, OUTPUT);
}

void loop()
{
    if (Serial.available()) {
        int msg = Serial.read();

       if (msg > 0) {
           servo.write(msg); // 10 = pos 1 10-9 = 1
    }
  }
}

To try to understand the problem better I changed the code to this (however, because the value of the servo goes from 0 to 180, this doesn't work):

#include <Servo.h>

Servo servo;
int pos;

void setup()
{
    servo.attach(9);
    Serial.begin(9600);
    pinMode(13, OUTPUT);
}

void loop()
{
    if (Serial.available()) {
        int cmd = Serial.read();

        if (cmd > 0) {
            // If I send a 1 the LED stays ON...
            // but when a send 12 the LED doesn't stay OFF.
            if (cmd == '1') {
                digitalWrite(13,HIGH);
            }

            if (cmd == '12') {
                digitalWrite(13,LOW);
            }
        }
    }
}

Upvotes: 1

Views: 3202

Answers (2)

Matthew Murdoch
Matthew Murdoch

Reputation: 31493

You should be able to use your original Arduino code, but change the C# code to this:

// ...   
private void button1_Click(object sender, System.EventArgs e)
{
    SendByte(1); // Send byte '1' to the Arduino
}

private void SendByte(byte byteToSend) {
    byte[] bytes = new byte[] { byteToSend };
    serialPort1.Write(bytes, 0, bytes.Length);
}
// ...

Upvotes: 1

luketorjussen
luketorjussen

Reputation: 3264

You want to convert the value of a string into an integer in C. So use the atoi function.

Upvotes: 2

Related Questions