Skip to content

Commit

Permalink
i2c: add ShowImage() function to ssd1306 driver based on @mikegleasonjr
Browse files Browse the repository at this point in the history
… suggestion

Signed-off-by: Ron Evans <[email protected]>
  • Loading branch information
deadprogram committed Aug 7, 2018
1 parent 3c4bfc2 commit 6bd5dce
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
21 changes: 21 additions & 0 deletions drivers/i2c/ssd1306_driver.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package i2c

import (
"errors"
"image"

"gobot.io/x/gobot"
)

Expand Down Expand Up @@ -299,6 +302,24 @@ func (s *SSD1306Driver) Display() (err error) {
return err
}

// ShowImage takes a standard Go image and shows it on the display in monochrome.
func (s *SSD1306Driver) ShowImage(img image.Image) (err error) {
if img.Bounds().Dx() != s.DisplayWidth || img.Bounds().Dy() != s.DisplayHeight {
return errors.New("Image must match the display width and height")
}

s.Clear()
for y, w, h := 0, img.Bounds().Dx(), img.Bounds().Dy(); y < h; y++ {
for x := 0; x < w; x++ {
c := img.At(x, y)
if r, g, b, _ := c.RGBA(); r > 0 || g > 0 || b > 0 {
s.Set(x, y, 1)
}
}
}
return s.Display()
}

// command sends a unique command
func (s *SSD1306Driver) command(b byte) (err error) {
_, err = s.connection.Write([]byte{0x80, b})
Expand Down
11 changes: 11 additions & 0 deletions drivers/i2c/ssd1306_driver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package i2c
import (
"errors"
"fmt"
"image"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -112,6 +113,16 @@ func TestSSD1306DriverDisplay(t *testing.T) {
gobottest.Assert(t, s.Display(), nil)
}

func TestSSD1306DriverShowImage(t *testing.T) {
s, _ := initTestSSD1306DriverWithStubbedAdaptor()
s.Start()
img := image.NewRGBA(image.Rect(0, 0, 640, 480))
gobottest.Assert(t, s.ShowImage(img), errors.New("Image must match the display width and height"))

img = image.NewRGBA(image.Rect(0, 0, 128, 64))
gobottest.Assert(t, s.ShowImage(img), nil)
}

func TestSSD1306DriverCommand(t *testing.T) {
s, adaptor := initTestSSD1306DriverWithStubbedAdaptor()
s.Start()
Expand Down

0 comments on commit 6bd5dce

Please sign in to comment.