Intel Edison not searching tweets - arduino

I was given a Intel Edison, with an integrated WiFi board, to mess around with and read some tweets. So far, I've downloaded the Twitter4j core .jar (version 4.0.2, latest as of today), and set up the Arduino-Processing communication.
Every time I try to execute a query (search tweets by hashtags, for instance) it says Error: api.twitter.com. I have verified that I am connected to the network, and that the network has no proxy issues with Twitter.
It stops working right after println("pre query").
Any ideas?
My Arduino sketch is as follows:
#include <WiFi.h>
#include <WiFiUdp.h>
#include <Ethernet.h>
int ledPin=13;
char ssid[] = "OnePlus One"; // the name of your network
char pass[] = "hugomario"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
void setup()
{
Serial.println("inside setup");
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
Serial.println("\nconnecting ...");
status = WiFi.begin(ssid, pass);
// if you're not connected, stop here:
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// if you are connected :
else {
Serial.print("Connected to the network");
}
}
void loop()
{
Serial.println("\ninside loop");
while(Serial.available()==0);
int val = Serial.read()- '0';
Serial.println(val);
if(val == 1)
{
Serial.println("LED IS ON");
digitalWrite(ledPin,HIGH);
delay(1000);
digitalWrite(ledPin,LOW);
}
else
{
Serial.println("LED IS OFF");
digitalWrite(ledPin,LOW);
}
}
My Processing sketch:
import processing.serial.*;
Serial port;
static String OAuthConsumerKey="kxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxO";
static String OAuthConsumerSecret="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
static String AccessToken= "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
static String AccessTokenSecret="Mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx5";
String[] searchedTweets = new String[50];
ConfigurationBuilder cb = new ConfigurationBuilder();
Twitter twitter;
void setup() {
//Set the size of the stage, and the background to black.
size(200, 200);
background(0);
smooth();
port = new Serial (this, "COM5", 115200);
connectTwitter();
}
void connectTwitter() {
cb.setOAuthConsumerKey(" kxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxO ");
cb.setOAuthConsumerSecret(" kxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxO ");
cb.setOAuthAccessToken("124767053- kxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxO ");
cb.setOAuthAccessTokenSecret(" kxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxO ");
cb.setHttpConnectionTimeout(100000);
twitter = new TwitterFactory(cb.build()).getInstance();
println("is twitter null? ");
println(twitter==null);
getSearchTweets();
}
void getSearchTweets() {
String queryStr = "#yolo";
try {
println("inside try");
Query query = new Query(queryStr);
// query.setRpp(10); //10 out of 100 results
query.count(10);
println("pre query");
QueryResult result = twitter.search(query);
println("post query");
ArrayList tweets = (ArrayList) result.getTweets();
println("tweets size= "+tweets.size());
for (int i=0; i<tweets.size (); i++) {
/*
Tweet t = (Tweet) tweets.get(i);
String user = t.getFromUser();
String msg = t.getText();
Date d = t.getCreatedAt();
*/
Status t = (Status) tweets.get(i);
String user = t.getUser().getName();
String msg = t.getText();
port.write('1');
searchedTweets[i] = user +": "+msg;
println(searchedTweets[i]);
}
}
catch (TwitterException e) {
println("Error: " + e.getMessage());
port.write('0');
}
}
void delay(int delay){
int time = millis();
while(millis()-time <= delay);
}

Related

How to send Bluetooth data from ESP32 in arduino?

Easy to handle received data with BLE but can't send data.
I'm using ESP32 BLE Uart code.
It's easy to get data from RxCharateristic but I don't know how to send data.
I'm trying to use TxCharacteristic to send data with BLE.
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
BLEServer *pServer = NULL;
BLECharacteristic * pTxCharacteristic;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint8_t txValue = 0;
// See the following for generating UUIDs:
// https://www.uuidgenerator.net/
#define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
class MyCallbacks: public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
std::string rxValue = pCharacteristic->getValue();
if (rxValue.length() > 0) {
Serial.println("*********");
Serial.print("Received Value: ");
for (int i = 0; i < rxValue.length(); i++){
Serial.print(rxValue[i]);
}
}
}
};
void setup() {
Serial.begin(115200);
// Create the BLE Device
BLEDevice::init("TheOneSystem");
// Create the BLE Server
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
// Create the BLE Service
BLEService *pService = pServer->createService(SERVICE_UUID);
// Create a BLE Characteristic
pTxCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID_TX,
BLECharacteristic::PROPERTY_NOTIFY
);
pTxCharacteristic->addDescriptor(new BLE2902());
BLECharacteristic * pRxCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID_RX,
BLECharacteristic::PROPERTY_WRITE
);
pRxCharacteristic->setCallbacks(new MyCallbacks());
// Start the service
pService->start();
// Start advertising
pServer->getAdvertising()->start();
Serial.println("Waiting a client connection to notify...");
}
void loop() {
if (deviceConnected) {
pTxCharacteristic->setValue(&txValue, 1);
pTxCharacteristic->notify();
txValue++;
delay(10); // bluetooth stack will go into congestion, if too many packets are sent
}
// disconnecting
if (!deviceConnected && oldDeviceConnected) {
delay(500); // give the bluetooth stack the chance to get things ready
pServer->startAdvertising(); // restart advertising
Serial.println("start advertising");
oldDeviceConnected = deviceConnected;
}
// connecting
if (deviceConnected && !oldDeviceConnected) {
// do stuff here on connecting
oldDeviceConnected = deviceConnected;
}
}
I can easily handle received data with this part of code
class MyCallbacks: public BLECharacteristicCallbacks {
String bleData;
void onWrite(BLECharacteristic *pCharacteristic) {
std::string rxValue = pCharacteristic->getValue();
if (rxValue.length() > 0) {
Serial.println("*********");
Serial.print("Received Value: ");
for (int i = 0; i < rxValue.length(); i++){
//Serial.print(rxValue[i]);
bleData=bleData+rxValue[i];
}
Serial.println();
Serial.println(bleData);
Serial.println("*********");
int first = bleData.indexOf(",");
String bleSSID = bleData.substring(0, first);
String blepw = bleData.substring(first+1, bleData.length());
Serial.println("Wifi : " + bleSSID + "," + "Password : " + blepw);
bleData="";
}
}
};
How to send data by using TxCharacteristic?
In my receiving code, I'm using this function to use callback.
if(pTxCharacteristic->canNotify()) {
pTxCharacteristic->registerForNotify(notifyCallback);
}
And here is my notifyCallback function i got from Google.
static void notifyCallback(
BLERemoteCharacteristic* pBLERemoteCharacteristic,
uint8_t* pData,
size_t length,
bool isNotify){
Serial.println(data);
}
It seems like i have to add a little function in notifyCallback.
However errors continue to occur. I can't get data. Tnx for help.

Problem Reading From Thingspeak from Arduino

I am using this code to retrieve data from a Thingspeak channel in a JSON format. I am using an ESP8266 along with an Arduino Nano 33 BLE. The Nono 33 BLE Arduino board is not compatible with Thingspeak library and it doesn’t support SoftwareSerial. Alternatively, I am using serial1 to communicate with the ESP8266 and REST API method to get the data from Thingspeak as it is shown in the code. However, I cannot get it to work. It is worth noting that Serial1.available() always gives zero even after adding delays.
I have used the same code to send data to the same Thingspeak channel and it works perfectly. I have no clue why it is not reading from the channel. I would really appreciate any help with this problem
Thanks in advance.
String AP ="xxxxxxxxxxx";
String PASS ="xxxxxxxxxxxxxx";
String PORT = "80";
String field = "Id";
int countTrueCommand;
int countTimeCommand;
boolean found = false;
String Data ="";
void setup() {
Serial.begin(9600);
Serial1.begin(115200);
sendCommand("AT",5,"OK",false);
Serial1.println("AT+UART_DEF=9600,8,1,0,0");
delay(1000);
Serial1.end();
Serial1.begin(9600);
ConnectToWifi();
}
void loop() {
String getData="GET https://api.thingspeak.com/channels/1335558/fields/1?api_key=7XFZKXEGOV5HY4TQ";
sendCommand("AT+CIPMUX=1",5,"OK",false);
sendCommand("AT+CIPSTART=4,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK",false);
sendCommand("AT+CIPSEND=4," +String(getData.length()+4),4,">",false);
sendCommand(getData,20,"OK",true);
delay(1500);
countTrueCommand++;
sendCommand("AT+CIPCLOSE=0",5,"OK",false);
}
bool ConnectToWifi(){
for (int a=0; a<15; a++)
{
sendCommand("AT",5,"OK",false);
sendCommand("AT+CWMODE=1",5,"OK",false);
boolean isConnected = sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK",false);
if(isConnected)
{
return true;
}
}
}
bool sendCommand(String command, int maxTime, char readReplay[],boolean isGetData) {
boolean result=false;
//Test Purpose
Serial.print(countTrueCommand);
Serial.print(". at command => ");
Serial.print(command);
Serial.print(" ");
while(countTimeCommand < (maxTime*1))
{
Serial1.println(command);
if(Serial1.find(readReplay))//ok
{
if(isGetData)
{
if(Serial1.find(readReplay))
{
Serial.println("Success : Request is taken from the server");
}
while(Serial1.available())
{
char character = Serial1.read()
Data.concat(character); /
if (character == '\n')
{
Serial.print("Received: ");
Serial.println(Data);
delay(50);
Data = "";
}
}
}
result = true;
break;
}
countTimeCommand++;
}
if(result == true)
{
Serial.println("Success");
countTrueCommand++;
countTimeCommand = 0;
}
if(result == false)
{
Serial.println("Fail");
countTrueCommand = 0;
countTimeCommand = 0;
}
found = false;
return result;

Sending two arrays to Arduino from Processing

I'm trying to pass multiple variables (n number of strings and n number of ints) from processing to my Arduino. I found this tutorial online and managed to send a single value. Now I have two arrays that both need to be accessed by the Arduino filesTypes[] and filesSizes[]. filesTypes[] consists of a 3 char long strings while fileSizes[] is an array of different integers.
Here is my Processing code:
import processing.serial.*;
Serial myPort; // Create object from Serial class
String[] fileTypes;
int[] fileSizes;
String[][] lines;
void setup()
{
size(200,200); //make our canvas 200 x 200 pixels big
String portName = Serial.list()[1]; //change the 0 to a 1 or 2 etc. to
match your port
myPort = new Serial(this, portName, 9600);
launch( sketchPath("") + "/test.bat");
}
void draw() {
if (mousePressed == true)
{ //if we clicked in the window
txtToStrg();
myPort.write('1'); //send a 1
txtToStrg();
} else
{ //otherwise
myPort.write('0'); //send a 0
}
}
void txtToStrg(){
String[] lines = loadStrings("list.txt");
fileTypes = new String[lines.length];
fileSizes = new int[lines.length];
for (int i = 0 ; i < lines.length; i++) {
if(lines[i] != null) {
String[] splitLine = split(lines[i], ' ');
fileTypes[i] = splitLine[0];
fileSizes[i] = int(splitLine[1]);
println(fileTypes[i] + " = " + fileSizes[i]);
}
}
}
And here my Arduino code:
char val; // Data received from the serial port
int ledPin = 4 ; // Set the pin to digital I/O 13
void setup() {
pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
if (Serial.available())
{ // If data is available to read,
val = Serial.read(); // read it and store it in val
}
if (val == '1')
{ // If 1 was received
digitalWrite(ledPin, HIGH); // turn the LED on
} else {
digitalWrite(ledPin, LOW); // otherwise turn it off
Serial.print(val);
}
delay(10); // Wait 10 milliseconds for next reading
}
If a pass anything but a char it stops working.

Issues with serial communication between Arduino and Processing

I'm attempting to create a data exchange between sensors on an Arduino (well, actually an ATmega328PU-based clone built on a breadboard, but I don't believe that that's the source of my problem) and a Processing script, and I'm getting some unexpected results.
I was following the method of serial communication detailed here, but I get stuck with what appears to be no data actually traveling over the serial connection.
The Arduino code:
int buttonPin = 9, photodiodePin = A0;
char dataToSend;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, OUTPUT);
pinMode(photodiodePin, INPUT);
}
void loop() {
if (Serial.available() > 0)
{
dataToSend = Serial.read();
if (dataToSend == 'B')
{
Serial.println(digitalRead(buttonPin));
}
else if (dataToSend == 'L')
{
Serial.println(analogRead(photodiodePin));
}
}
}
And the relevant parts of the Processing code:
import processing.serial.*;
Serial myPort;
void setup()
{
size(1600, 900);
String portName = Serial.list()[1];
myPort = new Serial(this, portName, 9600);
}
void draw()
{
if(getButtonData() == 1)
{
// Do stuff
}
}
int getLightData()
{
myPort.write('L');
println("L");
while(!(myPort.available() > 0))
{
}
int lightValue = int(myPort.readStringUntil('\n'));
return lightValue;
}
int getButtonData()
{
myPort.write('B');
println("B");
while(!(myPort.available() > 0))
{
println("stuck in here");
delay(500);
}
int buttonValue = int(myPort.readStringUntil('\n'));
return buttonValue;
}
And in Processing I get an output of:
B
stuck in here
stuck in here
stuck in here
stuck in here
...
Note: I know I have the correct port selected from the list, so that is not the issue.
I've tried debugging the issue and searching the Internet for similar problems, both to no avail.
I would first check if simply sending a simple message from Arduino to Processing works. Try something like this in Arduino:
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("test");
delay(1000);
}
and this in Processing:
import processing.serial.*;
Serial arduino;
void setup(){
String portName = Serial.list()[1];
try{
arduino = new Serial(this, portName, 9600);
arduino.bufferUntil('\n');
}catch(Exception e){
System.err.println("Error initializing Serial port!\nPlease check connections and port settings");
e.printStackTrace();
}
}
void draw(){
}
void serialEvent(Serial s){
println("received arduino message: " + s.readString());
}
If this simple setup works, you should be fine to move on to the next step and have two way communication. If the above doesn't work then there's something else causing issues with serial communication (in which case please report what errors you're receiving, if any or what behaviour you're experiencing)
In case the above works, you can try two way communication. Notice I'm making use of serialEvent() and bufferUntil. It's best to avoid blocking while loops wherever possible.
Arduino code:
int buttonPin = 9, photodiodePin = A0;
char dataToSend;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, OUTPUT);
pinMode(photodiodePin, INPUT);
}
void loop() {
}
void serialEvent(){
if(Serial.available() > 0){
char cmd = Serial.read();
if(cmd == 'B'){
Serial.println(digitalRead(buttonPin));
}
if(cmd == 'L'){
Serial.println(analogRead(photodiodePin));
}
}
}
Processing code:
import processing.serial.*;
Serial arduino;
int digitalValue;
int analogValue;
int lastCMD;
void setup(){
size(200,100);
String portName = Serial.list()[1];
try{
arduino = new Serial(this, portName, 9600);
arduino.bufferUntil('\n');
}catch(Exception e){
System.err.println("Error initializing Serial port!\nPlease check connections and port settings");
e.printStackTrace();
}
}
void draw(){
background(0);
text("Press 'B' to read digital pin\nPress 'L' to read analog pin\n\n"+
"digital pin: " + digitalValue + "\nanalog pin: " + analogValue,10,25);
}
void keyReleased(){
if(key == 'B' || key == 'L'){
lastCMD = key;
println("sending command" + lastCMD);
if(arduino != null){
arduino.write(lastCMD);
}else println("Arduino is not initializing, not writing to serial port");
}
}
void serialEvent(Serial s){
String rawString = s.readString();
println("received arduino message" + rawString);
try{
rawString = rawString.trim();//remove any white space characters (if present)
if(lastCMD == 'B') digitalValue = int(rawString);
if(lastCMD == 'L') analogValue = int(rawString);
}catch(Exception e){
println("Error parsing String from serial port:");
e.printStackTrace();
}
}

Arduino Communicate with android through bluetooth

Currently i success to build the communication between the android device and arduino through bluetooth. As arduino will send string "ON" or "OFF" depend on the LED condition to Android through bluetooth and my android able to receive the string "LED:ARE:OFF" and "LED:ARE:ON" through the read() function. But currently i want to read a data by split the string into 3 from the LED, for example: "LED:ARE:OFF" into "LED" , "Are", "OFF" , but i failed to received the data. I had tried the String.split(":") to split out the aaa:bbb:ccc into 3 part, and it unable to read the data as well. Please help
Arduino Code:
#include <SoftwareSerial.h>// import the serial library
SoftwareSerial Genotronex(10, 11); // RX, TX
int ledpin=8; // led on D13 will show blink on / off
long previousMillis = 0; // will store last time LED was updated
long interval = 1000; // interval at which to blink (milliseconds)
int ledState = LOW; // ledState used to set the LED
long Counter=0; // counter will increase every 1 second
void setup() {
// put your setup code here, to run once:
Genotronex.begin(9600);
Genotronex.println("Bluetooth On please wait....");
pinMode(ledpin,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
Counter+=1;
delay(4000);
// if the LED is off turn it on and vice-versa:
if (ledState == LOW){
ledState = HIGH;
Genotronex.print("LED:ARE:ON");
digitalWrite(ledpin, ledState);
}
else{
ledState = LOW;
Genotronex.print("LED:ARE:OFF");
digitalWrite(ledpin, ledState);
}
// set the LED with the ledState of the variable:
}
}
Android Code:
btnSend.setOnClickListener(this);
int delay = 1000; // delay in ms
int period = 100; // repeat in ms
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
if (flag)
{
final byte data = read();
readMessageHandler.post(new Runnable()
{
public void run()
{
if (data != 1){
message = txtReceived.getText().toString() + (char)data;}
else{
message = "";
}
String message;
//New Code for split the data
String[] parts = message.split(":"); // escape .
String part0 = parts[0];
String part1 = parts[1];
String part2 = parts[2];
txtReceived.setText(part0);
//End of Split
// txtReceived.setText(Message);
}
});
}
}
}, delay, period);
private byte read()
{
byte dataRead = 0;
try
{
dataRead = (byte) inputStream.read();
}
catch(IOException readException)
{
toastText = "Failed to read from input stream: " + readException.getMessage();
Toast.makeText(Blood_Pressure.this, toastText, Toast.LENGTH_SHORT).show();
}
return dataRead;
}

Resources