debsahu / TwitterWebAPI

An Arduino library to talk to Twitter using Twitter Web API made for ESP8266
GNU General Public License v3.0
29 stars 8 forks source link

New Message Does Display on Dot Matrix #2

Closed LizMyers closed 6 years ago

LizMyers commented 6 years ago

I've got data coming back in the Serial Monitor only. Dot Matrix display is not moving...

debsahu commented 6 years ago

Are your wires connected this way?

// VCC -> 5V, GND -> GND, DIN -> D7, CS -> D8 (configurable below), CLK -> D5

In the mean time, I'll get you a minimal code for https://github.com/SensorsIot/MAX7219-4-digit-display-for-ESP8266 to test your display

debsahu commented 6 years ago

Could you try this code to see if you see "Welcome" on your display?

#include <MAX7219_Dot_Matrix.h>
#include <ESP8266WiFi.h>

const byte chips = 8;
MAX7219_Dot_Matrix display (chips, D8);  // Chips / LOAD 
char* message = "Welcome";

unsigned long lastMoved = 0;
unsigned long MOVE_INTERVAL = 20;  // mS
int  messageOffset;

void updateDisplay(char* msg){
  display.sendSmooth (msg, messageOffset);
  // next time show one pixel onwards
  if (messageOffset++ >= (int) (strlen (msg) * 8)){
    messageOffset = - chips * 8;
  }
}  // end of updateDisplay

void setup() {
  display.begin();
  display.setIntensity(9);
}

void loop() {  
  if (millis() - lastMoved >= MOVE_INTERVAL){
    updateDisplay(message);
    lastMoved = millis();
  }
  yield();
}
debsahu commented 6 years ago

If that does not work, could you

LizMyers commented 6 years ago

My Dot Matrix Display works with the 4th sketch in the examples folder. BUT it only displays "No Message Yet!" (there's no message in the Serial Port either). However, the FIRST 8266 example (TwitterSearch.ino) works perfectly - I see the right results in the Serial Monitor - but there is not code integrated for Dot Matrix Display in that sketch (as you said it's separate). Here's my question how do I get both? I think the problem is the login credentials - with SSID and PASSWORD only I'm getting the latest tweet under the hashtag #voiceuimunich or the latest tweet in my feed @lizmyers. Could you please explain the 4 login pieces in the last sketch?

LizMyers commented 6 years ago

What do I enter for OTA User, OTA Password, AutoAP_Password, and Location?

debsahu commented 6 years ago

Thanks for clarifying, the last example uses wifimanager. So there is no need to hard code the WiFi settings. Once uploaded with correct Twitter credentials, use a phone and search for "TwitterDisplay" and password is what you set in "AutoAP_Password". Go ahead and put in your WiFi settings in there. This is only needed once, once setup it will connect to WiFi automatically.

debsahu commented 6 years ago

OTA user and OTA password are credentials used for updating Arduino completed sketch via browser. OTA location is where one would update the compile sketch. So it is http:///firmware using the location as '/firmware'.

LizMyers commented 6 years ago

I seem to connect to Wifi - but I don't get the latest @lizmyers tweet or #voiceuimunich tweet... without a step by step walkthru I don't know why. Could I share my screen with you? Could you add the DotMatrixDisplay to the simpler example (which does show the right twitter data?) TwitterSearch.ino? << I love that sketch, there's less code and so less to go wrong.

debsahu commented 6 years ago
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <TimeLib.h>
#include <ArduinoJson.h>                  // https://github.com/bblanchon/ArduinoJson
//#include "secret.h"                       // uncomment if using secret.h file with credentials
//#define TWI_TIMEOUT 3000                  // varies depending on network speed (msec), needs to be before TwitterWebAPI.h
#include <TwitterWebAPI.h>

// Choose one of the options below for MAX7219 Display
#define MAX7219DISPLAY                    // uncomment if using MAX7219-4-digit-display-for-ESP8266

#ifdef MAX7219DISPLAY
  #include <MAX7219_Dot_Matrix.h>           // https://github.com/SensorsIot/MAX7219-4-digit-display-for-ESP8266
  // VCC -> 5V, GND -> GND, DIN -> D7, CS -> D8 (configurable below), CLK -> D5
  const byte chips = 4;                     // Number of Display Chips
  MAX7219_Dot_Matrix display (chips, D8);   // Chips / LOAD
  unsigned long MOVE_INTERVAL = 20;         // (msec) increase to slow, decrease to fast
#endif

#ifndef WIFICONFIG
const char* ssid = "wifi_ssid";           // WiFi SSID
const char* password = "wifi_password";   // WiFi Password
#endif

std::string search_str = "#dog";          // Default search word for twitter
const char *ntp_server = "pool.ntp.org";  // time1.google.com, time.nist.gov, pool.ntp.org
int timezone = -5;                        // US Eastern timezone -05:00 HRS
unsigned long twi_update_interval = 20;   // (seconds) minimum 5s (180 API calls/15 min). Any value less than 5 is ignored!

#ifndef TWITTERINFO  // Obtain these by creating an app @ https://apps.twitter.com/
  static char const consumer_key[]    = "gkyjeH3EF32NJfiuheuyf8623";
  static char const consumer_sec[]    = "HbY5h$N86hg5jjd987HGFsRjJcMkjLaJw44628sOh353gI3H23";
  static char const accesstoken[]     = "041657084136508135-F3BE63U4Y6b346kj6bnkdlvnjbGsd3V";
  static char const accesstoken_sec[] = "bsekjH8YT3dCWDdsgsdHUgdBiosesDgv43rknU4YY56Tj";
#endif

//   Dont change anything below this line    //
///////////////////////////////////////////////

unsigned long api_mtbs = twi_update_interval * 1000; //mean time between api requests
unsigned long api_lasttime = 0; 
bool twit_update = false;
std::string search_msg = "No Message Yet!";
unsigned long lastMoved = 0;
int  messageOffset;

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, ntp_server, timezone*3600, 60000);  // NTP server pool, offset (in seconds), update interval (in milliseconds)
TwitterClient tcr(timeClient, consumer_key, consumer_sec, accesstoken, accesstoken_sec);

void extractTweetText(String tmsg) {
  Serial.print("Recieved Message Length");
  long msglen = tmsg.length();
  Serial.print(": ");
  Serial.println(msglen);
//  DEBUG_PRINT("MSG: ");
//  DEBUG_PRINTLN(tmsg);
  if (msglen <= 31) return;

  String searchstr = ",\"text\":\""; 
  unsigned int searchlen = searchstr.length();
  int pos1 = -1, pos2 = -1;
  for(long i=0; i <= msglen - searchlen; i++) {
    if(tmsg.substring(i,searchlen+i) == searchstr) {
      pos1 = i + searchlen;
      break;
    }
  }
  searchstr = "\",\""; 
  searchlen = searchstr.length();
  for(long i=pos1; i <= msglen - searchlen; i++) {
    if(tmsg.substring(i,searchlen+i) == searchstr) {
      pos2 = i;
      break;
    }
  }
  String text = tmsg.substring(pos1, pos2);

  searchstr = ",\"screen_name\":\""; 
  searchlen = searchstr.length();
  int pos3 = -1, pos4 = -1;
  for(long i=pos2; i <= msglen - searchlen; i++) {
    if(tmsg.substring(i,searchlen+i) == searchstr) {
      pos3 = i + searchlen;
      break;
    }
  }
  searchstr = "\",\""; 
  searchlen = searchstr.length();
  for(long i=pos3; i <= msglen - searchlen; i++) {
    if(tmsg.substring(i,searchlen+i) == searchstr) {
      pos4 = i;
      break;
    }
  }
  String usert = "@" + tmsg.substring(pos3, pos4);

  if (text.length() > 0) {
    if (usert.length() > 1) text =  usert + " says " + text;
//    text=convertUnicode(text);
    search_msg = std::string(text.c_str(), text.length());
  }
}

void updateDisplay(){
  char *msg = new char[search_msg.length() + 1];
  strcpy(msg, search_msg.c_str());
  display.sendSmooth (msg, messageOffset);

  // next time show one pixel onwards
  if (messageOffset++ >= (int) (strlen (msg) * 8)){
    messageOffset = - chips * 8;
    if (twit_update) {
      digitalWrite(LED_BUILTIN, LOW);
      display.sendString ("--------");
      extractTweetText(tcr.searchTwitter(search_str));
//      extractJSON(tcr.searchTwitter(search_str)); // ArduinoJSON crashes esp8266, twitter info is too long
      Serial.print("Search: ");
      Serial.println(search_str.c_str());
      Serial.print("MSG: ");
      Serial.println(search_msg.c_str());
      twit_update = false;
    }
  }
  delete [] msg;
  //free(msg);
}  // end of updateDisplay

void setup(void){
  //Begin Serial
  Serial.begin(115200);
  display.begin();
  display.setIntensity(9);
  // WiFi Connection
  WiFi.begin(ssid, password);
  Serial.print("\nConnecting to ");
  Serial.print(ssid);
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected. yay!");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  delay(100);
  // Connect to NTP and force-update time
  tcr.startNTP();
  Serial.println("NTP Synced");
  delay(100);
  // Setup internal LED
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  if (twi_update_interval < 5) api_mtbs = 5000; // Cant update faster than 5s.
}

void extractJSON(String tmsg) {
  const char* msg2 = const_cast <char*> (tmsg.c_str());
  DynamicJsonBuffer jsonBuffer;
  JsonObject& response = jsonBuffer.parseObject(msg2);

  if (!response.success()) {
    Serial.println("Failed to parse JSON!");
    Serial.println(msg2);
//    jsonBuffer.clear();
    return;
  }

  if (response.containsKey("statuses")) {
    String usert = response["statuses"][0]["user"]["screen_name"];
    String text = response["statuses"][0]["text"];
    if (text != "") {
      text = "@" + usert + " says " + text;
      search_msg = std::string(text.c_str(), text.length());
    }
  } else if(response.containsKey("errors")) {
    String err = response["errors"][0];
    search_msg = std::string(err.c_str(), err.length());
  } else {
    Serial.println("No useful data");
  }

  jsonBuffer.clear();
  delete [] msg2;
}

void loop(void){
  if (millis() > api_lasttime + api_mtbs)  {
    twit_update = true;
    updateDisplay();
    api_lasttime = millis();
  }
  if (millis() - lastMoved >= MOVE_INTERVAL){
    updateDisplay();
    lastMoved = millis();
  }
  delay(2);
  yield();
  digitalWrite(LED_BUILTIN, HIGH);
}
LizMyers commented 6 years ago

Awesome - I've started over again and see the following in the Serial Monitor:

Connecting to Tech_D0042172.......Connected. yay! IP address: 192.168.0.19 NTP Synced Recieved Message Length: 3226 Search: #voiceuimunich MSG: @adrian_paschek says The conclusion of our Voice meets IoT Hackathon: Amazing participants, awesome projects and great atmosphere! The l\u2026 https:\/\/t.co\/lRDm9GiFnt

My Screen is not displaying a msg - it's solid with red dots... i'll review the libraries again...

LizMyers commented 6 years ago

PS: I meant my Dot Matrix Display - "screen" was ambiguous

debsahu commented 6 years ago

Ok, I forgot at add display.begin(); display.setIntensity(9); inside setup(). Could you add those lines.

LizMyers commented 6 years ago

Line 59: "recieved" is misspelled > should be "received" Still struggling w/Display...

LizMyers commented 6 years ago

YES! that was it - i just added 2 lines at top of Setup() display.begin(); display.setIntensity(9);

and NOW IT WORKS!!! Thanks so much for this. I recommend you republish with these fixes so that others can use your wonderful work. This is now a useful product - love being able to change the #hashtag or @UserName parameters - thanks again for your time and attention today.

LizMyers commented 6 years ago

For marketers it would also be very useful if they could change the search term (hashtag or @user) from their phone or the web without having to recompile/load the sketch.

Last question(s) - how do I control the speed of the scrolling text? Is there any way to make the letters smaller? This DotMatrix library is kind of hard on the eyes/brain closeup. Thanks again - best, Liz

debsahu commented 6 years ago

The last example does just that, it keeps a webserver open http://\<HOSTIP>/search where all one has to do is log on and change the "search" term. If one goes to http://\<HOSTIP>/tweet one can tweet from the ESP8266 as well.

Change unsigned long MOVE_INTERVAL = 20; // (msec) increase to slow, decrease to fast to control speed. To change font, edit https://github.com/SensorsIot/MAX7219-4-digit-display-for-ESP8266/blob/master/MAX7219_Dot_Matrix_font.h

LizMyers commented 6 years ago

fantastic! It's really satisfying when you can customize and modify to the point where it works and you're happy with the way it works. Thanks again for all your hard work. IFTTT + Adafruit I/O wasn't responsive enough. Now the project is responsive, fun, and useful.

LizMyers commented 6 years ago

Debsahu - this red dot matrix reminds me of the stock ticker on the outside of the bldg in London's financial district. Have you written a sketch (or seen one) to display current stock prices? That's the project I would like to do next.

debsahu commented 6 years ago

Something similar will be my next video this friday ;) Some machine learning stuff as well.

LizMyers commented 6 years ago

REALLY?! Awesome. Would you pls send me a link to your video? liz@theAlexpert.io. Thank you!!

debsahu commented 6 years ago

It is not exactly what you are describing but very close, friday around mid-night EST on my channel https://www.youtube.com/channel/UC8AWNs6efg2MLhBTuCIJcsg