Mpu6050 and Adafruit Ultimate Gps not working together on Arduino Due - gps

I have the codes for mpu6050 and adafruit ultimate gps breakout v3 and they are working fine seperately on arduino due but when i try to combine both the codes the gps does not get a fix. Can anybody help me out?
The code for mpu6050 is given below
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
extern TwoWire Wire1;
const int MPU_addr=0x68; // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
int minVal=265;
int maxVal=402;
double x;
double y;
double z;
double pitch,roll,delta_X,delta_Y,delta_Z;
double old_AcX=0;
double old_AcY=0;
double old_AcZ=0;
int led = 13;
void setup(){
Wire1.begin();
Wire1.beginTransmission(MPU_addr);
Wire1.write(0x6B); // PWR_MGMT_1 register
Wire1.write(0); // set to zero (wakes up the MPU-6050)
Wire1.endTransmission(true);
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop(){
Wire1.beginTransmission(MPU_addr);
Wire1.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire1.endTransmission(false);
Wire1.requestFrom(MPU_addr,14,true); // request a total of 14 registers
AcX=Wire1.read()<<8|Wire1.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY=Wire1.read()<<8|Wire1.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ=Wire1.read()<<8|Wire1.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp=Wire1.read()<<8|Wire1.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX=Wire1.read()<<8|Wire1.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY=Wire1.read()<<8|Wire1.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ=Wire1.read()<<8|Wire1.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
Serial.print("AcX = "); Serial.print(AcX);
Serial.print(" | AcY = "); Serial.print(AcY);
Serial.print(" | AcZ = "); Serial.print(AcZ);
Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53); //equation for temperature in degrees C from datasheet
Serial.print(" | GyX = "); Serial.print(GyX);
Serial.print(" | GyY = "); Serial.print(GyY);
Serial.print(" | GyZ = "); Serial.println(GyZ);
delay(1000);
}
And the code for the Adafruit ultimate Gps breakout is given below
#include <Adafruit_GPS.h>
#define mySerial Serial1
Adafruit_GPS GPS(&mySerial);
#define GPSECHO true
boolean usingInterrupt = false;
void useInterrupt(boolean); // Func prototype keeps Arduino 0023 happy
void setup()
{
Serial.begin(9600);
GPS.begin(9600);
mySerial.begin(9600);
GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);
GPS.sendCommand(PGCMD_ANTENNA);
#ifdef __arm__
usingInterrupt = false;
#else
useInterrupt(true);
#endif
delay(1000);
}
#ifdef __AVR__
SIGNAL(TIMER0_COMPA_vect) {
char c = GPS.read();
#ifdef UDR0
if (GPSECHO)
if (c) UDR0 = c;
// writing direct to UDR0 is much much faster than Serial.print
// but only one character can be written at a time.
#endif
}
void useInterrupt(boolean v) {
if (v) {
OCR0A = 0xAF;
TIMSK0 |= _BV(OCIE0A);
usingInterrupt = true;
} else {
// do not call the interrupt function COMPA anymore
TIMSK0 &= ~_BV(OCIE0A);
usingInterrupt = false;
}
}
#endif //#ifdef__AVR__
uint32_t timer = millis();
void loop()
{
if (! usingInterrupt) {
char c = GPS.read();
}
// if a sentence is received, we can check the checksum, parse it...
if (GPS.newNMEAreceived()) {
// a tricky thing here is if we print the NMEA sentence, or data
// we end up not listening and catching other sentences!
// so be very wary if using OUTPUT_ALLDATA and trytng to print out data
//Serial.println(GPS.lastNMEA()); // this also sets the newNMEAreceived() flag to false
if (!GPS.parse(GPS.lastNMEA())) // this also sets the newNMEAreceived() flag to false
return; // we can fail to parse a sentence in which case we should just wait for another
}
// if millis() or timer wraps around, we'll just reset it
if (timer > millis()) timer = millis();
// approximately every 2 seconds or so, print out the current stats
if (millis() - timer > 2000) {
timer = millis(); // reset the timer
Serial.print("\nTime: ");
Serial.print(GPS.hour, DEC); Serial.print(':');
Serial.print(GPS.minute, DEC); Serial.print(':');
Serial.print(GPS.seconds, DEC); Serial.print('.');
Serial.println(GPS.milliseconds);
Serial.print("Date: ");
Serial.print(GPS.day, DEC); Serial.print('/');
Serial.print(GPS.month, DEC); Serial.print("/20");
Serial.println(GPS.year, DEC);
Serial.print("Fix: "); Serial.print((int)GPS.fix);
Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
if (GPS.fix) {
//Serial.print("Location: ");
Serial.print(convertDegMinToDecDeg(GPS.latitude));
Serial.print(", ");
Serial.println(convertDegMinToDecDeg(GPS.longitude));
//Serial.print("Speed (knots): "); Serial.println(GPS.speed);
//Serial.print("Angle: "); Serial.println(GPS.angle);
//Serial.print("Altitude: "); Serial.println(GPS.altitude);
//Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
}
}
}
Both the codes are working fine separetely but i am unable to combine them and run in a single code.I tried to combine them and tha adafruit Ultimate gps breakout isn't working and it gives nothing. I want to know how i can combine them to work in a single code.Thanks in advance.

Use NeoGPS instead -- just add it to your IMU sketch:
#include <NMEAGPS.h>
NMEAGPS gps;
#define gpsPort Serial1
...
void setup(){
Wire1.begin();
Wire1.beginTransmission(MPU_addr);
Wire1.write(0x6B); // PWR_MGMT_1 register
Wire1.write(0); // set to zero (wakes up the MPU-6050)
Wire1.endTransmission(true);
Serial.begin(9600);
pinMode(led, OUTPUT);
gpsPort.begin( 9600 );
}
void loop(){
if (gps.available( gpsPort )) {
gps_fix fix = gps.read(); // A new GPS update is ready, get all the pieces
// Print some of the pieces?
Serial.print( F("Location: ") );
if (fix.valid.location) {
Serial.print( fix.latitude(), 6 );
Serial.print( ',' );
Serial.print( fix.longitude(), 6 );
}
Serial.print( F(", Altitude: ") );
if (fix.valid.altitude)
Serial.print( fix.altitude() );
Serial.println();
// Take an IMU sample too.
Wire1.beginTransmission(MPU_addr);
...
Serial.print(" | GyZ = "); Serial.println(GyZ);
}
}
This will display one GPS update and one IMU sample per second.
Also, you cannot use delay. The Arduino will not do anything else during the delay, and it will lose GPS characters. Notice that the above loop structure is always running, checking for GPS data. When a GPS update is finally ready, it takes the IMU sample and prints all the results.
You also have to be careful about printing too much information. Eventually, the Arduino will spend all its time waiting to print characters.
NeoGPS is available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries. NeoGPS is faster, smaller, more reliable and more accurate than all other GPS libraries, and the examples are properly structured. It is very common for the other libraries' examples to break when they are modified. Even if you don't use it, there is lots of information on the NeoGPS Installation and Troubleshooting pages.

Related

error message in order to connect arduino in bluetooth

(sorry for bad english)
I try to display the accelerometer data (x,y,z) from my arduino (33 ble sense) to my phone via bluetooth.
This is a project for school : it will be a hit captor for a boxer (put on a punching bag). Indeed, it will save the acceleration of the punching bag to finally convert it into "power" of hit .
To finally manage to convert this data into power of an athlete (a boxer) maybe with a function include in the programm later (F=m x acc).
I start with nrF connect for the beggining but i have to create a app with "MIT app inventor" later..
but now my code do not work. My code is here :
#include <ArduinoBLE.h>
#include <Arduino_LSM9DS1.h>
BLEService dataService("180C"); // User defined service
BLEStringCharacteristic dataCharacteristic("2A56", // standard 16-bit characteristic UUID
BLERead | BLENotify, 50); // remote clients will be able to read and subscribe to notifications
float oldX = 0.0; // last value
float oldY = 0.0;
float oldZ = 0.0;
long previousMillis = 0; // last time the value was checked, in ms
void setup()
{
Serial.begin(9600); // initialize serial communication
while (!Serial)
;
pinMode(LED_BUILTIN, OUTPUT); // initialize the built-in LED pin
if (!BLE.begin()) { // initialize BLE
Serial.println("starting BLE failed!");
while (1)
;
}
BLE.setLocalName("Sac de frappe"); // Set name for connection
BLE.setAdvertisedService(dataService); // Advertise service
dataService.addCharacteristic(dataCharacteristic); // Add characteristic to service
BLE.addService(dataService); // Add service
dataCharacteristic.setValue(String(oldX)); // Set data string
BLE.advertise(); // Start advertising
Serial.print("Peripheral device MAC: ");
Serial.println(BLE.address());
Serial.println("Waiting for connections...");
Serial.begin(9600);
while (!Serial);
Serial.println("Started");
if (!IMU.begin()) {
Serial.println("Failed to initialize IMU!");
while (1);
}
Serial.print("Accelerometer sample rate = ");
Serial.print(IMU.accelerationSampleRate());
Serial.println(" Hz");
Serial.println();
Serial.println("Acceleration in G's");
Serial.println("X\tY\tZ");
}
void loop()
{
BLEDevice central = BLE.central(); // Wait for a BLE central to connect
// if a central is connected to the peripheral:
if (central) {
Serial.print("Connected to central MAC: ");
// print the central's BT address:
Serial.println(central.address());
// turn on the LED to indicate the connection:
digitalWrite(LED_BUILTIN, HIGH);
// update value every 200ms
// while the central is connected:
while (central.connected()) {
long currentMillis = millis();
// if 200ms have passed, update value:
if (currentMillis - previousMillis >= 200) {
previousMillis = currentMillis;
updateValue();
}
}
}
// when the central disconnects, turn off the LED:
digitalWrite(LED_BUILTIN, LOW);
Serial.print("Disconnected from central MAC: ");
Serial.println(central.address());
}
void updateValue() {
float x, y, z;
if (!IMU.accelerationAvailable()) return; // Return if not ready
IMU.readAcceleration(x, y, z); // Read new data
if (x != oldX || y != oldY || z != oldZ) {
// print it
Serial.print(x);
Serial.print('\t');
Serial.print(y);
Serial.print('\t');
Serial.println(z);
dataCharacteristic.writeValue("X: " + (String(x)) + " Y: " (String(y)) + " Z: " + (String(z))); // update value
// save the value for next comparison
oldX = x;
oldY = y;
oldZ = z;
}
}
I have an error message : expression cannot be used as a function ... about this line : (void updateValue):
dataCharacteristic.writeValue("X: " + (String(x)) + " Y: " (String(y)) + " Z: " + (String(z))); // update value
and also in this line : (void setup)
dataCharacteristic.setValue(String(oldX)); // Set data string
How am i suppose to put the three value x, y and z ?
I can't fix it ... can you help me please ?
thanks
I already fixed my two mistakes in my answer to your last question
#include <ArduinoBLE.h>
#include <Arduino_LSM9DS1.h>
BLEService dataService("180C"); // User defined service
BLEStringCharacteristic dataCharacteristic("2A56", // standard 16-bit characteristic UUID
BLERead | BLENotify, 50); // remote clients will be able to read and subscribe to notifications
float oldX = 0.0; // last value
float oldY = 0.0;
float oldZ = 0.0;
long previousMillis = 0; // last time the value was checked, in ms
void setup()
{
Serial.begin(9600); // initialize serial communication
while (!Serial)
;
pinMode(LED_BUILTIN, OUTPUT); // initialize the built-in LED pin
if (!BLE.begin()) { // initialize BLE
Serial.println("starting BLE failed!");
while (1)
;
}
BLE.setLocalName("Sac de frappe"); // Set name for connection
BLE.setAdvertisedService(dataService); // Advertise service
dataService.addCharacteristic(dataCharacteristic); // Add characteristic to service
BLE.addService(dataService); // Add service
dataCharacteristic.setValue(""); // Set initial value
BLE.advertise(); // Start advertising
Serial.print("Peripheral device MAC: ");
Serial.println(BLE.address());
Serial.println("Waiting for connections...");
Serial.begin(9600);
while (!Serial);
Serial.println("Started");
if (!IMU.begin()) {
Serial.println("Failed to initialize IMU!");
while (1);
}
Serial.print("Accelerometer sample rate = ");
Serial.print(IMU.accelerationSampleRate());
Serial.println(" Hz");
Serial.println();
Serial.println("Acceleration in G's");
Serial.println("X\tY\tZ");
}
void loop()
{
BLEDevice central = BLE.central(); // Wait for a BLE central to connect
// if a central is connected to the peripheral:
if (central) {
Serial.print("Connected to central MAC: ");
// print the central's BT address:
Serial.println(central.address());
// turn on the LED to indicate the connection:
digitalWrite(LED_BUILTIN, HIGH);
// update value every 200ms
// while the central is connected:
while (central.connected()) {
long currentMillis = millis();
// if 200ms have passed, update value:
if (currentMillis - previousMillis >= 200) {
previousMillis = currentMillis;
updateValue();
}
}
}
// when the central disconnects, turn off the LED:
digitalWrite(LED_BUILTIN, LOW);
Serial.print("Disconnected from central MAC: ");
Serial.println(central.address());
}
void updateValue() {
float x, y, z;
if (!IMU.accelerationAvailable()) return; // Return if not ready
IMU.readAcceleration(x, y, z); // Read new data
if (x != oldX || y != oldY || z != oldZ) {
// print it
Serial.print(x);
Serial.print('\t');
Serial.print(y);
Serial.print('\t');
Serial.println(z);
dataCharacteristic.writeValue("X: " + String(x) + " Y: " + String(y) + " Z: " + String(z)); // update value
// save the value for next comparison
oldX = x;
oldY = y;
oldZ = z;
}
}

Updated--Issue with sensors connecting to Arduino Uno via Atlas Scientific hardware serial port expander 8:1

Hardware connection and also programming issue with sensors (GPS NEO-6M module, ESP8266 etc.) connecting to Arduino Uno via Atlas Scientific serial port expander 8:1
Hardware:
Arduino Uno
Atlas Scientific serial port expander 8:1
GPS NEO-6M module
ESP8266 Wifi module
Arduino Uno to GPS module we are able to get latitude and longitude values, below is the code for the same:
#include <SoftwareSerial.h>
#include <TinyGPS.h>
long lat, lon;
SoftwareSerial gpsSerial(6, 5);
TinyGPS gps;
void setup() {
Serial.begin(9600);
gpsSerial.begin(9600);
}
void loop() {
while (gpsSerial.available()) {
if (gps.encode(gpsSerial.read())) {
gps.get_position(&lat, &lon);
Serial.print("Position:");
Serial.print("lat:"); Serial.print(lat); Serial.print(" ");
Serial.print("long:"); Serial.println(lon);
}
}
}
Our requirement is that we have four sensors that need to be connected to an Arduino Uno. For that we used an Atlas Scientific hardware serial port expander 8:1.
Below is the code which we are working to get the GPS coordinates:
#include <SoftwareSerial.h> // we have to include the SoftwareSerial library, or else we can't use it
#define rx 8 // define what pin rx is going to be
#define tx 9 // define what pin tx is going to be
SoftwareSerial mySerial(rx, tx); //define how the soft serial port is going to work
int s1 = 6; // Arduino pin 6 to control pin S1
int s2 = 5; // Arduino pin 5 to control pin S2
int s3 = 4; // Arduino pin 4 to control pin S3
const uint8_t module_count = 8; // number of modules connected to the serial port expander 1=Port1, 2= Port2 and so on
void setup() {
Serial.begin(115200); // Set the hardware serial port to 115200
mySerial.begin(9600); // Set baud rate for the software serial port to 9600
pinMode(s1, OUTPUT); // Set the digital pin as output
pinMode(s2, OUTPUT); // Set the digital pin as output
pinMode(s3, OUTPUT); // Set the digital pin as output
}
void loop() {
if (Serial.available()) { // if we get data from the computer
char c = Serial.read();
for (uint8_t i = 1; i <= module_count; i++) { // loop through the modules
Serial.print("Connecting to Port: ");
Serial.println(i);
open_port(i); // open the port
mySerial.print(c); // print character to port
delay(100); // insert a delay to wait for the reply
if (mySerial.available()) { // print reply to serial monitor
while (mySerial.available()) {
Serial.println(mySerial.read());
if (gps.encode(mySerial.read())) {
gps.get_position(&lat, &lon);
Serial.print("Position:");
Serial.print("lat:"); Serial.print(lat);
Serial.print(" ");
Serial.print("long:"); Serial.println(lon);
}
}
}
else {
Serial.print("No response received");
}
Serial.println();
}
}
}
void open_port(uint8_t _port) { //this function controls what port is opened on the serial port expander
if (_port < 1 || module_count > 8)_port = 1; //if the value of the port is within range (1-8) then open that port. If it's not in range set it to port 1
uint8_t port_bits = _port - 1;
digitalWrite(s1, bitRead(port_bits, 0)); //Here we have two commands combined into one.
digitalWrite(s2, bitRead(port_bits, 1)); //The digitalWrite command sets a pin to 1/0 (high or low)
digitalWrite(s3, bitRead(port_bits, 2)); //The bitRead command tells us what the bit value is for a specific bit location of a number
delay(2); //this is needed to make sure the channel switching event has completed
}
Kindly guide us in sorting the issue; we are having an issue with gps.encode(mySerial.read()).
Thank you in advance.
Issue was sorted out by ourselves,
Below is the working code for the same ,
#include <SoftwareSerial.h> //we have to include the SoftwareSerial library, or else we can't use it
#define rx 3 //define what pin rx is going to be
#define tx 2 //define what pin tx is going to be
SoftwareSerial mySerial(rx, tx); //define how the soft serial port is going to work
#include <TinyGPS.h>
#include <NMEAGPS.h>
int s1 = 6; //Arduino pin 6 to control pin S1
int s2 = 5; //Arduino pin 5 to control pin S2
int s3 = 4; //Arduino pin 4 to control pin S3
int i;
const uint8_t module_count = 8; //number of modules connected to the serial port expander 1=Port1, 2= Port2 and so on
TinyGPS gps;
gps_fix fix;
long lat, lon;
void setup() {
Serial.begin(9600); //Set the hardware serial port to 115200
mySerial.begin(9600); //set baud rate for the software serial port to 9600
pinMode(s1, OUTPUT); //Set the digital pin as output
pinMode(s2, OUTPUT); //Set the digital pin as output
pinMode(s3, OUTPUT); //Set the digital pin as output
}
void loop() {
if (Serial.available()) { //if we get data from the computer
char c = Serial.read();
for (uint8_t i = 1; i <= module_count; i++) { // loop through the modules
Serial.print("Connecting to Port: ");
Serial.println(i);
open_port(i); // open the port
Serial.print(c); //print character to port
delay(1000); //insert a delay to wait for the reply
//Serial.println(Serial.available());
if (Serial.available()) {
//Serial.println(gps.available(Serial));//print reply to serial monitor
while (Serial.available()) {
//Serial.write(mySerial.read());
//Serial.write(gps.encode(mySerial.read()));
//Serial.println(mySerial.available());
//Serial.println(gps.encode(mySerial.read()));
if (mySerial.available()>0) {
//Serial.println(gps.encode(mySerial.read()));
char d = byte(mySerial.read());
//Serial.println(d);
if (gps.encode(d)) {
gps.get_position(&lat, &lon);
Serial.print("Position:");
Serial.print("lat:"); Serial.print(lat); Serial.print(" ");
Serial.print("long:"); Serial.println(lon);
}
}
}
Serial.println();
}
}
}
}
void open_port(uint8_t _port) { //this function controls what port is opened on the serial port expander
if (_port < 1 || module_count > 8)_port = 1; //if the value of the port is within range (1-8) then open that port. If it's not in range set it to port 1
uint8_t port_bits = _port - 1;
digitalWrite(s1, bitRead(port_bits, 0)); //Here we have two commands combined into one.
digitalWrite(s2, bitRead(port_bits, 1)); //The digitalWrite command sets a pin to 1/0 (high or low)
digitalWrite(s3, bitRead(port_bits, 2)); //The bitRead command tells us what the bit value is for a specific bit location of a number
delay(2); //this is needed to make sure the channel switching event has completed
}

User input stuck in loop

I have made this code on Arduino where the objective is to have the user type in a delay time into the serial monitor, and then the LED should be blink with that delay time. For example if I type in 1000 the LED should be turned on for 1 second then off for 1 second, then repeat.
My problem is that when the code has finished running once, it waits for a new user input, instead of continuing to blink. I think i have to take the Serial.parseInt out of the loop but i'm not sure how as every time I have tried to put it somewhere else the LED just lights up constantly.
Here is the code:
int ledPin = 13;
void setup() {
// put your setup code here, to run once:
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
Serial.print(" Enter delay time: ");
while (!Serial.available());
}
void loop() {
// put your main code here, to run repeatedly
int delayTime = Serial.parseInt();
digitalWrite(ledPin, HIGH);
delay(delayTime);
digitalWrite(ledPin, LOW);
delay(delayTime);
}
Serial.parseInt is a blocking function. That means it waits for valid serial input until it times out. Because of this, any other action in loop has to wait too. Reading user input in setup works only once though, so it never asks the user for input again.
To avoid this, you'll have to check the serial buffer, and then read each byte individually, while also doing the LED blinking in the main loop.
Another thing to avoid now, is the use of the delay function, because it also hangs the entire main loop (including the serial readings) for the given parameter time. You can still blink the LED by using timestamp intervals.
For a nice example of a non-blocking serial read, we can use this sample from the Arduino docs. Additionally, for another nice example of an LED-blinking sketch without using delay, we can use the BlinkWithoutDelay sample from the Arduino docs too.
String inString = "";
unsigned long previousMillis = 0;
int delayTime = 0;
int ledState = LOW;
int ledPin = 13;
void nonBlockingSerialReadDelayTime() {
while (Serial.available() > 0) {
int inChar = Serial.read();
if (isDigit(inChar)) {
// convert the incoming byte to a char and add it to the string
inString += (char)inChar;
}
// if you get a newline (user pressed ENTER on the serial console)
if (inChar == '\n') {
// set our new delay time
delayTime = inString.toInt();
// clear the string for new input
inString = "";
// ask user again
Serial.print(" Enter delay time: ");
}
}
}
void blinkLED() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= delayTime) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
// set the LED with the ledState of the variable
digitalWrite(ledPin, ledState);
}
}
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
while (!Serial.available());
Serial.print(" Enter delay time: ");
}
void loop() {
nonBlockingSerialReadDelayTime();
blinkLED();
}
Simply read the delay time in your setup befor you enter loop
int ledPin = 13;
int delayTime = 0;
void setup() {
// put your setup code here, to run once:
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
Serial.print(" Enter delay time: ");
while (!Serial.available());
delayTime = Serial.parseInt();
}
void loop() {
// put your main code here, to run repeatedly
digitalWrite(ledPin, HIGH);
delay(delayTime);
digitalWrite(ledPin, LOW);
delay(delayTime);
}
Sure Serial.parseInt() is blocking, but you can combine it with Serial.available()
const int ledPin = 13;
int delayTime = 1000;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
Serial.print(" Enter delay time: ");
}
void loop() {
digitalWrite(ledPin, HIGH);
delay(delayTime);
digitalWrite(ledPin, LOW);
delay(delayTime);
if (Serial.available()) {
int temp = Serial.parseInt();
if (temp > 0) delayTime = temp;
Serial.print(" Enter delay time: ");
}
}
Of course this approach does not allow to break into a very slow blink cycle immediately, but that's a different issue.

P5.js and Tone.js Can't Connect to Arduino

I'm having trouble displaying an image and playing audio using p5 when my arduino red led goes off. My arduino works, I just can't figure out how to get an image to pop up and audio to play when the red led goes off. My project is basically a motion sensor using an ultrasonic sensor, if that helps.
Thank you for your time.
Here's my sketch.js code:
var serial; // variable to hold an instance of the serialport library
var portName = '/dev/cu.usbmodem1421'; // fill in your serial port name here
var synth;
function preload() {
alert = loadImage('alert.jpeg');
}
function setup() {
createCanvas(1920,1080);
serial = new p5.SerialPort(); // make a new instance of the serialport
library
serial.on('list', printList); // set a callback function for the serialport
list event
serial.on('connected', serverConnected); // callback for connecting to the
server
serial.on('open', portOpen); // callback for the port opening
serial.on('data', serialEvent); // callback for when new data arrives
serial.on('error', serialError); // callback for errors
serial.on('close', portClose); // callback for the port closing
serial.list(); // list the serial ports
serial.open(portName); // open a serial port
var synth = new Tone.Synth().toMaster();
synth.triggerAttackRelease(440, 2);
var player = new Tone.Player("IntruderAlert.mp4").toMaster();
//play as soon as the buffer is loaded
player.autostart = true;
player.playbackRate = 0.8;
}
function serverConnected() {
println('connected to server.');
}
function portOpen() {
println('the serial port opened.')
}
function serialEvent() {
}
function serialError(err) {
println('Something went wrong with the serial port. ' + err);
}
function portClose() {
println('The serial port closed.');
}
Here's my .ino code:
#define trigPin 6<br>#define echoPin 7
#define GreenLED 11
#define YellowLED 10
#define RedLED 9
#define buzzer 3
int sound = 500;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(GreenLED, OUTPUT);
pinMode(YellowLED, OUTPUT);
pinMode(RedLED, OUTPUT);
pinMode(buzzer, OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/5) / 29.1;
if (distance < 50) {
digitalWrite(GreenLED, HIGH);
}
else {
digitalWrite(GreenLED, LOW);
}
if (distance < 20) {
digitalWrite(YellowLED, HIGH);
}
else {
digitalWrite(YellowLED,LOW);
}
if (distance < 5) {
digitalWrite(RedLED, HIGH);
sound = 1000;
}
else {
digitalWrite(RedLED,LOW);
}
if (distance > 5 || distance <= 0){
Serial.println("Out of range");
noTone(buzzer);
}
else {
Serial.print(distance);
Serial.println(" cm");
tone(buzzer, sound);
}
delay(300);
}
You're going to have to break your problem down into smaller steps and then approach those steps one at a time.
Can you create a sketch that just shows an image? Forget about the Arduino for a second, and just display an image. Now can you display an image when the user clicks on the screen?
Separately from that, can you write Arduino code that simply sends a message to a sketch when the red light goes off?
When you get those working independently, then it'll be much easier to think about combining them into a single application that combines both ideas.
If you get stuck, please post a MCVE of the specific step that you're stuck on, and we'll go from there. Good luck.

Sensor reading communication via bluetooth

I have two bluetooth modules(HC05) connected to separate arduinos. One acting as master and other as slave. One LDR is connected to the slave part which will be taking continuous readings and sending it to master via bluetooth.
The modules are successfully paired.I could even control an led connected to master using a pushbutton connected to slave.
Since 4 days I am struggling to get the readings of LDR on the serial monitor of master.
The slave part of the project(having the LDR):
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
#define ldrPin A0
int ldrValue = 0;
void setup() {
pinMode(9, OUTPUT); // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
digitalWrite(9, HIGH);
pinMode(ldrPin, INPUT);
BTSerial.begin(9600);
Serial.begin(9600);
}
void loop()
{
ldrValue = analogRead(ldrPin);
BTSerial.println(ldrValue);
Serial.println(ldrValue);
delay(1000);
}
The master part of the project which will be getting the reaings and displaying on serial monitor:
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
const byte numChars = 1024;
char receivedChars[numChars]; // an array to store the received data
boolean newData = false;
void setup() {
pinMode(9, OUTPUT); // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
digitalWrite(9, HIGH);
BTSerial.begin(9600);
Serial.begin(9600);
Serial.println("<Arduino is ready>");
}
void loop() {
recvWithEndMarker();
showNewData();
}
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = '\n';
char rc;
while (BTSerial.available() > 0 && newData == false) {
rc = BTSerial.read();
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
void showNewData() {
if (newData == true) {
Serial.print("This just in ... ");
Serial.println(receivedChars);
newData = false;
}
}
But the problem is that in the serial monitor only the highest digit ( 3 in 392) is displayed in the serial monitor. The readings are correct but the complete readings are not displayed.
The serial monitor showed something like this:
<Arduino is ready>
This just in ... 1
This just in ... 1
This just in ... 1
This just in ... 1
This just in ... 1
This just in ... 3
This just in ... 3
This just in ... 3
This just in ... 3
This just in ... 3
Ifin the Slave part instead of LDR readings if I am sending a string "hello", then it is printing as :
<Arduino is ready>
This just in ... h
This just in ... h
This just in ... h
This just in ... h
This just in ... h
This just in ... h
I have referred this link for serial communications Serial input basics
Can someone please help me out as I am new to arduino.
To read a string directly into a variable you can use:
BTSerial.readString()
instead of:
BTSerial.read()
like in the official documentation