Class: PiWire::Serial

Inherits:
Object
  • Object
show all
Defined in:
lib/pi_wire/serial.rb,
ext/pi_wire/pi_wire_serial.c

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, baud_rate) ⇒ Serial

Returns a new instance of Serial.



5
6
7
8
9
10
11
12
13
14
# File 'lib/pi_wire/serial.rb', line 5

def initialize(name, baud_rate)
  @name = name
  @baud_rate = baud_rate
  open

  if block_given?
    yield self
    close
  end
end

Instance Attribute Details

#baud_rateObject (readonly)

Returns the value of attribute baud_rate.



3
4
5
# File 'lib/pi_wire/serial.rb', line 3

def baud_rate
  @baud_rate
end

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/pi_wire/serial.rb', line 3

def name
  @name
end

Instance Method Details

#closeObject



59
60
61
62
63
# File 'ext/pi_wire/pi_wire_serial.c', line 59

static VALUE serial_close(VALUE self) {
  int fd = get_fd(self);
  serialClose(fd);
  return Qtrue;
}

#readObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'ext/pi_wire/pi_wire_serial.c', line 39

static VALUE serial_read(VALUE self) {
  int fd = get_fd(self);
  int chars_available = serialDataAvail(fd);
  int i;
  char *str = malloc(chars_available + 1);

  if (chars_available == -1) {
    rb_raise(rb_eRuntimeError, "No data to read");
    return Qnil;
  }

  for (i = 0; i < chars_available; i++) {
    str[i] = serialGetchar(fd);
  }

  str[chars_available +1] = '\0';

  return rb_str_new2(str);
}

#write(str) ⇒ Object



31
32
33
34
35
36
37
# File 'ext/pi_wire/pi_wire_serial.c', line 31

static VALUE serial_write(VALUE self, VALUE str) {
  int fd = get_fd(self);
  char *s = StringValueCStr(str);
  serialPuts(fd, s);
  tcdrain(fd);
  return Qtrue;
}