using Ultrasonic sensor to find obstecles Arduino - arduino

Am trying to make a smart cane for blind ppl using 2 ultrasonic sensors
to detect obstacles, and use a buzzer and a flat vibrating motor as a feedback when an obstacle is detected, where the flat motor should be ON when an obstacle
between 1m - 3m is detected, and the buzzer when it's less than 1m.
now recently i used the NewPing library which solved some of the problems but
the code doesn't do exactly what i want, instead it triggers both the buzzer and motor together when object detected, i'd appreciate it if anyone could help.
#include <NewPing.h>
const int trigPin = 8;
const int trigPin1 = 13;
const int echoPin = 9;
const int echoPin1 = 12;
const int buzzer = 5;
const int motor = 3;
NewPing sonar1(trigPin,echoPin,maxout);
NewPing sonar2(trigPin1,echoPin1,maxout);
// defines variables
long duration;
long duration1;
int distance;
int distance1;
void setup() {
pinMode(buzzer, OUTPUT);
pinMode(motor, OUTPUT);
Serial.begin(9600);
}
void loop() {
distance = sonar1.ping_cm();
distance1 = sonar2.ping_cm();
if (distance > 100 || distance1 > 100) {
digitalWrite(buzzer,LOW);
digitalWrite(motor,HIGH);
}
else if (distance <= 100 || distance1 <= 100) {
digitalWrite(buzzer,HIGH);
digitalWrite(motor,LOW);
}
Serial.print("Distance1: ");
Serial.println(distance);
Serial.print("Distance2: ");
Serial.println(distance1);
}
this is the ultrasonic pins:
first sensor (Vcc = 5V, trig = 8, echo = 9, GND = GND)
second sensor(Vcc = 5V, trig = 13 , echo = 12 , GND = GND)
and this is the buzzer and motor pins:
buzzer = 5 , GND
motor = 3 , GND

Separate the logic for the motor and the buzzer:
if (distance >= 100 && distance <= 300) {
// Motor on
digitalWrite(motor, HIGH);
}
else {
// Motor off
digitalWrite(motor, LOW);
}
if (distance1 < 100) {
// Buzzer on
digitalWrite(buzzer, HIGH);
}
else {
// Buzzer off
digitalWrite(buzzer, LOW);
}

Related

Stepper motor does not work when used with ultrasonic sensor and step motor in Arduino

When the ultrasonic sensor determines that there is an object within a certain range, I want to make the step motor move once, but the step motor does not move. The step motor lights up, but I don't know what the problem is. Except for the conditional syntax and ultrasonic sensor, the step motor works well when you run the step motor.
The code is as follows:
#include <AccelStepper.h>
int a;
int trigPin4 = A1;
int echoPin4 = A2;
long duration4, distance4;
// Define step constants
#define FULLSTEP 4
#define HALFSTEP 8
#define motorPin1 8
#define motorPin2 9
#define motorPin3 10
#define motorPin4 11
#define motorPin5 4
#define motorPin6 5
#define motorPin7 6
#define motorPin8 7
AccelStepper stepper1(FULLSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
AccelStepper stepper2(FULLSTEP, motorPin5, motorPin7, motorPin6, motorPin8);
void setup()
{
pinMode(trigPin4, OUTPUT);
pinMode(echoPin4, INPUT);
Serial.begin(9600);
// 1 revolution Motor 1 CW
stepper1.setMaxSpeed(1000.0);
stepper1.setAcceleration(50.0);
stepper1.setSpeed(100);
stepper1.moveTo(2048);
// 1 revolution Motor 2 CCW
stepper2.setMaxSpeed(1000.0);
stepper2.setAcceleration(50.0);
stepper2.setSpeed(100);
stepper2.moveTo(-2048);
}
void loop()
{
digitalWrite(trigPin4, LOW);
delayMicroseconds(2);
digitalWrite(trigPin4, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin4, LOW);
duration4 = pulseIn(echoPin4, HIGH);
distance4 = duration4 * 0.034 / 2;
if (distance4 >= 500 || distance4 <= 0) {
Serial.println("Out of range");
}
else {
Serial.print("Sensor4 : ");
Serial.print(distance4);
Serial.println("cm");
a = 1;
}
if (a == 1) {
stepper1.run();
stepper2.run();
}
delay(2000);
}
first, do not use "delay" function.
Second, put a= 0 to the first if statement because in your code, once the distance satisfies the the else condition the value of a will remain 1 forever

Connection problem of ESP8266 ESP-01 arduino uno to cayenne

I am using the ESP8266 Wi-Fi shield to connect Arduino to the cayenne server. However once connect the chip to the access point it will heat up and sometimes will lagging. After that, it shows some message but the Cayenne server didn't connect to the Arduino. Every widget can not be operated (No response when clicking a button, temperature value unchanged, etc.). Can anyone solve this issue? It is important for my course work. I am using Arduino Uno and ESP8266 ESP-01 chip. We have tried different styles of code to upload data to cayenne server but they didn't work(Below include 3 versions)
Finale 1 Version(Cayenne out) :
#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266Shield.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <virtuabotixRTC.h>
//Real+Virtual
#define LED_PIN 5
#define temp_sensor 4
#define EspSerial Serial
//Virtual
#define Power_sensor 9
#define DayPower 10
#define MonthPower 11
#define LED_PWM 12
//SSID
char ssid[] = "TP-LINK_MWNg";
char password[] = "mwngpass";
char username[] = "743674368676328742somenumbers";
char mqtt_password[] = "743674368676328742somenumbers";
char client_id[] = "743674368676328742somenumbers";
ESP8266 wifi(&EspSerial);
//Temperature setup
OneWire oneWire(4);
DallasTemperature sensors(&oneWire);
//Power sensor
const int analogInPin = A0;
int sensorValue = 0; // value read from the pot
float MAXValue = 0; // value output to the PWM (analog out)
float Power = 0;
int PWM = 0;
//Time
int curSec = 0;
int curMin = 0;
int curHour = 0;
int curDay = 0;
virtuabotixRTC myRTC(6, 7, 8);
unsigned PowerInDay = 0;
unsigned PowerInMonth = 0;
void setup() {
// put your setup code here, to run once:
sensors.begin();
EspSerial.begin(115200);
delay(10);
Cayenne.begin(username, mqtt_password, client_id, wifi, ssid, password);
pinMode(LED_PIN, OUTPUT);
analogWrite(LED_PIN, PWM);
curSec = myRTC.seconds;
curMin = myRTC.minutes;
curHour = myRTC.hours;
curDay = myRTC.dayofmonth;
//test
}
void loop() {
Cayenne.loop();
myRTC.updateTime();
if ( curSec != myRTC.seconds ) {
PowerInDay += Power;
curSec = myRTC.seconds;
}
if (curDay != myRTC.dayofmonth) {
PowerInMonth += PowerInDay;
PowerInDay = 0;
curDay = myRTC.dayofmonth;
}
if (curDay > myRTC.dayofmonth) {
PowerInMonth = 0;
}
Serial.print(myRTC.dayofmonth);
Serial.print('/');
Serial.print(myRTC.month);
Serial.print('/');
Serial.print(myRTC.year);
Serial.print('/');
Serial.print(' ');
Serial.print(myRTC.hours);
Serial.print(':');
Serial.print(myRTC.minutes);
Serial.print(':');
Serial.print(myRTC.seconds);
Serial.print('\n');
Serial.print(PowerInDay);
Serial.print(' ');
Serial.print(PowerInMonth);
Serial.print('\n');
}
CAYENNE_OUT(temp_sensor)
{
sensors.requestTemperatures();
Cayenne.celsiusWrite(temp_sensor, sensors.getTempCByIndex(0));
}
CAYENNE_OUT(Power_sensor)
{
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
if (sensorValue > 0)
MAXValue = sensorValue * 0.00007307;
Power = MAXValue * ((float)PWM / (float)255) * 3.3 * ((float)PWM / (float)255);
// change the analog out value:/
// print the results to the serial monitor:
Serial.print("sensor = ");
Serial.print(sensorValue); //RAW value from analog read :)
Serial.print("\t output = ");
Serial.println(MAXValue * ((float)PWM / (float)255), 3); //Output the current
Serial.print("Power =");
Serial.println(Power, 3);
// wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(50);
Cayenne.virtualWrite(Power_sensor, Power, "pow", "w");
}
CAYENNE_OUT(DayPower) {
Cayenne.virtualWrite(DayPower, PowerInDay, "pow", "w");
}
CAYENNE_OUT(MonthPower) {
Cayenne.virtualWrite(MonthPower, PowerInMonth, "pow", "w");
}
CAYENNE_IN(LED_PIN)
{
int currentValue = getValue.asInt();
if (currentValue == 1) {
PWM = 255;
digitalWrite(LED_PIN, HIGH);
} else {
PWM = 0;
digitalWrite(LED_PIN, LOW);
}
//digitalWrite(Relay, HIGH);
//Process message here. If there is an error set an error message using getValue.setError(), e.g getValue.setError("Error message");
}
CAYENNE_IN(LED_PWM)
{
int value = getValue.asInt(); // 0 to 255
PWM = value;
analogWrite(LED_PIN, value);
}
Finale 2 Version(Cayenne out_Default):
#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266Shield.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <virtuabotixRTC.h>
//Real+Virtual
#define LED_PIN 5
#define temp_sensor 4
#define EspSerial Serial
//Virtual
#define Power_sensor 9
#define DayPower 10
#define MonthPower 11
#define LED_PWM 12
//SSID
char ssid[] = "TP-LINK_MWNg";
char password[] = "mwngpass";
char username[] = "743674368676328742somenumbers";
char mqtt_password[] = "743674368676328742somenumbers";
char client_id[] = "743674368676328742somenumbers";
ESP8266 wifi(&EspSerial);
//Temperature setup
OneWire oneWire(4);
DallasTemperature sensors(&oneWire);
//Power sensor
const int analogInPin = A0;
int sensorValue = 0; // value read from the pot
float MAXValue = 0; // value output to the PWM (analog out)
float Power = 0;
int PWM = 0;
//Time
int curSec = 0;
int curMin = 0;
int curHour = 0;
int curDay = 0;
virtuabotixRTC myRTC(6, 7, 8);
unsigned PowerInDay = 0;
unsigned PowerInMonth = 0;
void setup() {
// put your setup code here, to run once:
sensors.begin();
EspSerial.begin(115200);
delay(10);
Cayenne.begin(username, mqtt_password, client_id, wifi, ssid, password);
pinMode(LED_PIN, OUTPUT);
analogWrite(LED_PIN, PWM);
curSec = myRTC.seconds;
curMin = myRTC.minutes;
curHour = myRTC.hours;
curDay = myRTC.dayofmonth;
//test
}
void loop() {
Cayenne.loop();
myRTC.updateTime();
if ( curSec != myRTC.seconds ) {
PowerInDay += Power;
curSec = myRTC.seconds;
}
if (curDay != myRTC.dayofmonth) {
PowerInMonth += PowerInDay;
PowerInDay = 0;
curDay = myRTC.dayofmonth;
}
if (curDay > myRTC.dayofmonth) {
PowerInMonth = 0;
}
Serial.print(myRTC.dayofmonth);
Serial.print('/');
Serial.print(myRTC.month);
Serial.print('/');
Serial.print(myRTC.year);
Serial.print('/');
Serial.print(' ');
Serial.print(myRTC.hours);
Serial.print(':');
Serial.print(myRTC.minutes);
Serial.print(':');
Serial.print(myRTC.seconds);
Serial.print('\n');
Serial.print(PowerInDay);
Serial.print(' ');
Serial.print(PowerInMonth);
Serial.print('\n');
}
CAYENNE_OUT_DEFAULT()
{
//Temp sensor-----------------------------------------
sensors.requestTemperatures();
Cayenne.celsiusWrite(temp_sensor, sensors.getTempCByIndex(0));
//Temp sensor-----------------------------------------
//Power sensor-------------------------------------------------
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
if (sensorValue > 0)
MAXValue = sensorValue * 0.00007307;
Power = MAXValue * ((float)PWM / (float)255) * 3.3 * ((float)PWM / (float)255);
// change the analog out value:/
// print the results to the serial monitor:
Serial.print("sensor = ");
Serial.print(sensorValue); //RAW value from analog read :)
Serial.print("\t output = ");
Serial.println(MAXValue * ((float)PWM / (float)255), 3); //Output the current
Serial.print("Power =");
Serial.println(Power, 3);
// wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(50);
Cayenne.virtualWrite(Power_sensor, Power, "pow", "w");
//Power sensor-------------------------------------------------
//Power Day-------------------------------------------------
Cayenne.virtualWrite(DayPower, PowerInDay, "pow", "w");
//Power Month-------------------------------------------------
Cayenne.virtualWrite(MonthPower, PowerInMonth, "pow", "w");
}
CAYENNE_IN(LED_PIN)
{
int currentValue = getValue.asInt();
if (currentValue == 1) {
PWM = 255;
digitalWrite(LED_PIN, HIGH);
} else {
PWM = 0;
digitalWrite(LED_PIN, LOW);
}
//digitalWrite(Relay, HIGH);
//Process message here. If there is an error set an error message using getValue.setError(), e.g getValue.setError("Error message");
}
CAYENNE_IN(LED_PWM)
{
int value = getValue.asInt(); // 0 to 255
PWM = value;
analogWrite(LED_PIN, value);
}
Finale 3 Version(Send data with time difference):
#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266Shield.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <virtuabotixRTC.h>
//Real+Virtual
#define LED_PIN 5
#define temp_sensor 4
#define EspSerial Serial
//Virtual
#define Power_sensor 9
#define DayPower 10
#define MonthPower 11
#define LED_PWM 12
//SSID
char ssid[] = "TP-LINK_MWNg";
char password[] = "mwngpass";
char username[] = "743674368676328742somenumbers";
char mqtt_password[] = "743674368676328742somenumbers";
char client_id[] = "743674368676328742somenumbers";
ESP8266 wifi(&EspSerial);
//Temperature setup
OneWire oneWire(4);
DallasTemperature sensors(&oneWire);
//Power sensor
const int analogInPin = A0;
int sensorValue = 0; // value read from the pot
float MAXValue = 0; // value output to the PWM (analog out)
float Power = 0;
int PWM = 0;
//Time
int curSec = 0;
int curMin = 0;
int curHour = 0;
int curDay = 0;
virtuabotixRTC myRTC(6, 7, 8);
unsigned PowerInDay = 0;
unsigned PowerInMonth = 0;
int lastMillis = 0;
void setup() {
// put your setup code here, to run once:
sensors.begin();
EspSerial.begin(115200);
delay(10);
Cayenne.begin(username, mqtt_password, client_id, wifi, ssid, password);
pinMode(LED_PIN, OUTPUT);
analogWrite(LED_PIN, PWM);
curSec = myRTC.seconds;
curMin = myRTC.minutes;
curHour = myRTC.hours;
curDay = myRTC.dayofmonth;
//test
}
void loop() {
Cayenne.loop();
myRTC.updateTime();
if ( curSec != myRTC.seconds ) {
PowerInDay += Power;
curSec = myRTC.seconds;
}
if (curDay != myRTC.dayofmonth) {
PowerInMonth += PowerInDay;
PowerInDay = 0;
curDay = myRTC.dayofmonth;
}
if (curDay > myRTC.dayofmonth) {
PowerInMonth = 0;
}
// Serial.print(myRTC.dayofmonth);
// Serial.print('/');
// Serial.print(myRTC.month);
// Serial.print('/');
// Serial.print(myRTC.year);
// Serial.print('/');
// Serial.print(' ');
// Serial.print(myRTC.hours);
// Serial.print(':');
// Serial.print(myRTC.minutes);
// Serial.print(':');
// Serial.print(myRTC.seconds);
// Serial.print('\n');
// Serial.print(PowerInDay);
// Serial.print(' ');
// Serial.print(PowerInMonth);
// Serial.print('\n');
if(millis() - lastMillis > 10000 && millis() - lastMillis < 20000 ) {//Send data between 10 - 20 seconds
//Temp sensor-----------------------------------------
sensors.requestTemperatures();
Cayenne.celsiusWrite(temp_sensor, sensors.getTempCByIndex(0));
//Temp sensor-----------------------------------------
}
if(millis() - lastMillis > 20000 && millis() - lastMillis < 30000 ) {//Send data between 20 - 30 seconds
//Power sensor-------------------------------------------------
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
if (sensorValue > 0)
MAXValue = sensorValue * 0.00007307;
Power = MAXValue * ((float)PWM / (float)255) * 3.3 * ((float)PWM / (float)255);
// change the analog out value:/
// print the results to the serial monitor:
Serial.print("sensor = ");
Serial.print(sensorValue); //RAW value from analog read :)
Serial.print("\t output = ");
Serial.println(MAXValue * ((float)PWM / (float)255), 3); //Output the current
Serial.print("Power =");
Serial.println(Power, 3);
// wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(50);
Cayenne.virtualWrite(Power_sensor, Power, "pow", "w");
//Power sensor-------------------------------------------------
}
if(millis() - lastMillis > 30000 && millis() - lastMillis < 40000 ) {//Send data between 30 - 40 seconds
//Power Day-------------------------------------------------
Cayenne.virtualWrite(DayPower, PowerInDay, "pow", "w");
}
if(millis() - lastMillis > 40000 && millis() - lastMillis < 50000 ) {//Send data between 40 - 50 seconds
//Power Month-------------------------------------------------
Cayenne.virtualWrite(MonthPower, PowerInMonth, "pow", "w");
lastMillis = millis();
}
}
CAYENNE_IN(LED_PIN)
{
int currentValue = getValue.asInt();
if (currentValue == 1) {
PWM = 255;
digitalWrite(LED_PIN, HIGH);
} else {
PWM = 0;
digitalWrite(LED_PIN, LOW);
}
//digitalWrite(Relay, HIGH);
//Process message here. If there is an error set an error message using getValue.setError(), e.g getValue.setError("Error message");
}
CAYENNE_IN(LED_PWM)
{
int value = getValue.asInt(); // 0 to 255
PWM = value;
analogWrite(LED_PIN, value);
}
Serial monitor message:
AT
ATE0
AT+CIPMUX=1
AT+CWMODE?
AT+CWJAP="TP-LINK_MWNg","mwngpass"
[5618] Connected to WiFi
[5619] Connecting to mqtt.mydevices.com:1883
AT+CIPSTART=1,"TCP","mqtt.mydevices.com",1883
[15636] Network connect failed
AT+CIPSTART=1,"TCP","mqtt.mydevices.com",1883
AT+CIPSEND=1,40
MQIsdp
9c6b2/things/743674368676328742somenumbersAT+CIPSEND=1,16
e7f5ba423/cmd/+
AT+CIPSEND=1,40
AT+CIPSEND=1,40
AT+CIPSEND=1,40
AT+CIPSEND=1,40
1i Zv1/743674368676328742somenumbersAT+CIPSEND=1,40
6b2/things/743674368676328742somenumbersAT+CIPSEND=1,27
f5ba423/data/4temp,c=28.125sensor = 0 output = 0.000
Power =0.000
AT+CIPSEND=1,40
1g
If your module is getting warm its probably a hardwareissue.I guess you use 5V for the esp module which is bad as it only needs 3.3V. It might survive 5V for a short time(moment) but don't stretch your luck. So you have to convert 5V ro 3.3V level shifter. You can not use the Arduino 3.3V output pin because it can not provide the power needed by the ESP (up to 250mA) vs. max 50mA on the Arduino (UNO) 3.3V pin.
The schematic shortly explained:
The ESP's VCC pin is powered by the 3.3V output pin of the voltage regulator (AMS1117 in the grphic).
The 10uF capacitor is connected to the output pins to stabilize the regulator.
The CH_PD pin must also be connected to 3.3V.
The GND pin is obviously connected to ground.
The ESP's TXD pin can be connected directly to the RX pin of Arduino (emulated on pin 6).
The ESP's RXD pin is connected to the TX pin of Arduino (emulated on pin 7) through the level shifter.
The last two can be changed depending if you use hardware or software serial EDIT
As you use rtc it makes no sense to update the time every loop this will crash your connection. Either do it every x hours and make sure with if/else that nochyenne loop() is running. It makes no sense to sync time every x millis() the syncing of time every hourisenough foryour scenario, I would go for once a day

Motors With Arduino's

I have been working on getting some motors to work through H-bridges and managed to with this code.
// initialise motors
int enA = 3; // Motor 1
int in1 = 4;
int in2 = 2;
int enB = 5; // Motor 2
int in3 = 8;
int in4 = 7;
int enC = 11; // Motor 3
int in5 = 12;
int in6 = 13;
int enD = 6; // Motor 4
int in7 = 9;
int in8 = 10;
void setup()
{
pinMode(enA, OUTPUT); // set the outputs for motors
pinMode(enB, OUTPUT);
pinMode(enC, OUTPUT);
pinMode(enD, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
pinMode(in5, OUTPUT);
pinMode(in6, OUTPUT);
pinMode(in7, OUTPUT);
pinMode(in8, OUTPUT);
}
void motorLoop(){
// setting the direction to turn and speed
digitalWrite(in1, HIGH); // Motor 1
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH); // Motor 2
digitalWrite(in4, LOW);
digitalWrite(in5, HIGH); // Motor 3
digitalWrite(in6, LOW);
digitalWrite(in7, HIGH); // Motor 4
digitalWrite(in8, LOW);
// Set the speed for the Motors
analogWrite(enA, 1);
analogWrite(enB, 20);
analogWrite(enC, 100);
analogWrite(enD, 200);
};
void loop()
{
motorLoop();
delay(500);
}
However I am trying to turn the data into an array and have hit some issues.
I have never tried creating arrays with Digital inputs but have with Analog ones.
Here is a link to my project on (TinkerCAD) https://www.tinkercad.com/things/fFQKRTjhDrb-smashing-allis-kieran/editel?tenant=circuits?sharecode=6rKnUZsFtcOAetd_TufIuN8TfUgi8EupA1TMjlxiacM=
As you can see by this code I have tried to setup the enable inputs which show no errors but I am struggling setting up the OUTPUT and Speed that the motors rotate at.
// initialise motors
// Motor 1
int in1 = 4;
int in2 = 2;
// Motor 2
int in3 = 8;
int in4 = 7;
// Motor 3
int in5 = 12;
int in6 = 13;
// Motor 4
int in7 = 9;
int in8 = 10;
// Array of PWM's
int i = 0;
byte pwms[i] = {3,5,6,11};
byte numberPwms = 4;
void setup()
{
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
pinMode(in5, OUTPUT);
pinMode(in6, OUTPUT);
pinMode(in7, OUTPUT);
pinMode(in8, OUTPUT);
for(byte i = 0; i <= numberPwms; i++){
pinMode(pwms[i], OUTPUT);
};
}
void motorLoop(){
// setting the direction to turn and speed
digitalWrite(in1, HIGH); // Motor 1
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH); // Motor 2
digitalWrite(in4, LOW);
digitalWrite(in5, HIGH); // Motor 3
digitalWrite(in6, LOW);
digitalWrite(in7, HIGH); // Motor 4
digitalWrite(in8, LOW);
// Set the speed for the Motors
for(byte i = 0; i < numberPwms; i++){
analogWrite(pwms[i], 200);
};
};
void loop()
{
motorLoop();
delay(500);
}
Any help with this would be greatly appreciated :D
Your for loop counts 5 times. Try changing it to this:
for (byte i = 0; i < numberPwms; i++) {
pinMode(pwms[i], OUTPUT);
};
Also your array pwms[] is initialized with 0 elements, but should work anyway. But you can change it.
uint8_t pwms[] = {3, 5, 6, 11};

Arduino I2C Slave to Master communication problem

I am having a problem with reading random data in my Arduino Mega (Master) from my Arduino Uno (Slave) while using I2C communication.
Some background: I am reading Encoder data from the Uno and sending to the Mega via I2C communication. The encoder data is been used in the MEga to adjust the speed of a motor so that the revolutions per second of the different wheels have the same value.
The issue of reading random data arises when I include an IF condition or function.
Even if the IF condition included is an empty one or a call to function which has an empty body it starts to read random wrong data from the Uno.
If i don't have the adjusting part (IF condition/ function) of the code the reading of the data from the Uno works fine.
If anybody can help, it would be greatly appreciated.
Master Code:
#include <SoftwareSerial.h>
#include <SabertoothSimplified.h>
// Include the required Wire library for I2C<br>#include
#include <Wire.h>
// RX on pin 17 (to S2), TX on pin 16 (to S1).
SoftwareSerial SWSerial(NOT_A_PIN, 16);
// Use SWSerial as the serial port.
SabertoothSimplified ST(SWSerial);
//////////////////ENCODER DATA//////////////////
unsigned int revolutions_L_rpm = 0;
unsigned int revolutions_R_rpm = 0;
int16_t x = 0;
int16_t y = 0;
////////////////////////////////////////////////
//////////////VARIABLES FOR ADJUST//////////////
int error = 0;
int kp = 12;
int adjusted = 0;
////////////////////////////////////////////////
////////////////////MOTORS//////////////////////
//Declare the arduino pins
int LEDg = 7;
int LEDr = 6;
int LEDy = 5;
int speedVar = 0;
int speedOne = 0;
int speedTwo = 0;
int power;
////////////////////END/////////////////////////
void setup() {
//initlize the mode of the pins
pinMode(LEDg,OUTPUT);
pinMode(LEDr,OUTPUT);
pinMode(LEDy,OUTPUT);
//set the serial communication rate
Serial.begin(9600);
SWSerial.begin(9600);
Wire.begin();
}
void loop()
{
//check whether arduino is reciving signal or not
if(Serial.available() > 0){
char val = Serial.read();//reads the signal
Serial.print("Recieved: ");
Serial.println(val);
switch(val){
/*********Increase speed by 1 as long as e(triangle) is held*********/
case 'a':
forward();
break;
/*********Decrease speed by 1 as long as g(x) is held*********/
case 'c':
reverse();
break;
/*********Increase speed by 1 as long as e(triangle) is held*********/
case 'd':
turnLeft();
break;
/*********Decrease speed by 1 as long as g(x) is held*********/
case 'b':
turnRight();
break;
/*********Toggle when Circle is held for 5 seconds*********/
case 'f':
toggleSwitch(LEDy);
break;
/*********Toggle when Square is held for 5 seconds*********/
case 'h':
stopMotors();
break;
}
Serial.print("sppedVar = ");
Serial.print(speedVar);
Serial.print("\tleftSpeed: ");
Serial.print(speedOne);
Serial.print("\trightSpeed: ");
Serial.println(speedTwo);
}
Wire.requestFrom(9,4); // Request 4 bytes from slave arduino (9)
byte a = Wire.read();
Serial.print("a: ");
Serial.print(a);
byte b = Wire.read();
Serial.print(" b: ");
Serial.print(b);
byte e = Wire.read();
Serial.print(" --- e: ");
Serial.print(e);
byte f = Wire.read();
Serial.print(" f: ");
Serial.print(f);
x = a;
x = (x << 8) | b;
Serial.print("\tX: ");
Serial.print(x);
y = e;
y = (y << 8) | f;
Serial.print("\tY: ");
Serial.print(y);
revolutions_L_rpm = x;
revolutions_R_rpm = y;
if ((revolutions_L_rpm != revolutions_R_rpm) && (speedVar != 0)){
error = 0;
error = revolutions_L_rpm - revolutions_R_rpm;
adjusted = error/kp;
Serial.print("Error: ");
Serial.print(error);
Serial.print("Error/kp: ");
Serial.println(adjusted);
if ((speedTwo < 20) && (speedTwo > -20)){
speedTwo -= adjusted;
power = speedTwo;
ST.motor(2, -power);
//delay(20);
}
}
// Print out rpm
Serial.print("Left motor rps*100: ");
Serial.print(revolutions_L_rpm);
Serial.print(" ///// Right motor rps*100: ");
Serial.println(revolutions_R_rpm);
// Print out speed
Serial.print("speedOne: ");
Serial.print(speedOne);
Serial.print("\tspeedTwo: ");
Serial.println(speedTwo);
delay(1000);
}
Slave code:
// Include the required Wire library for I2C<br>#include <Wire.h>
#include <Wire.h>
// Checked for main program
volatile boolean counterReady;
// Internal to counting routine
unsigned int timerPeriod;
unsigned int timerTicks;
unsigned long overflowCount;
// The pin the encoder is connected
int encoder_in_L = 2;
int encoder_in_R = 3;
// The number of pulses per revolution
// depends on your index disc!!
unsigned int pulsesperturn = 16;
// The total number of revolutions
int16_t revolutions_L = 0;
int16_t revolutions_R = 0;
int16_t revolutions_L_rpm = 0;
int16_t revolutions_R_rpm = 0;
// Initialize the counter
int16_t pulses_L = 0;
int16_t pulses_R = 0;
byte myData[4];
// This function is called by the interrupt
void count_L() {
pulses_L++;
}
void count_R() {
pulses_R++;
}
void startCounting(unsigned int ms) {
counterReady = false; // time not up yet
timerPeriod = ms; // how many ms to count to
timerTicks = 0; // reset interrupt counter
overflowCount = 0; // no overflows yet
// Reset timer 2
TCCR2A = 0;
TCCR2B = 0;
// Timer 2 - gives us our 1 ms counting interval
// 16 MHz clock (62.5 ns per tick) - prescaled by 128
// counter increments every 8 µs.
// So we count 125 of them, giving exactly 1000 µs (1 ms)
TCCR2A = bit (WGM21) ; // CTC mode
OCR2A = 124; // count up to 125 (zero relative!!!!)
// Timer 2 - interrupt on match (ie. every 1 ms)
TIMSK2 = bit (OCIE2A); // enable Timer2 Interrupt
TCNT2 = 0; // set counter to zero
// Reset prescalers
GTCCR = bit (PSRASY); // reset prescaler now
// start Timer 2
TCCR2B = bit (CS20) | bit (CS22) ; // prescaler of 128
}
ISR (TIMER2_COMPA_vect){
// see if we have reached timing period
if (++timerTicks < timerPeriod)
return;
TCCR2A = 0; // stop timer 2
TCCR2B = 0;
TIMSK2 = 0; // disable Timer2 Interrupt
counterReady = true;
if(counterReady){
Serial.print("Pulses_L: ");
Serial.print(pulses_L);
Serial.print(" Pulses_R: ");
Serial.println(pulses_R);
// multiplying by 100 to get a greater difference to compare
revolutions_L_rpm = (pulses_L * 100) / pulsesperturn;
revolutions_R_rpm = (pulses_R * 100) / pulsesperturn;
// Total revolutions
// revolutions_L = revolutions_L + (pulses_L / pulsesperturn);
// revolutions_R = revolutions_R + (pulses_R / pulsesperturn);
pulses_L = 0;
pulses_R = 0;
}
}
void requestEvent() {
myData[0] = (revolutions_L_rpm >> 8) & 0xFF;
myData[1] = revolutions_L_rpm & 0xFF;
myData[2] = (revolutions_R_rpm >> 8) & 0xFF;
myData[3] = revolutions_R_rpm & 0xFF;
Wire.write(myData, 4); //Sent 4 bytes to master
}
void setup() {
Serial.begin(9600);
pinMode(encoder_in_L, INPUT);
pinMode(encoder_in_R, INPUT);
attachInterrupt(0, count_L, RISING); //attachInterrupt(digitalPinToInterrupt(encoder_in_L, count_L, RISING);
attachInterrupt(1, count_R, RISING); //attachInterrupt(digitalPinToInterrupt(encoder_in_R, count_R, RISING);
// Start the I2C Bus as Slave on address 9
Wire.begin(9);
// Attach a function to trigger when something is received.
Wire.onRequest(requestEvent);
}
void loop() {
// stop Timer 0 interrupts from throwing the count out
byte oldTCCR0A = TCCR0A;
byte oldTCCR0B = TCCR0B;
TCCR0A = 0; // stop timer 0
TCCR0B = 0;
startCounting (1000); // how many ms to count for
while (!counterReady)
{ } // loop until count over
// Print out rpm
Serial.print("Left motor rps: ");
Serial.println(revolutions_L_rpm);
Serial.print("Right motor rps: ");
Serial.println(revolutions_R_rpm);
// Print out revolutions
// Serial.print("Left motor revolution count: ");
// Serial.println(revolutions_L);
// Serial.print("Right motor revolution count: ");
// Serial.println(revolutions_R);
// restart timer 0
TCCR0A = oldTCCR0A;
TCCR0B = oldTCCR0B;
delay(200);
}

I m transmitting flex sensor values through serial port of arduino using Serial.print() function but I'm not able to read it at the receiving end

Actually in my code I'm transmitting accelerometer values as well as 4 flex sensor values. I have converted accelerometer value to 4 state as F(forward), B(backward),R(right),L(left). I am able to receive this 4 states and also I'm able to write code for these states. With these states I'm also sending flex sensor values to control servo motor remotely. But I'm not able to read those flex values as it is a varying integer. Please help me to read the flex values. I have tried Serial.read(), Serial.parseInt().
My transmitter code is:
int xpin = A0;
int x;
int ypin = A1;
int y;
int vcc=13;
const int flexpin1 = 2;
const int flexpin2 = 3;
const int flexpin3 = 4;
const int flexpin4 = 5;
int flex1[20];
int flex2[20];
int flex3[20];
int flex4[20];
int flexsum1=0;
int flexsum2=0;
int flexsum3=0;
int flexsum4=0;
char state1 = 'S';
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(flexpin1, INPUT);
pinMode(flexpin2, INPUT);
pinMode(flexpin3, INPUT);
pinMode(flexpin4, INPUT);
pinMode(xpin, INPUT);
pinMode(ypin, INPUT);
pinMode(vcc, OUTPUT);
digitalWrite(vcc, HIGH);
}
void loop() {
x = analogRead(xpin);
Serial.print("xpin=");
Serial.print(x);
y = analogRead(ypin);
Serial.print("\t ypin=");
Serial.print(y);
if ( y > 415)
{
state1 = 'F';
}
else if (y < 315)
{
state1 = 'B';
}
else if (x > 410)
{
state1 = 'R';
}
else if (x < 310)
{
state1 = 'L';
}
else {
state1 = 'S';
}
// flex readings stabelized//
for(int x=0; x<25; x++)
{
flex1[x]=analogRead(flexpin1);
flex2[x]=analogRead(flexpin2);
flex3[x]=analogRead(flexpin3);
flex4[x]=analogRead(flexpin4);
flexsum1=flexsum1+flex1[x];
flexsum2=flexsum2+flex2[x];
flexsum3=flexsum3+flex3[x];
flexsum4=flexsum4+flex4[x];
delayMicroseconds(20);
}
flexsum1=flexsum1/25;
flexsum2=flexsum2/25;
flexsum3=flexsum3/25;
flexsum4=flexsum4/25;
Serial.print("\t\t\tflexsum1= ");
Serial.print(flexsum1);
Serial.print("\tflexsum2= ");
Serial.print(flexsum2);
Serial.print("\tflexsum3= ");
Serial.print(flexsum3);
Serial.print("\tflexsum4= ");
Serial.print(flexsum4);
Serial.print("\t state1=");
Serial.println(state1);
delay(200);
}
My receiving code:
#include<Servo.h>
int IN1 = 13;
int IN2 = 12;
int IN3 = 7;
int IN4 = 6;
char state1 = 'S';
Servo servo1, servo2, servo3, servo4;
int flex1, flex2, flex3, flex4;
int angle1, angle2, angle3, angle4;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
servo1.attach(9);
servo2.attach(8);
servo3.attach(10);
servo4.attach(11);
}
void loop() {
// put your main code here, to run repeatedly:
while (Serial.available()) {
delay(10);
state1 = Serial.read();
Serial.print(state1);
switch (state1)
{
case 'F' : digitalWrite(IN1 , HIGH);
digitalWrite(IN2 , LOW);
digitalWrite(IN3 , HIGH);
digitalWrite(IN4 , LOW);
Serial.print("\tcar is moving forward ");
delay(100);
break;
case 'B' : digitalWrite(IN1 , LOW);
digitalWrite(IN2 , HIGH);
digitalWrite(IN3 , LOW);
digitalWrite(IN4 , HIGH);
Serial.print("\tcar is moving backward ");
delay(100);
break;
case 'L' : digitalWrite(IN1 , HIGH);
digitalWrite(IN2 , LOW);
digitalWrite(IN3 , LOW);
digitalWrite(IN4 , HIGH);
Serial.print("\tcar is turning left ");
delay(100);
break;
case 'R' : digitalWrite(IN1 , LOW);
digitalWrite(IN2 , HIGH);
digitalWrite(IN3 , HIGH);
digitalWrite(IN4 , LOW);
Serial.print("\tcar is turning right");
delay(100);
break;
case 'S' : digitalWrite(IN1 , LOW);
digitalWrite(IN2 , LOW);
digitalWrite(IN3 , LOW);
digitalWrite(IN4 , LOW);
delay(100);
break;
}
if (flex1 >= 845)
{
flex1 = Serial.read();
angle1 = map(flex1, 848, 1000, 0, 180);
angle1 = constrain(angle1, 0, 90);
servo1.write(angle1);
Serial.print("\tangle1=");
Serial.print(angle1);
delay(200);
}
if (flex2 >= 820)
{
flex2 = Serial.read();
angle2 = map(flex2, 825, 1000, 0, 180);
angle2 = constrain(angle2, 0, 90);
servo2.write(angle2);
Serial.print("\tangle2=");
Serial.print(angle2);
delay(200);
}
if (flex3 >= 770)
{
flex3 = Serial.read();
angle3 = map(flex3, 770, 930, 0, 180);
angle3 = constrain(angle3, 90, 180);
servo3.write(angle3);
Serial.print("\tangle3=");
Serial.print(angle3);
delay(200);
}
if (flex4 >= 870)
{
flex4 = Serial.read();
angle4 = map(flex4, 875, 1020, 0, 180);
angle4 = constrain(angle4, 90, 180);
servo4.write(angle4);
Serial.print("\tangle4=");
Serial.print(angle4);
delay(200);
}
}
}

Resources