How to add two physical buttons to AC fan dimmer sketch and update the corresponding slider/step widget once it’s pressed - nodemcu

There are a lot of AC Fan dimmer codes are available in internet with zero cross detection and runs by Blynk app as well.
Problem is All those are only controllable by wifi (with internet) , rather have no manual control (without internet) at all.
I share a code below for AC fan dimmer which is runs by blynk app (Board NodeMCU) . It is only runs when wifi is available, i.e it has no manual contro. I am trying to improve/modify the same code by adding two physical push buttons to control Fan speed manually when internet is not available. In this case I am unable to modify the codes for these two push buttons which also capable to increase and decrease the fan speed along with the Blynk app slider button. Can anyone help/Guide me to develop this.
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#define triacPulse 4 //D2
#define ZVC 12 //D6
int Slider_Value;
int dimming;
int x = 0;
char auth[] = "AUTH TOKEN"; // You should get Auth Token in the Blynk App.
char ssid[] = "SSID"; // Your WiFi credentials.
char pass[] = "PASS"; // Set password to "" for open networks.
BLYNK_WRITE(V1) // function to assign value to variable Slider_Value whenever slider changes position
{
Slider_Value = param.asInt(); // assigning incoming value from pin V1 to a variable
}
void setup()
{
pinMode(ZVC, INPUT_PULLUP);
//digitalWrite(2, INPUT_PULLUP); // pull up
pinMode(triacPulse, OUTPUT);
Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
attachInterrupt(digitalPinToInterrupt(ZVC), acon, FALLING); // attach Interrupt at PIN2
}
void loop()
{
Blynk.run();
// When the switch is closed
dimming = map(Slider_Value, 0, 100, 7200, 200);
}
void acon()
{
// Serial.println("REad");
delayMicroseconds(dimming); // read AD0
digitalWrite(triacPulse, HIGH);
delayMicroseconds(50); //delay 50 uSec on output pulse to turn on triac
digitalWrite(triacPulse, LOW);
// Serial.println(digitalRead(triacPulse));
}

Related

Using Ultrasonic sensor HC-SR04 and Gps (neogps 6m) together on arduino uno

I am trying to read data from both the sensor and the gps (one by one is ok). The sensors work well individually but the Ultrasonic sensor does not give any output. I am new to arduino so i just mixed the codes from the two examples using NewPing Library and TinyGPS libraries. Here is the code. Please suggest what additions need to be made to the code to make both devices work together.
/*********************
*10 to GPS Module TX*
*09 to GPS Module RX*
*********************/
// 1.TESTED USING LED
// 2. added ultrasound libraries
#include <NewPing.h>
#define TRIGGER_PIN 5 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 4 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
#include <SoftwareSerial.h>
#include <TinyGPS.h>
SoftwareSerial mySerial(10, 11);
TinyGPS gps;
float gpsdump(TinyGPS &gps);
void setup()
{
// Oploen serial communications and wait for port to open:
Serial.begin(9600);
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
delay(1000);
}
void loop() // run over and over
{
bool newdata = false;
unsigned long start = millis();
// Every 5 seconds we print an update
while (millis() - start < 5000)
{
if (mySerial.available())
{
char c = mySerial.read();
//Serial.print(c); // uncomment to see raw GPS data
if (gps.encode(c))
{
newdata = true;
break; // uncomment to print new data immediately!
}
}
}
if (newdata)
{
Serial.println("Acquired Data");
Serial.println("-------------");
gpsdump(gps);
Serial.println("-------------");
Serial.println();
}
}
float gpsdump(TinyGPS &gps)
{
// On Arduino, GPS characters may be lost during lengthy Serial.print()
// On Teensy, Serial prints to USB, which has large output buffering and
// runs very fast, so it's not necessary to worry about missing 4800
// baud GPS characters.
Serial.println("speed");
Serial.println(gps.f_speed_kmph()) ;
Serial.print(sonar.ping_cm());
;
}
The main problems:
You cannot wait 5 seconds without processing the characters. The Arduino receive buffer only has room for 64 characters. The GPS device could have sent 5000 characters during that time, so most of them will get dropped. This prevents the GPS library from ever parsing a complete sentence.
A ping will interfere with software serial ports. You will have to wait for the GPS quiet time to do the ping. Otherwise, the ping process will cause characters to be lost.
Other problems:
You are printing the speed value even though it may not be valid. If you are not moving, or you do not have good satellite reception, the GPS device may not provide a speed.
The Arduino millis() clock will not be synchronized with the GPS clock. You could use the GPS updates as an exact 1-second clock. Simply count 5 fixes as they arrive, and this will mean that 5 seconds have elapsed.
You should use a different serial port and/or library.
This answer describes the various choices: HardwareSerial (i.e. Serial on pins 0 & 1), AltSoftSerial (8 & 9 on an UNO) or NeoSWSerial (any two pins).
Here is a NeoGPS version of your sketch that addresses these issues:
/*********************
*10 to GPS Module TX*
*09 to GPS Module RX*
*********************/
// 1.TESTED USING LED
// 2. added ultrasound libraries
#include <NewPing.h>
#define TRIGGER_PIN 5 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 4 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
#include <NeoSWSerial.h>
#include <NMEAGPS.h>
NeoSWSerial gpsPort(10, 11);
NMEAGPS gps; // the parser
gps_fix fix; // all the parsed values from GPS
uint8_t fixCount = 0; // a one-second "clock"
float gpsdump();
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
// set the data rate for the SoftwareSerial port
gpsPort.begin(9600);
delay(1000);
}
void loop() // run over and over
{
// Check for available GPS characters and parse them
if (gps.available( gpsPort ))
{
// Once per second, a complete fix structure is ready.
fix = gps.read();
fixCount++;
// The GPS device is going to be quiet for a while,
// *now* is a good time to do a ping.
Serial.print( "ping " );
Serial.println( sonar.ping_cm() );
// Every 5 seconds we print an update
if (fixCount >= 5)
{
fixCount = 0; // reset counter
Serial.println("Acquired Data");
Serial.println("-------------");
gpsdump();
Serial.println("-------------");
Serial.println();
}
}
}
float gpsdump()
{
// On Arduino, GPS characters may be lost during lengthy Serial.print()
// On Teensy, Serial prints to USB, which has large output buffering and
// runs very fast, so it's not necessary to worry about missing 4800
// baud GPS characters.
Serial.println("speed ");
if (fix.valid.speed)
Serial.println( fix.speed_kph() );
}
If you want to try it, NeoGPS, AltSoftSerial and NeoSWSerial are available from the IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries. NeoGPS is smaller, faster, more reliable and more accurate than all other libraries.
Even if you don't use it, there are many suggestions on the Installation and Troubleshooting pages.

Eliminating noise from sensor readings on CC3200?

step by step what I did so far
1) micro controller used CC3200 from Texas instruments ( wifi builted micro controller)
2) Conductive rubber cord stretch sensor - connected to Microcontroller's analog pin
**Sensor's behaviour = ( resistance increases upon stretching the conductive rubber)
So now, following is the code fo reference which I debugged in to the microcontroller to run the sensor(Using energia tool-IDE).
The code is nothing but written for the web server( which I gave- available wifi ssid and password-which you can see in the following programm "iPhone and the passowrd"), where the sensor's code is also wrote in to,
And this webserver reads and generates IP address of the microcontroller and also values of the stretch sensor.
Webserver code :
#include <SPI.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
// which analog pin to connect
#define RUBBERPIN A3
// how many samples to take and average, more takes longer
// but is more 'smooth'
#define NUMSAMPLES 5
// the value of the 'other' resistor
#define SERIESRESISTOR 10000
int samples[NUMSAMPLES];
// your network name also called SSID
char ssid[] = "iPhone";
// your network password
char password[] = "123456789";
// your network key Index number (needed only for WEP)
int keyIndex = 0;
WiFiServer server(3000);
void setup() {
Serial.begin(115200); // initialize serial communication
analogReference(EXTERNAL);
pinMode(RED_LED, OUTPUT); // set the LED pin mode
// attempt to connect to Wifi network:
Serial.print("Attempting to connect to Network named: ");
// print the network name (SSID);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP
network:
WiFi.begin(ssid, password);
while ( WiFi.status() != WL_CONNECTED) {
// print dots while we wait to connect
Serial.print(".");
delay(300);
}
Serial.println("\nYou're connected to the network");
Serial.println("Waiting for an ip address");
while (WiFi.localIP() == INADDR_NONE) {
// print dots while we wait for an ip addresss
Serial.print(".");
delay(300);
}
// you're connected now, so print out the status
printWifiStatus();
Serial.println("Starting dataerver on port 3000");
server.begin(); // start the web server on port
80
Serial.println("Dataserver started!");
}
void loop() {
// listen for incoming clients
WiFiClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
uint8_t i;
float average;
// take N samples in a row, with a slight delay
for (i=0; i< NUMSAMPLES; i++) {
samples[i] = analogRead(RUBBERPIN);
delay(10);
}
// average all the samples out
average = 0;
for (i=0; i< NUMSAMPLES; i++) {
average += samples[i];
}
average /= NUMSAMPLES;
Serial.println(average);
client.println(average);
delay(10);
}
delay(1);
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("Network Name: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
After running this programm it generates IP address and sensor's values(
221.40
221.20
221.20
*********here = value missing were a noise is visible on graph
221.00
221.20
221.40
221.00
221.20
221.40
221.00
221.40
221.20
221.40
221.20
221.00
221.00
221.60
221.00
221.20
*********here = value missing were a noise is visible on graph
221.20
221.00
Now,
I wrote the generated IP address in to a client programm (In the tool- named processing.org )
Here is my client code
import processing.net.*;
Client c;
String input;
int data[];
int posx;
void setup()
{
size(1000, 500);
background(204);
stroke(0);
frameRate(5); // Slow it down a little
// Connect to the server's IP address and port
c = new Client(this, "192.168.23.2", 3000); // Replace with your server's IP
and port
posx =2;
data = new int[3];
}
void draw()
{
posx++;
// Receive data from server
if (c.available() > 0) {
input = c.readString();
input = input.substring(0, input.indexOf("\n")); // Only up to the newline
println(input);
data[0]=data[1];
data[1] = int(input); // Split values into an array
// Draw line using received coords
stroke(0);
line(posx-1, data[0]+10, posx, data[1]+10);
}
}
My results after running the following programm:
Server sending the data and client receiving the data wirelessly- its all fine
I am able to see the output signal which I am expecting. i.e., when my sensor is in rest position the output must be straight line and if I stretch my sensor the voltage signal must increase- Iam able to see all these. But,
here is a small problem
There is a noise coming out from the output signal (please have a look in to the following picture.)
Noise
So my problem is even when the sensor is in rest position- with out any stretch- there is peak coming out.
please help me

can't pair mac and arduino fio with bluetooth bee

I can't get my arduino fio with bluetooth bee paired with my mac. I got my application working with a different board (arduino uno) and USB connection. The code I'm uploading to my arduino fio is below:
#include <SoftwareSerial.h>
SoftwareSerial softSerial(2, 3); // RX, TX
void setup() {
// bluetooth bee setup
softSerial.print("\r\n+STWMOD=0\r\n"); // set to slave
delay(1000);
softSerial.print("\r\n+STNA=MYAPP\r\n"); // set name
delay(1000);
// Serial.print("\r\n+STAUTO=1\r\n"); // permit auto-connect of paired devices
softSerial.print("\r\n+STOAUT=1\r\n");
delay(1000);
//Serial.print("\r\n +STPIN=0000\r\n"); // set PIN
//delay(1000);
softSerial.print("\r\n+STBD=9600\r\n"); // set baud
delay(2000); // required
// initiate BTBee connection
softSerial.print("\r\n+INQ=1\r\n");
delay(20000); // wait for pairing
// Start the software serial.
softSerial.begin(9600);
// Start the hardware serial.
Serial.begin(9600);
}
I think the pins are right -- 2 and 3 seem to be the pins that connect to the bluetooth bee. I've been googling for 2 days straight, and people don't seem to have problems pairing. What am I doing wrong?
Thanks,
Ok -- this took me nearly three solid days of Google-fu, and I stumbled across this page. Apparently that guy, also, had an immense amount of trouble finding a solution, so hopefully having the solution posted on StackOverflow will help future inquirers.
Really, two things are necessary. First, for whatever reason, I have no idea why, you don't worry about the "software serial". Just address the "Serial". Secondly, it will not work if you don't have the baud for the Serial at 38400. I'm actually using a "software serial" to talk to another device, and that baud is at 9600, but for the bluetooth Serial, you want it at 38400.
If you define "setup" as follows, the BluetoothBee should blink red and green, and pair (mac has nothing to do with it):
long DATARATE = 38400; // default data rate for BT Bee
char inChar = 0;
int LED = 13; // Pin 13 is connected to a LED on many Arduinos
void setup() {
Serial.begin(DATARATE);
// bluetooth bee setup
Serial.print("\r\n+STWMOD=0\r\n"); // set to slave
delay(1000);
Serial.print("\r\n+STNA=myDeviceName\r\n"); // set the device name
delay(1000);
Serial.print("\r\n+STAUTO=0\r\n"); // don't permit auto-connect
delay(1000);
Serial.print("\r\n+STOAUT=1\r\n"); // existing default
delay(1000);
Serial.print("\r\n +STPIN=0000\r\n"); // existing default
delay(2000); // required
// initiate BTBee connection
Serial.print("\r\n+INQ=1\r\n");
delay(2000); // wait for pairing
pinMode(LED, OUTPUT);
}
Then, after pairing you should see another serial port under 'tools -> serial port' in your Arduino IDE. If you select that and define the "loop" function as follows, you should be able to send those commands and get verification that you are, in fact, talking to the bluetooth bee:
void loop() {
// test app:
// wait for character,
// a returns message, h=led on, l=led off
if (Serial.available()) {
inChar = Serial.read();
if (inChar == 'a') {
Serial.print("connected"); // test return connection
}
if (inChar == 'h') {
digitalWrite(LED, HIGH); // on
}
if (inChar == 'l') {
digitalWrite(LED, LOW); // off
}
}
}

Arduino/MPU6050/AdafruitMotorShieldV2: script hangs/freezes when turn on motors

I'm a newby to robotics and electronics in general, so please don't assume I tried anything you might think is obvious.
I'm trying to create a cart which will basically run around by itself (simple AI routines to avoid obstacles, go from pt. A to pt. B around corners, follow lines, etc.). I'm putting together an Adafruit Arduino Uno R3 with the Adafruit Motor Shield v2 and an MPU-6050. I'm using the "breadboard" on the Motor Shield for the circuitry, soldering everything there.
I can get all the pieces working independently with their own scripts: the Motor Shield drives the 4 motors as expected using the Adafruit library; I'm using the "JRowberg" library for the MPU-6050, and started with the example MPU6050_DMP6.ino, which works fine as long as the cart motors are turned off. My only changes in the example script below are motor startup and some simple motor commands.
As long as I leave the switch which powers the motors off, everything seems fine: it outputs to the Serial window continuously with Euler data which, I assume, is correct. However, a few seconds after I turn on the power to the motors (and the wheels start turning), it just hangs/freezes: the output to the Serial window stops (sometimes in mid-line), and the wheels keep turning at the speed of their last change. Sometimes I see "FIFO overflow" errors, but not always. Sometimes I see "nan" for some of the floating point values before it hangs, but not always.
Some things I've tried, all of which changed noting:
* I've swapped out the MPU-6050 board for another from the same manufacturer.
* I've tried moving the MPU-6050 away from the motors using a ribbon cable.
* I've changed the I2C clock using JRowber's advice (a change in a .h file and changing the value of the TWBR variable), but I don't think I've tried all possible values.
* I've changed the speed of the MotorShield in the AFMS.begin() command, although, again, there are probably other values I haven't tried, and I'm not sure how in-sync this and the TWBR value need to be.
And some other things, all to no avail.
Below is an example script which fails for me:
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
#include "Adafruit_MotorShield.h"
#include "utility/Adafruit_PWMServoDriver.h"
#define DEBUG 1
MPU6050 mpu;
#define OUTPUT_READABLE_EULER
#define LED_PIN 13
bool blinkState = false;
bool dmpReady = false; // set true if DMP init was successful
uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount; // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer
Quaternion q; // [w, x, y, z] quaternion container
VectorInt16 aa; // [x, y, z] accel sensor measurements
VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements
VectorFloat gravity; // [x, y, z] gravity vector
float euler[3]; // [psi, theta, phi] Euler angle container
float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
#define NUM_MOTORS 4
#define MOTOR_FL 0
#define MOTOR_FR 1
#define MOTOR_RR 2
#define MOTOR_RL 3
Adafruit_DCMotor *myMotors[NUM_MOTORS] = {
AFMS.getMotor(1),
AFMS.getMotor(2),
AFMS.getMotor(3),
AFMS.getMotor(4),
};
#define CHANGE_SPEED_TIME 500
long changeSpeedMillis = 0;
int curSpeed = 30;
volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}
void setup() {
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
Serial.begin(115200);
while (!Serial); // wait for Leonardo enumeration, others continue immediately
// start the motor shield.
AFMS.begin(); // create with the default frequency 1.6KHz
// AFMS.begin(4000); // OR with a different frequency, say 4KHz
// kill all the motors.
myMotors[MOTOR_FL]->run(BRAKE);
myMotors[MOTOR_FL]->setSpeed(0);
myMotors[MOTOR_FR]->run(BRAKE);
myMotors[MOTOR_FR]->setSpeed(0);
myMotors[MOTOR_RR]->run(BRAKE);
myMotors[MOTOR_RR]->setSpeed(0);
myMotors[MOTOR_RL]->run(BRAKE);
myMotors[MOTOR_RL]->setSpeed(0);
Serial.println("Motor Shield ready!");
Serial.println(F("Initializing I2C devices..."));
mpu.initialize();
// verify connection
Serial.println(F("Testing device connections..."));
Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
// wait for ready
Serial.println(F("\nSend any character to begin DMP programming and demo: "));
while (Serial.available() && Serial.read()); // empty buffer
while (!Serial.available()); // wait for data
while (Serial.available() && Serial.read()); // empty buffer again
// load and configure the DMP
Serial.println(F("Initializing DMP..."));
devStatus = mpu.dmpInitialize();
// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXGyroOffset(220);
mpu.setYGyroOffset(76);
mpu.setZGyroOffset(-85);
mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
// make sure it worked (returns 0 if so)
if (devStatus == 0) {
// turn on the DMP, now that it's ready
Serial.println(F("Enabling DMP..."));
mpu.setDMPEnabled(true);
// enable Arduino interrupt detection
Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
attachInterrupt(0, dmpDataReady, RISING);
mpuIntStatus = mpu.getIntStatus();
// set our DMP Ready flag so the main loop() function knows it's okay to use it
Serial.println(F("DMP ready! Waiting for first interrupt..."));
dmpReady = true;
// get expected DMP packet size for later comparison
packetSize = mpu.dmpGetFIFOPacketSize();
} else {
// ERROR!
// 1 = initial memory load failed
// 2 = DMP configuration updates failed
// (if it's going to break, usually the code will be 1)
Serial.print(F("DMP Initialization failed (code "));
Serial.print(devStatus);
Serial.println(F(")"));
}
// configure LED for output
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// if programming failed, don't try to do anything
if (!dmpReady) return;
// wait for MPU interrupt or extra packet(s) available
while (!mpuInterrupt && fifoCount < packetSize) {
// as per Vulpo's post.
delay(10);
if (millis() > changeSpeedMillis) {
curSpeed += 20;
if (curSpeed > 256) {
curSpeed = 30;
}
Serial.print("changing speed to: ");
Serial.println(curSpeed);
myMotors[MOTOR_FL]->run(FORWARD);
myMotors[MOTOR_FL]->setSpeed(curSpeed);
myMotors[MOTOR_FR]->run(FORWARD);
myMotors[MOTOR_FR]->setSpeed(curSpeed);
myMotors[MOTOR_RR]->run(FORWARD);
myMotors[MOTOR_RR]->setSpeed(curSpeed);
myMotors[MOTOR_RL]->run(FORWARD);
myMotors[MOTOR_RL]->setSpeed(curSpeed);
changeSpeedMillis = millis() + CHANGE_SPEED_TIME;
}
}
// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();
// get current FIFO count
fifoCount = mpu.getFIFOCount();
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
Serial.println(F("FIFO overflow!"));
// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
// read a packet from FIFO
mpu.getFIFOBytes(fifoBuffer, packetSize);
// track FIFO count here in case there is > 1 packet available
// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
#ifdef OUTPUT_READABLE_EULER
// display Euler angles in degrees
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetEuler(euler, &q);
Serial.print("euler\t");
Serial.print(euler[0] * 180/M_PI);
Serial.print("\t");
Serial.print(euler[1] * 180/M_PI);
Serial.print("\t");
Serial.println(euler[2] * 180/M_PI);
#endif
// blink LED to indicate activity
blinkState = !blinkState;
digitalWrite(LED_PIN, blinkState);
}
}
Have you considered that your troubles are caused by interference from the currents flowing into your motors?
If your motors are DC brush, then more interference may be radiated from the brushes back into your various wires.
As a first step, perhaps let only one motor work and see if hangups diminish in frequency (although, to be sure, you need a 'scope onto a few wires carrying logic signals.

Arduinos IDE Serial Monitor works while XCode popen() does not.

I am trying to communicate with my Arduino through popen() function. I wrote a simple Mac App in XCode:
- (IBAction)ButtonPressed:(id)sender {
popen("echo hello world > /dev/tty.usbmodem1411", "r");
}
And here is the Arduino Code:
int redPin = 8;
int greenPin = 9;
int bluePin = 10;
int inByte = 0; // for incoming serial data
void setup()
{
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Serial.begin(8000);
}
void loop()
{
if (Serial.available() > 0) {
// get incoming byte:
inByte = Serial.read();
Serial.print(inByte);
setColor(inByte,inByte,inByte);
delay(1000);
setColor(0,0,0);
}
}
void setColor(int red, int green, int blue)
{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}
Now, when I try to use Arduino Serial Monitor and write some gibberish there my LED's light up fine and I see that it is working. When I run my XCode program, press the button, nothing happens. I did set break points and I did check that the line of code gets executed. I double checked the serial port, it is all fine, but no luck. It still does not work.
Basically I solved the problem by using IOKit/ioctl. I am still not sure why popen() did not work, might be because Arduino IDE was using the port and thus it was not available, however IOKit works like a charm. Plus it allows more control and flexibility, you can actually search for ports before you start and see if they are available. If anyone runs in to the same problem check http://playground.arduino.cc/Interfacing/Cocoa#IOKit. Thanks for all help.

Resources