1

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);
            }
        }
    }
}
1
  • 1
    Is a C adpted for arduino ! ;) Commented Nov 27, 2011 at 16:19

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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);
}
// ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.