0

Neopixel Plug and Play
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Neopixel Plug and Play

by alexshmalex on Sat Mar 17, 2018 6:41 pm

Hello,

Working on a totem LED sign and The Mini Skinny Neopixel is small enough (w/ casing removed) for what I'm looking for. Although, I'm looking for quick and easy set up at the moment. Like using your touch wheel controllers even if it means limited function. I do have some tinkering experience and am sure I could work with arduino and a microcontroller but I am pressed for time and would prefer not to. Any ideas or suggestions to get the Neopixel running would be super helpful.

Thanks!
Alex H.

EDIT: Appears the Adafruit Trinket might be as good as it gets then? Or I if I can find a premade controller with correct requirements?

alexshmalex
 
Posts: 10
Joined: Sat Mar 17, 2018 6:22 pm

Re: Neopixel Plug and Play

by Naip on Fri Apr 06, 2018 7:28 pm

I have the same issue. I need a controller with preset programs that can fit inside a 1.5" Inside Diameter tube.
Naip
 
Posts: 3
Joined: Thu Nov 29, 2012 5:32 pm

Re: Neopixel Plug and Play

by Naip on Fri Apr 06, 2018 7:28 pm

I have the same issue. I need a controller with preset programs that can fit inside a 1.5" Inside Diameter tube.
Naip
 
Posts: 3
Joined: Thu Nov 29, 2012 5:32 pm

Re: Neopixel Plug and Play

by Disciple on Mon Apr 09, 2018 2:48 am

Hi. I hobby a bit with NeoPixels, and have been taught that they won't work without a controller and a program. A Trinket or Gemma can manage the colors of about 100, an Arduino about 500, an M0 Trinket a couple thousand. A goodly number of projects in the learning system show useful circuits and sketches that might adapt to your needs, like the Animated NeoPixel Glow Fur Scarf. See what you think. Best of success.

Hallelujah!
Disciple

Disciple
 
Posts: 550
Joined: Tue Jan 06, 2015 8:13 pm

Re: Neopixel Plug and Play

by alexshmalex on Mon Apr 09, 2018 2:54 am

Thanks! That one will be useful. I have slowly realized that Im just going to have go for it haha. I'll share my build soon.

alexshmalex
 
Posts: 10
Joined: Sat Mar 17, 2018 6:22 pm

Re: Neopixel Plug and Play

by alexshmalex on Fri Apr 13, 2018 1:39 am

I have pretty come to the conclusion I believe but i would appreciate any insight on my wiring. I Imagine first pic (on left) is ideal since the feather will regulate the 5v down to 3.7v. I'm going to run a usb from my battery pack in a back pack up to the feather (8 to9ft, it's not ideal but I hope the extra amps will make up for it) where it will split into bare cables for the neopixel and also into a micro usb to power the feather.
EDIT: I meant 4.5 amps not volts
Diagrams.png
Diagrams.png (167.48 KiB) Viewed 498 times

alexshmalex
 
Posts: 10
Joined: Sat Mar 17, 2018 6:22 pm

Re: Neopixel Plug and Play

by Disciple on Thu Apr 19, 2018 5:29 pm

Hello again. I'm no qualified technician, but I'll role-play for a moment.
How many pixels will be part of this circuit? Enough to draw 4.5A? There's a safety limit for current running through these little circuit boards, and I'm sure 4.5A exceeds it. The official technicians will have recommendations for managing that much demand.

I should point out a second detail. Both circuit layouts provide 5V power to your NeoPixels, but data at only 3.3V levels. I'm told this difference in voltage makes pixel performance unreliable. One solution is to shift the data level up to 5V with a 74AHCT125 or something similar. Another answer is to power both Feather and pixels from a 3.7V rechargable. The Feather can even do the recharging (but a large capacity battery may take some time).
That's what I have at the moment. Hope it's useful.

Hallelujah!
Disciple

Disciple
 
Posts: 550
Joined: Tue Jan 06, 2015 8:13 pm

Re: Neopixel Plug and Play

by alexshmalex on Fri Apr 20, 2018 5:58 pm

From my limited understanding of electronics, the NeoPixels (60pixels) will only pull the amps they need so 4.5amps gives it more than enough and will help with resistance along my 10ft USB cord (I doubt there's that much anyways). Because the feather will be stored in the top of a 9ft pole where it will control my NeoPixels and the power is going to be coming from my backpack where my charger will be because I'll be carrying it around EDC all day and need enough power to last around 8-10 hours.

With data, I'm super lost. I saw a few things about that but it doesn't click with me. I first assumed they meant that powering the pixels with 3.7v makes them unreliable. And I also assumed data is data and there's no difference. My things just got delivered and I suppose I'll have to try it out with 3.7v data because I really dont want pay to ship just thay 1 piece haha.

alexshmalex
 
Posts: 10
Joined: Sat Mar 17, 2018 6:22 pm

Re: Neopixel Plug and Play

by alexshmalex on Fri Apr 20, 2018 7:34 pm

Double checked NeoPixel Uberguide, more amps is good.

They say the logic shifter is neccesary. When powering it with 5v they require a 5v data signal. But it also says when "powering with 3.7v like from a LiPoly, a 3.3v data signal is OK". So I beleive I was hoping that I can maximize the brightness by giving the NeoPixels 5v power and it would be "OK" to use the 3.3V data signal. I saw a few projects that did this:

Festive Feather Holiday Lights, Bluefruit Controlled Macetech RGB LED Shades (also same setup but drawing power from usb on board, not directly)

I know my power is good and then if my data doesn't work out i don't think that'll cause any harm? But it just wont work. I don't have the recommended capacitor and resistor though. I saw most projects didn't bother including them. The Holiday Lights even has a lot more power and leds. Maybe I'll be good?

alexshmalex
 
Posts: 10
Joined: Sat Mar 17, 2018 6:22 pm

Re: Neopixel Plug and Play

by Disciple on Sun Apr 22, 2018 12:01 am

Well, I'll defer to the experts at this point. For my part, I'd really hesitate to send 4.5 amps through a single USB cord. Few NeoPixel projects light them all at full power, though, and maybe yours are for select color effects that consume only 1/2 to 1/3 of maximum. That would ease the demand. As for going without a level shifter, I guess you could try it and see. Might work, but no guarantees. Wouldn't want it to fail between rehearsal and showtime. Best of success for your project, and pictures of the WIPs and finals are invited.

Hallelujah!
Disciple

Disciple
 
Posts: 550
Joined: Tue Jan 06, 2015 8:13 pm

Re: Neopixel Plug and Play

by alexshmalex on Wed Apr 25, 2018 4:56 am

Whelp I ended up buying the capacitor, resistor, and level shifter(same day shipped) because I figured better safe than sorry before I got to work.

After many hours of soldering with a soldering iron with a broken tip and my better one at work, I can't control my NeoPixels. I can power the Feather, run Blink test, command test (the setting from 6 to 4 which was set as default anyways, is set), and connect via bluetooth. I checked all my connections soldering wise (could be a little rough but they should be fine so lets assume these are perfect haha) and just general placement:

1. Data: Pin 6 goes in to Level Shifter "1A" pin and out on "1Y" and then to data input on strip (arrow going away from connection so its not output. it would be output if the strip arrow is pointing towards the connections correct?).
2. Power: Level shifter (direct 5V), Feather (via USB), and NeoPixel (direct 5V)
3. GND: Level Shifter (direct and on GND to 1OE on the shifter), Feather (via USB), and neopixel (direct)
4. 300omh resistor is in between output on Level Shifter and input on NeoPixel strip.
5. Capacitor is across main GND and 5V(negative end on GND).

I ran the strand test as described in the NeoPixel UberGuide, tried messing with the Bluetooth app, and uploading a few projects code. No luck, any suggestions/advice would be super helpful.

Thanks!
Alex H

alexshmalex
 
Posts: 10
Joined: Sat Mar 17, 2018 6:22 pm

Re: Neopixel Plug and Play

by Disciple on Thu Apr 26, 2018 3:50 pm

I can't do the expert's job, but I can save some steps in finding the problem.
  • Take some photos and upload them. Make sure they show the appearance of the soldering and how all the wiring is connected. Aim for 800x600 at about 1Meg.
  • Include the full texts of your sketches. Enclose each in code tags; there's a button above the reply window to create them.
  • If you're following instructions from a tutorial, include a link to it.
I hope the techs arrive soon, though a question with replies is harder to detect, their radar may still pick it up. And just because I can't resist sniffing for clues, I must ask. Did your NeoPixels work correctly in a test before soldering?

Hallelujah!
Disciple

Disciple
 
Posts: 550
Joined: Tue Jan 06, 2015 8:13 pm

Re: Neopixel Plug and Play

by alexshmalex on Thu Apr 26, 2018 4:01 pm

Still not working, and I was just about to update with some more info and i just got notified of your reply:

I bypassed a connector I had wired my leds into to make sure it wasn't bad. I also bypassed one resistor to make sure it wasn't bad (I used a new one on the bypass). Also, I bypassed the logic shifter to make sure it wasn't bad (so I ran on 3v logic). I have the Bluefruit LE sketch exported and uploaded to my Feather, I can connect to feather, and select NeoPixel. It says ready to connect, I click connect and then it says "not detected" shortly after.

For awhile, I wasn't able to update my feather from my phone but via mac osx version I was able to update it.

I got ahead of my self one night and didn't test it pre-soldered mainly because I didn't want to solder on a bunch of headers. I'll send some pics soon but the wiring matches the diagram I posted early besides their being the required capacitor, resistor, and logic shifter.

alexshmalex
 
Posts: 10
Joined: Sat Mar 17, 2018 6:22 pm

Re: Neopixel Plug and Play

by alexshmalex on Tue May 01, 2018 3:46 am

I can only imagine its probably bad code on my part. Probably something I misunderstood but I just exported from the app, to email, to arduino, and uploaded to the feather. My current theory is I need to enter my NeoPixel, pixel count into the code. I was just following the feather and NeoPixel uberguide tutorials. Here's my code and hopefully enough pics:

After looking at my pictures when posting, they're not focused super well for whatever reason. Hopefully enough to get the point across. Solder on "6" was with a much better soldering iron and my GND (although blurry) is rough but definitely connected. I also re soldered the main GND and PWR (where most things are attached) to where it melted all throughout nicely.

Code: Select all | TOGGLE FULL SIZE
// Include Bluetooth

#include <Arduino.h>
#include <SPI.h>
#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_)
#include <SoftwareSerial.h>
#endif

#include "Adafruit_BLE.h"
#include "Adafruit_BluefruitLE_SPI.h"
#include "Adafruit_BluefruitLE_UART.h"

#include "BluefruitConfig.h"

// Include NeoPixel
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif

// Include
#include "ArdPrintf.h"

// Config
#define FACTORYRESET_ENABLE      1

// Bluetooth
// ...hardware SPI, using SCK/MOSI/MISO hardware SPI pins and then user selected CS/IRQ/RST
Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);

// Neopixel
#define PIN            6   /* Pin used to drive the NeoPixels */

#define MAXCOMPONENTS  4
uint8_t *pixelBuffer = NULL;
uint8_t width = 0;
uint8_t height = 0;
uint8_t components = 3;     // only 3 and 4 are valid values
uint8_t stride;

Adafruit_NeoPixel pixels = Adafruit_NeoPixel();

void setup()
{
  while (!Serial);  // required for Flora & Micro
  delay(500);

  Serial.begin(115200);
  Serial.println(F("Adafruit Bluefruit Neopixel Test"));
  Serial.println(F("------------------------------------"));

  // Initialise the module
  Serial.print(F("Initialising the Bluefruit LE module: "));

  if ( !ble.begin(VERBOSE_MODE) )
  {
    error(F("Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?"));
  }
  Serial.println( F("OK!") );

  // Factory Reset
  if ( FACTORYRESET_ENABLE )
  {
    /* Perform a factory reset to make sure everything is in a known state */
    Serial.println(F("Performing a factory reset: "));
    if ( ! ble.factoryReset() ) {
      error(F("Couldn't factory reset"));
    }
  }

  /* Disable command echo from Bluefruit */
  ble.echo(false);

  Serial.println("Requesting Bluefruit info:");
  /* Print Bluefruit information */
  ble.info();

  /* Wait for a connection before starting the test */
  Serial.println("Waiting for a BLE connection to continue ...");

  ble.verbose(false);  // debug info is a little annoying after this point!

  while ( !ble.isConnected() )
  {
    delay(10);
  }
 
  // Wait for the connection to complete
  delay(1000);

  Serial.println(F("CONNECTED!"));
  Serial.println(F("**********"));

  // Set module to DATA mode
  Serial.println( F("Switching to DATA mode!") );
  ble.setMode(BLUEFRUIT_MODE_DATA);

  Serial.println(F("******************************"));

  // Neopixels
  pixels.begin();
}

void loop()
{
  // Echo received data
  while ( ble.isConnected() )
  {
    int command = ble.read();

    switch (command) {
      case 'V': {   // Get Version
          commandVersion();
          break;
        }
 
      case 'S': {   // Setup dimensions, components, stride...
          commandSetup();
          break;
       }

      case 'C': {   // Clear with color
          commandClearColor();
          break;
      }

      case 'B': {   // Set Brightness
          commandSetBrightness();
          break;
      }
           
      case 'P': {   // Set Pixel
          commandSetPixel();
          break;
      }
 
      case 'I': {   // Receive new image
          commandImage();
          break;
       }

    }
  }
}

void swapBuffers()
{
  uint8_t *base_addr = pixelBuffer;
  int pixelIndex = 0;
  for (int j = 0; j < height; j++)
  {
    for (int i = 0; i < width; i++) {
      if (components == 3) {
        pixels.setPixelColor(pixelIndex, pixels.Color(*base_addr, *(base_addr+1), *(base_addr+2)));
      }
      else {
        Serial.println(F("TODO: implement me"));
      }
      base_addr+=components;
      pixelIndex++;
    }
    pixelIndex += stride - width;   // move pixelIndex to the next row (take into account the stride)
  }
  pixels.show();

}

void commandVersion() {
  Serial.println(F("Command: Version check"));
  sendResponse("Neopixel v1.0");
}

void commandSetup() {
  Serial.println(F("Command: Setup"));

  width = ble.read();
  height = ble.read();
  components = ble.read();
  stride = ble.read();
  neoPixelType pixelType;
  pixelType = ble.read();
  pixelType += ble.read()<<8;
 
  ardprintf("\tsize: %dx%d", width, height);
  ardprintf("\tcomponents: %d", components);
  ardprintf("\tstride: %d", stride);
  ardprintf("\tpixelType %d", pixelType );


  if (pixelBuffer != NULL) {
      delete[] pixelBuffer;
  }

  uint32_t size = width*height;
  pixelBuffer = new uint8_t[size*components];
  pixels.updateLength(size);
  pixels.updateType(pixelType);
  pixels.setPin(PIN);

  // Done
  sendResponse("OK");
}

void commandSetBrightness() {
  Serial.println(F("Command: SetBrightness"));

   // Read value
  uint8_t brightness = ble.read();

  // Set brightness
  pixels.setBrightness(brightness);

  // Refresh pixels
  swapBuffers();

  // Done
  sendResponse("OK");
}

void commandClearColor() {
  Serial.println(F("Command: ClearColor"));

  // Read color
  uint8_t color[MAXCOMPONENTS];
  for (int j = 0; j < components;) {
    if (ble.available()) {
      color[j] = ble.read();
      j++;
    }
  }

  // Set all leds to color
  int size = width * height;
  uint8_t *base_addr = pixelBuffer;
  for (int i = 0; i < size; i++) {
    for (int j = 0; j < components; j++) {
      *base_addr = color[j];
      base_addr++;
    }
  }

  // Swap buffers
  Serial.println(F("ClearColor completed"));
  swapBuffers();


  if (components == 3) {
    ardprintf("\tcolor (%d, %d, %d)", color[0], color[1], color[2] );
  }
 
  // Done
  sendResponse("OK");
}

void commandSetPixel() {
  Serial.println(F("Command: SetPixel"));

  // Read position
  uint8_t x = ble.read();
  uint8_t y = ble.read();

  // Read colors
  uint32_t pixelIndex = y*width+x;
  uint32_t pixelComponentOffset = pixelIndex*components;
  uint8_t *base_addr = pixelBuffer+pixelComponentOffset;
  for (int j = 0; j < components;) {
    if (ble.available()) {
      *base_addr = ble.read();
      base_addr++;
      j++;
    }
  }

  // Set colors
  if (components == 3) {
    uint32_t pixelIndex = y*stride+x;
    pixels.setPixelColor(pixelIndex, pixels.Color(pixelBuffer[pixelComponentOffset], pixelBuffer[pixelComponentOffset+1], pixelBuffer[pixelComponentOffset+2]));

    ardprintf("\tcolor (%d, %d, %d)", pixelBuffer[pixelComponentOffset], pixelBuffer[pixelComponentOffset+1], pixelBuffer[pixelComponentOffset+2] );
  }
  else {
    Serial.println(F("TODO: implement me"));
  }
  pixels.show();

  // Done
  sendResponse("OK");
}

void commandImage() {
  ardprintf("Command: Image %dx%d, %d, %d", width, height, components, stride);
 
  // Receive new pixel buffer
  int size = width * height;
  uint8_t *base_addr = pixelBuffer;
  for (int i = 0; i < size; i++) {
    for (int j = 0; j < components;) {
      if (ble.available()) {
        *base_addr = ble.read();
        base_addr++;
        j++;
      }
    }

/*
    if (components == 3) {
      uint32_t index = i*components;
      ardprintf("\tp%d (%d, %d, %d)", i, pixelBuffer[index], pixelBuffer[index+1], pixelBuffer[index+2] );
    }
    */
  }

  // Swap buffers
  Serial.println(F("Image received"));
  swapBuffers();

  // Done
  sendResponse("OK");
}

void sendResponse(char *response) {
    ardprintf("Send Response: %s", response);
    ble.write(response, strlen(response)*sizeof(char));
}

// A small helper
void error(const __FlashStringHelper*err) {
  Serial.println(err);
  while (1);
}
Attachments
3.png
3.png (792.39 KiB) Viewed 292 times
2.png
2.png (930.04 KiB) Viewed 292 times
1.png
1.png (865.05 KiB) Viewed 292 times

alexshmalex
 
Posts: 10
Joined: Sat Mar 17, 2018 6:22 pm

Re: Neopixel Plug and Play

by alexshmalex on Tue May 08, 2018 3:28 am

I also tried using this code when I realized I did not code properly and still no luck sadly. I also put in the proper info in the adafruit code supplied by the BlueFruit app. I was thinking, I'm getting power to my board, but is it possible that the NeoPixels need a instant active current going to them. I was thinking maybe the USB charger detects that the board needs power and powers it but since the NeoPixels have no power they do not go "hey I need power too" so the charger just supplys the amps needed to power the board but not any extra for the NeoPixels. Just another theory I had, still have no idea why nothing is working.

Code: Select all | TOGGLE FULL SIZE
// Adafruit Bluefruit LE Feather Holiday Lights
// See the full guide at:
//   https://learn.adafruit.com/feather-holiday-lights/overview
// Author: Tony DiCola
// Based on the neopixel_picker example from the Adafruit Bluefruit nRF51 library.
// Released under a MIT license:
//   https://opensource.org/licenses/MIT
#include "Adafruit_BLE.h"
#include "Adafruit_BluefruitLE_SPI.h"
#include "Adafruit_NeoPixel.h"
#include "BluefruitConfig.h"
#include "SoftwareSerial.h"
#include "SPI.h"


#define PIXEL_COUNT 60    // The number of NeoPixels connected to the board.

#define PIXEL_PIN   6     // The pin connected to the input of the NeoPixels.

#define PIXEL_TYPE  NEO_GRB + NEO_KHZ800  // The type of NeoPixels, see the NeoPixel
                                          // strandtest example for more options.

#define ANIMATION_PERIOD_MS  300  // The amount of time (in milliseconds) that each
                                  // animation frame lasts.  Decrease this to speed
                                  // up the animation, and increase it to slow it down.


// Create NeoPixel strip from above parameters.
Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, PIXEL_TYPE);

// Create the Bluefruit object using hardware SPI (for Bluefruit LE feather).
Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);

// Global variable to hold the current pixel color.  Starts out red but will be
// changed by the BLE color picker.
int r = 255;
int g = 0;
int b = 0;

// Function prototypes and data over in packetparser.cpp
uint8_t readPacket(Adafruit_BLE *ble, uint16_t timeout);
float parsefloat(uint8_t *buffer);
void printHex(const uint8_t * data, const uint32_t numBytes);
extern uint8_t packetbuffer[];


void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Adafruit Bluefruit LE Holiday Lights"));

  // Initialize NeoPixels.
  strip.begin();
  strip.show();

  // Initialize BLE library.
  if (!ble.begin(false))
  {
    Serial.println(F("Couldn't find Bluefruit LE module!"));
    while (1);
  }
  ble.echo(false);

  Serial.println(F("Please use Adafruit Bluefruit LE app to connect in Controller mode"));
  Serial.println(F("Then activate/use the color picker to change color."));
  Serial.println();

  // Wait for connection.
  while (!ble.isConnected()) {
    // Make sure to animate the pixels while waiting!
    animatePixels(strip, r, g, b, ANIMATION_PERIOD_MS);
    delay(50);
  }
  ble.setMode(BLUEFRUIT_MODE_DATA);
}

void loop(void)
{
  // Animate the pixels.
  animatePixels(strip, r, g, b, ANIMATION_PERIOD_MS);
 
  // Grab a BLE controller packet if available.
  uint8_t len = readPacket(&ble, BLE_READPACKET_TIMEOUT);
  if (len == 0) return;

  // Parse a color packet.
  if (packetbuffer[1] == 'C') {
    // Grab the RGB values from the packet and change the light color.
    r = packetbuffer[2];
    g = packetbuffer[3];
    b = packetbuffer[4];
    // Print out the color that was received too:
    Serial.print ("RGB #");
    if (r < 0x10) Serial.print("0");
    Serial.print(r, HEX);
    if (g < 0x10) Serial.print("0");
    Serial.print(g, HEX);
    if (b < 0x10) Serial.print("0");
    Serial.println(b, HEX);
  }
}

void animatePixels(Adafruit_NeoPixel& strip, uint8_t r, uint8_t g, uint8_t b, int periodMS) {
  // Animate the NeoPixels with a simple theater chase/marquee animation.
  // Must provide a NeoPixel object, a color, and a period (in milliseconds) that controls how
  // long an animation frame will last.
  // First determine if it's an odd or even period.
  int mode = millis()/periodMS % 2;
  // Now light all the pixels and set odd and even pixels to different colors.
  // By alternating the odd/even pixel colors they'll appear to march along the strip.
  for (int i = 0; i < strip.numPixels(); ++i) {
    if (i%2 == mode) {
      strip.setPixelColor(i, r, g, b);  // Full bright color.
    }
    else {
      strip.setPixelColor(i, r/4, g/4, b/4);  // Quarter intensity color.
    }
  }
  strip.show();
}

Code: Select all | TOGGLE FULL SIZE
// COMMON SETTINGS
// ----------------------------------------------------------------------------------------------
// These settings are used in both SW UART, HW UART and SPI mode
// ----------------------------------------------------------------------------------------------
#define BUFSIZE                        128   // Size of the read buffer for incoming data
#define VERBOSE_MODE                   true  // If set to 'true' enables debug output
#define BLE_READPACKET_TIMEOUT         50   // Timeout in ms waiting to read a response


// SOFTWARE UART SETTINGS
// ----------------------------------------------------------------------------------------------
// The following macros declare the pins that will be used for 'SW' serial.
// You should use this option if you are connecting the UART Friend to an UNO
// ----------------------------------------------------------------------------------------------
#define BLUEFRUIT_SWUART_RXD_PIN       9    // Required for software serial!
#define BLUEFRUIT_SWUART_TXD_PIN       10   // Required for software serial!
#define BLUEFRUIT_UART_CTS_PIN         11   // Required for software serial!
#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused


// HARDWARE UART SETTINGS
// ----------------------------------------------------------------------------------------------
// The following macros declare the HW serial port you are using. Uncomment
// this line if you are connecting the BLE to Leonardo/Micro or Flora
// ----------------------------------------------------------------------------------------------
#ifdef Serial1    // this makes it not complain on compilation if there's no Serial1
  #define BLUEFRUIT_HWSERIAL_NAME      Serial1
#endif


// SHARED UART SETTINGS
// ----------------------------------------------------------------------------------------------
// The following sets the optional Mode pin, its recommended but not required
// ----------------------------------------------------------------------------------------------
#define BLUEFRUIT_UART_MODE_PIN        12    // Set to -1 if unused


// SHARED SPI SETTINGS
// ----------------------------------------------------------------------------------------------
// The following macros declare the pins to use for HW and SW SPI communication.
// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno when
// using HW SPI.  This should be used with nRF51822 based Bluefruit LE modules
// that use SPI (Bluefruit LE SPI Friend).
// ----------------------------------------------------------------------------------------------
#define BLUEFRUIT_SPI_CS               8
#define BLUEFRUIT_SPI_IRQ              7
#define BLUEFRUIT_SPI_RST              4    // Optional but recommended, set to -1 if unused

// SOFTWARE SPI SETTINGS
// ----------------------------------------------------------------------------------------------
// The following macros declare the pins to use for SW SPI communication.
// This should be used with nRF51822 based Bluefruit LE modules that use SPI
// (Bluefruit LE SPI Friend).
// ----------------------------------------------------------------------------------------------
#define BLUEFRUIT_SPI_SCK              13
#define BLUEFRUIT_SPI_MISO             12
#define BLUEFRUIT_SPI_MOSI             11

Code: Select all | TOGGLE FULL SIZE
#include <string.h>
#include <Arduino.h>
#include <SPI.h>
#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_)
  #include <SoftwareSerial.h>
#endif

#include "Adafruit_BLE.h"
#include "Adafruit_BluefruitLE_SPI.h"
#include "Adafruit_BluefruitLE_UART.h"


#define PACKET_ACC_LEN                  (15)
#define PACKET_GYRO_LEN                 (15)
#define PACKET_MAG_LEN                  (15)
#define PACKET_QUAT_LEN                 (19)
#define PACKET_BUTTON_LEN               (5)
#define PACKET_COLOR_LEN                (6)
#define PACKET_LOCATION_LEN             (15)

//    READ_BUFSIZE            Size of the read buffer for incoming packets
#define READ_BUFSIZE                    (20)


/* Buffer to hold incoming characters */
uint8_t packetbuffer[READ_BUFSIZE+1];

/**************************************************************************/
/*!
    @brief  Casts the four bytes at the specified address to a float
*/
/**************************************************************************/
float parsefloat(uint8_t *buffer)
{
  float f = ((float *)buffer)[0];
  return f;
}

/**************************************************************************/
/*!
    @brief  Prints a hexadecimal value in plain characters
    @param  data      Pointer to the byte data
    @param  numBytes  Data length in bytes
*/
/**************************************************************************/
void printHex(const uint8_t * data, const uint32_t numBytes)
{
  uint32_t szPos;
  for (szPos=0; szPos < numBytes; szPos++)
  {
    Serial.print(F("0x"));
    // Append leading 0 for small values
    if (data[szPos] <= 0xF)
    {
      Serial.print(F("0"));
      Serial.print(data[szPos] & 0xf, HEX);
    }
    else
    {
      Serial.print(data[szPos] & 0xff, HEX);
    }
    // Add a trailing space if appropriate
    if ((numBytes > 1) && (szPos != numBytes - 1))
    {
      Serial.print(F(" "));
    }
  }
  Serial.println();
}

/**************************************************************************/
/*!
    @brief  Waits for incoming data and parses it
*/
/**************************************************************************/
uint8_t readPacket(Adafruit_BLE *ble, uint16_t timeout)
{
  uint16_t origtimeout = timeout, replyidx = 0;

  memset(packetbuffer, 0, READ_BUFSIZE);

  while (timeout--) {
    if (replyidx >= 20) break;
    if ((packetbuffer[1] == 'A') && (replyidx == PACKET_ACC_LEN))
      break;
    if ((packetbuffer[1] == 'G') && (replyidx == PACKET_GYRO_LEN))
      break;
    if ((packetbuffer[1] == 'M') && (replyidx == PACKET_MAG_LEN))
      break;
    if ((packetbuffer[1] == 'Q') && (replyidx == PACKET_QUAT_LEN))
      break;
    if ((packetbuffer[1] == 'B') && (replyidx == PACKET_BUTTON_LEN))
      break;
    if ((packetbuffer[1] == 'C') && (replyidx == PACKET_COLOR_LEN))
      break;
    if ((packetbuffer[1] == 'L') && (replyidx == PACKET_LOCATION_LEN))
      break;

    while (ble->available()) {
      char c =  ble->read();
      if (c == '!') {
        replyidx = 0;
      }
      packetbuffer[replyidx] = c;
      replyidx++;
      timeout = origtimeout;
    }
   
    if (timeout == 0) break;
    delay(1);
  }

  packetbuffer[replyidx] = 0;  // null term

  if (!replyidx)  // no data or timeout
    return 0;
  if (packetbuffer[0] != '!')  // doesn't start with '!' packet beginning
    return 0;
 
  // check checksum!
  uint8_t xsum = 0;
  uint8_t checksum = packetbuffer[replyidx-1];
 
  for (uint8_t i=0; i<replyidx-1; i++) {
    xsum += packetbuffer[i];
  }
  xsum = ~xsum;

  // Throw an error message if the checksum's don't match
  if (xsum != checksum)
  {
    Serial.print("Checksum mismatch in packet : ");
    printHex(packetbuffer, replyidx+1);
    return 0;
  }
 
  // checksum passed!
  return replyidx;
}

alexshmalex
 
Posts: 10
Joined: Sat Mar 17, 2018 6:22 pm

Please be positive and constructive with your questions and comments.