Arduino - deleting variables after radio send doesn't work - arduino

I have tried so hard but i just can't understand why the two lines in my Tx code :
inputString = "";
stringComplete = false;
Stop my radio is working.
If I delete this code, it just keeps sending the values over and over without being able to stop it.
Tx:
/* YourDuinoStarter Example: nRF24L01 Transmit Joystick values
- WHAT IT DOES: Reads Analog values on A0, A1 and transmits
them over a nRF24L01 Radio Link to another transceiver.
- SEE the comments after "//" on each line below
- CONNECTIONS: nRF24L01 Modules See:
http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
1 - GND
2 - VCC 3.3V !!! NOT 5V
3 - CE to Arduino pin 9
4 - CSN to Arduino pin 10
5 - SCK to Arduino pin 13
6 - MOSI to Arduino pin 11
7 - MISO to Arduino pin 12
8 - UNUSED
-
Analog Joystick or two 10K potentiometers:
GND to Arduino GND
VCC to Arduino +5V
X Pot to Arduino A0
Y Pot to Arduino A1
- V1.00 11/26/13
Based on examples at http://www.bajdi.com/
Questions: terry#yourduino.com */
/*-----( Import needed libraries )-----*/
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
/*-----( Declare Constants and Pin Numbers )-----*/
#define CE_PIN 9
#define CSN_PIN 10
// NOTE: the "LL" at the end of the constant is "LongLong" type
const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe
/*-----( Declare objects )-----*/
RF24 radio(CE_PIN, CSN_PIN); // Create a Radio
/*-----( Declare Variables )-----*/
String inputString = "";
boolean stringComplete = false;
int msg[1]; // 2 element array holding Joystick readings
int msgNum = 0;
void setup() /****** SETUP: RUNS ONCE ******/
{
Serial.begin(9600);
radio.begin();
radio.openWritingPipe(pipe);
}//--(end setup )---
void loop() /****** LOOP: RUNS CONSTANTLY ******/
{
serialEvent();
if (stringComplete) {
inputString.trim();
String on1 = "onone";
on1.trim();
String on2 = "ontwo";
on2.trim();
String off1 = "offone";
off1.trim();
String off2 = "offtwo";
off2.trim();
if (inputString.equals(on1)) {
Serial.print("1 is On");
msg[0] = 111;
radio.write(msg, 1);
inputString = "";
stringComplete = false;
} else if (inputString.equals(off1)) {
Serial.print("1 Is Off");
msg[0] = 112;
radio.write(msg, 1);
inputString = "";
stringComplete = false;
} else if (inputString.equals(on2)) {
Serial.print("2 Is On");
msg[0] = 113;
radio.write(msg, 1);
inputString = "";
stringComplete = false;
} else if (inputString.equals(off2)) {
Serial.print("2 Is Off");
msg[0] = 114;
radio.write(msg, 1);
inputString = "";
stringComplete = false;
} else {
inputString = "";
stringComplete = false;
}
}
}//--(end main loop )---
/*-----( Declare User-written Functions )-----*/
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
delay(100);
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
//NONE
//*********( THE END )***********
Rx:
/* YourDuinoStarter Example: nRF24L01 Receive Joystick values
- WHAT IT DOES: Receives data from another transceiver with
2 Analog values from a Joystick or 2 Potentiometers
Displays received values on Serial Monitor
- SEE the comments after "//" on each line below
- CONNECTIONS: nRF24L01 Modules See:
http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
1 - GND
2 - VCC 3.3V !!! NOT 5V
3 - CE to Arduino pin 9
4 - CSN to Arduino pin 10
5 - SCK to Arduino pin 13
6 - MOSI to Arduino pin 11
7 - MISO to Arduino pin 12
8 - UNUSED
- V1.00 11/26/13
Based on examples at http://www.bajdi.com/
Questions: terry#yourduino.com */
/*-----( Import needed libraries )-----*/
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
/*-----( Declare Constants and Pin Numbers )-----*/
#define CE_PIN 9
#define CSN_PIN 10
int ledPin = 3;
// NOTE: the "LL" at the end of the constant is "LongLong" type
const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe
/*-----( Declare objects )-----*/
RF24 radio(CE_PIN, CSN_PIN); // Create a Radio
/*-----( Declare Variables )-----*/
int msg[1]; // 2 element array holding Joystick readings
int lastMsgNum;
void setup() /****** SETUP: RUNS ONCE ******/
{
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
delay(1000);
Serial.println("Nrf24L01 Receiver Starting");
radio.begin();
radio.openReadingPipe(1,pipe);
radio.startListening();;
}//--(end setup )---
void loop() /****** LOOP: RUNS CONSTANTLY ******/
{
if ( radio.available() )
{
// Read the data payload until we've received everything
bool done = false;
while (!done)
{
// Fetch the data payload
done = radio.read( msg, sizeof(msg) );
Serial.print(msg[0]);
if (msg[0] == 111) {
digitalWrite(3, HIGH);
} else if (msg[0] == 112) {
digitalWrite(3, LOW);
} else if (msg[0] == 113) {
digitalWrite(5, HIGH);
} else if (msg[0] == 114) {
digitalWrite(5, LOW);
}
}
}
else
{
//Serial.println("No radio available");
}
}//--(end main loop )---
/*-----( Declare User-written Functions )-----*/
//NONE
//*********( THE END )***********

I think that you don't understand why you must initialize/set your variables.
inputString and stringComplete are global variables, so when you changed it in serialEvent() you could see it in loop() so when you read a '\n' in serialEvent(). You understand that the sender has finished transmission so you must analize it. Once you finished the corresponding action, you must initialize the global variable again to start again. Unless you have done that, you see stringComplete == true so you start to analize it again in the next cycle of loop().
Usually we call this boolean variables as 'flag', you can see it in several places of code to 'sync' it. In this case, you set true when you have finished the reception and set false when you have finished the analisys.

Related

TTGO ESP32 + GSM 800l AT Commands

Good day all
I'm working on a project that takes sensor data and sends it to an online database using HTTP requests.Im ussing the TTGO esp32 sim 800 board, Everything works fine and all the data is stored in my online database the problem is that I cant get the AT commands to work, I need the Signal strength, battery voltage, and amount of Data available on the sim card.
Can someone please assist with this matter?
kind regards Hansie
Code
#include <HCSR04.h>
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
// Set serial for debug console (to Serial Monitor, default speed 115200)
#define SerialMon Serial
// Set serial for AT commands (to SIM800 module)
#define SerialAT Serial1
// Configure TinyGSM library
#define TINY_GSM_MODEM_SIM800 // Modem is SIM800
#define TINY_GSM_RX_BUFFER 1024 // Set RX buffer to 1Kb
// Define the serial console for debug prints, if needed
//#define DUMP_AT_COMMANDS
#include <Wire.h>
#include <TinyGsmClient.h>
#define uS_TO_S_FACTOR 1000000UL /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 36 /* Time ESP32 will go to sleep (in seconds) 3600 seconds = 1 hour */
#define IP5306_ADDR 0x75
#define IP5306_REG_SYS_CTL0 0x00
// TTGO T-Call pins
#define MODEM_RST 5
#define MODEM_PWKEY 4
#define MODEM_POWER_ON 23
#define MODEM_TX 27
#define MODEM_RX 26
#define I2C_SDA 21
#define I2C_SCL 22
int deviceID=101;
const int trigPin = 5;
const int echoPin = 18;
//Calculation variable for depth
//define sound speed in cm/uS
long duration;
float distanceCm;
double damDepth =200;
// Your GPRS credentials
const char apn[] = "Vodacom APN"; // APN
const char gprsUser[] = ""; // GPRS User
const char gprsPass[] = ""; // GPRS Password
// SIM card PIN (leave empty, if not defined)
const char simPIN[] = "";
// Server details
const char server[] = "grow-with-pierre.com"; // domain name:
const char resource[] = "/post-data.php"; // resource path, for example: /post-data.php
const int port = 80; // server port number
// Keep this API Key value to be compatible with the PHP code
String apiKeyValue = "tPmAT5Ab3j7F9";
#ifdef DUMP_AT_COMMANDS
#include <StreamDebugger.h>
StreamDebugger debugger(SerialAT, SerialMon);
TinyGsm modem(debugger);
#else
TinyGsm modem(SerialAT);
#endif
// I2C for SIM800 (to keep it running when powered from battery)
TwoWire I2CPower = TwoWire(0);
// TinyGSM Client for Internet connection
TinyGsmClient client(modem);
bool setPowerBoostKeepOn(int en)
{
I2CPower.beginTransmission(IP5306_ADDR);
I2CPower.write(IP5306_REG_SYS_CTL0);
if (en)
{
I2CPower.write(0x37); // Set bit1: 1 enable 0 disable boost keep on
} else
{
I2CPower.write(0x35); // 0x37 is default reg value
}
return I2CPower.endTransmission() == 0;
}
void setup()
{
Serial.begin(115200); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
// Set serial monitor debugging window baud rate to 115200
SerialMon.begin(115200);
// Start I2C communication
I2CPower.begin(I2C_SDA, I2C_SCL, 400000);
// Keep power when running from battery
bool isOk = setPowerBoostKeepOn(1);
SerialMon.println(String("IP5306 KeepOn ") + (isOk ? "OK" : "FAIL"));
// Set modem reset, enable, power pins
pinMode(MODEM_PWKEY, OUTPUT);
pinMode(MODEM_RST, OUTPUT);
pinMode(MODEM_POWER_ON, OUTPUT);
digitalWrite(MODEM_PWKEY, LOW);
digitalWrite(MODEM_RST, HIGH);
digitalWrite(MODEM_POWER_ON, HIGH);
// Set GSM module baud rate and UART pins
SerialAT.begin(115200, SERIAL_8N1, MODEM_RX, MODEM_TX);
delay(3000);
// Restart SIM800 module, it takes quite some time
// To skip it, call init() instead of restart()
SerialMon.println("Initializing modem...");
modem.restart();
// use modem.init() if you don't need the complete restart
// Unlock your SIM card with a PIN if needed
if (strlen(simPIN) && modem.getSimStatus() != 3 )
{
modem.simUnlock(simPIN);
}
// Configure the wake up source as timer wake up
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
}
void loop()
{
postData();
Serial.print(String(" Percentage: ") + depth());
// Put ESP32 into deep sleep mode (with timer wake up)
esp_deep_sleep_start();
}
String postData()
{
SerialMon.print("Connecting to APN: ");
SerialMon.print(apn);
if (!modem.gprsConnect(apn, gprsUser, gprsPass))
{
SerialMon.println(" fail");
}
else
{
SerialMon.println(" OK");
SerialMon.print("Connecting to ");
SerialMon.print(server);
if (!client.connect(server, port))
{
SerialMon.println(" fail");
}
else
{
SerialMon.println(" OK");
// Making an HTTP POST request
SerialMon.println("Performing HTTP POST request...");
String httpRequestData = "api_key=" + apiKeyValue + "&value1=" + String(deviceID)
+ "&value2=" + String(distanceCm) + "&value3=" + String(80) + "&value4=" + String(40) + ""+ "&value5=" + String(50) + "";
// then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)
// String httpRequestData = "api_key=tPmAT5Ab3j7F9&value1=24.75&value2=49.54&value3=1005.14";
client.print(String("POST ") + resource + " HTTP/1.1\r\n");
client.print(String("Host: ") + server + "\r\n");
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(httpRequestData.length());
client.println();
client.println(httpRequestData);
unsigned long timeout = millis();
while (client.connected() && millis() - timeout < 10000L)
{
// Print available data (HTTP response from server)
while (client.available())
{
char c = client.read();
SerialMon.print(c);
timeout = millis();
}
}
SerialMon.println();
// Close client and disconnect
client.stop();
SerialMon.println(F("Server disconnected"));
modem.gprsDisconnect();
SerialMon.println(F("GPRS disconnected"));
}
}
}
float depth() //Find Depth in cm
{
double persentage;
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
persentage = (distanceCm/damDepth)*100;
if(persentage>=100)
{
persentage=100;
}
else
{
persentage=100- persentage;
}
return persentage;
}
For at least some of the desired functions, it isn't necessary to push AT-commands.
Try signalStrength = modem.getSignalQuality(); instead. It works for me on the Lilygo T-Call SIM800L. You can check out TinyGSM's Github-page for additional commands or this handy class reference

TMC2208 Stepper driver replacement with A4988 Trouble

I am using a version of an Arduino CNC board that is found here to drive 4 wheels on a small wheeled robot. The shield came with A4988 stepper drivers and I got them to work fine, however the motors were much louder than intended so I went searching for another driver and found the TMC2208. I saw that the pin-outs were the same as long as the boards themselves aligned the enable pins on the shield.
The problem however seems to be in the code though. I am using the Accelstepper library in my code and everything works fine with the A4988 driver board. When I swapped just the boards, nothing happened in my program. I went looking on the TMCStepper library git to try and find some help. I managed to at lease get the steppers working using a version of the 'Simple' example. I tried to take out as much as possible while still being able to move the motors so that I could use it in my actual program. I still am not having any luck.
When I run this program
#include <TMCStepper.h>
#define EN_PIN 8 // Enable
#define DIR_PIN1 5 // Direction
#define STEP_PIN1 2 // Step
#define DIR_PIN2 6 // Direction
#define STEP_PIN2 3
#define DIR_PIN3 7 // Direction
#define STEP_PIN3 4
#define DIR_PIN4 13 // Direction
#define STEP_PIN4 12
#define SW_RX1 55 // TMC2208/TMC2224 SoftwareSerial receive pin
#define SW_TX1 60 // TMC2208/TMC2224 SoftwareSerial transmit pin
#define SW_RX2 56 // TMC2208/TMC2224 SoftwareSerial receive pin
#define SW_TX2 61
#define SW_RX3 57 // TMC2208/TMC2224 SoftwareSerial receive pin
#define SW_TX3 62
#define SW_RX4 58 // TMC2208/TMC2224 SoftwareSerial receive pin
#define SW_TX4 63
#define R_SENSE 0.11f // Match to your driver
TMC2208Stepper driverX(SW_RX1, SW_TX1, R_SENSE);
TMC2208Stepper driverY(SW_RX1, SW_TX1, R_SENSE);
TMC2208Stepper driverZ(SW_RX1, SW_TX1, R_SENSE);
TMC2208Stepper driverA(SW_RX1, SW_TX1, R_SENSE); // Software serial
void setup() {
pinMode(EN_PIN, OUTPUT);
pinMode(STEP_PIN1, OUTPUT);
pinMode(DIR_PIN1, OUTPUT);
pinMode(STEP_PIN2, OUTPUT);
pinMode(DIR_PIN2, OUTPUT);
pinMode(STEP_PIN3, OUTPUT);
pinMode(DIR_PIN3, OUTPUT);
pinMode(STEP_PIN4, OUTPUT);
pinMode(DIR_PIN4, OUTPUT);
digitalWrite(EN_PIN, LOW); // Enable driver in hardware
driverX.begin();
driverY.begin();
driverZ.begin();
driverA.begin(); // SPI: Init CS pins and possible SW SPI pins
// UART: Init SW UART (if selected) with default 115200 baudrate
driverX.microsteps(16); // Set microsteps to 1/16th
}
void loop() {
// Run 5000 steps and switch direction in software
for (uint16_t i = 5; i>0; i++) {
digitalWrite(STEP_PIN1, HIGH);
digitalWrite(STEP_PIN2, HIGH);
digitalWrite(STEP_PIN3, HIGH);
digitalWrite(STEP_PIN4, HIGH);
delayMicroseconds(160);
digitalWrite(STEP_PIN1, LOW);
digitalWrite(STEP_PIN2, LOW);
digitalWrite(STEP_PIN3, LOW);
digitalWrite(STEP_PIN4, LOW);
delayMicroseconds(160);
}
the motors just continuously spin, so I know that the drivers actually work.
My main code is below.
#include <AccelStepper.h>
#include <TMCStepper.h>
const int stepperCount = 4;
AccelStepper BLStepper(AccelStepper::DRIVER, 2, 5);
AccelStepper FLStepper(AccelStepper::DRIVER, 3, 6);
AccelStepper FRStepper(AccelStepper::DRIVER, 4, 7);
AccelStepper BRStepper(AccelStepper::DRIVER, 12, 13);
#define R_SENSE 0.11f
// define pins numbers
#define stepX_PIN 2
#define dirX_PIN 5
#define stepX_RX 55
#define dirX_TX 60
#define stepY_PIN 3
#define dirY_PIN 6
#define stepY_RX 56
#define dirY_TX 61
#define stepZ_PIN 4
#define dirZ_PIN 7
#define stepZ_RX 57
#define dirZ_TX 62
#define stepA_PIN 12
#define dirA_PIN 13
#define stepA_RX 58
#define dirA_TX 63
#define enPin_PIN 8
TMC2208Stepper driverX(stepX_RX, dirX_TX, R_SENSE);
TMC2208Stepper driverY(stepY_RX, dirY_TX, R_SENSE);
TMC2208Stepper driverZ(stepZ_RX, dirZ_TX, R_SENSE);
TMC2208Stepper driverA(stepA_RX, dirA_TX, R_SENSE);
//Front left wheel
//const int stepX_PIN = 2;
//const int dirX_PIN = 5;
//Front right wheel
//const int stepY_PIN = 3;
//const int dirY_PIN = 6;
//Back left wheel
//const int stepZ_PIN = 4;
//const int dirZ_PIN = 7;
//Back right wheel
//const int stepA_PIN = 12;
//const int dirA_PIN = 13;
//const int enPin_PIN = 8;
char split = ':'; //this is the character that would be used for seperating the different parts of your commands
//the syntax for commands would be: command:value1:value2
int listSize = 5; //the amount of commands in the list
String commands[] = {"hello", "add", "sub", "YMOV", "XMOV"}; //the list of every command name
void setup()
{
Serial.begin(115200); //sets the data transfer rate for the serial interface
//9600 is good for basic testing, but should be as high
//as possible for both devices
FRStepper.setMaxSpeed(300);
FRStepper.setAcceleration(200);
BRStepper.setMaxSpeed(300);
BRStepper.setAcceleration(200);
FLStepper.setMaxSpeed(300);
FLStepper.setAcceleration(200);
BLStepper.setMaxSpeed(300);
BLStepper.setAcceleration(200);
pinMode(stepX_PIN, OUTPUT);
pinMode(dirX_PIN, OUTPUT);
pinMode(stepY_PIN, OUTPUT);
pinMode(dirY_PIN, OUTPUT);
pinMode(stepZ_PIN, OUTPUT);
pinMode(dirZ_PIN, OUTPUT);
pinMode(stepA_PIN, OUTPUT);
pinMode(dirA_PIN, OUTPUT);
pinMode(enPin_PIN, OUTPUT);
digitalWrite(enPin_PIN, LOW);
digitalWrite(dirX_PIN, HIGH);
digitalWrite(dirY_PIN, HIGH);
digitalWrite(dirZ_PIN, HIGH);
digitalWrite(dirA_PIN, HIGH);
//digitalWrite(stepX_PIN, HIGH);
//digitalWrite(stepY_PIN, HIGH);
//digitalWrite(stepZ_PIN, HIGH);
//digitalWrite(stepA_PIN, HIGH);
driverX.begin();
driverY.begin();
driverZ.begin();
driverA.begin();
FRStepper.setEnablePin(enPin_PIN);
FLStepper.setEnablePin(enPin_PIN);
BRStepper.setEnablePin(enPin_PIN);
BLStepper.setEnablePin(enPin_PIN);
FRStepper.enableOutputs();
FLStepper.enableOutputs();
BRStepper.enableOutputs();
BLStepper.enableOutputs();
}
void loop()
{
CommCheck(); //checks serial buffer for data commands
runMotors();
}
void runMotors()
{
if ((FLStepper.distanceToGo() != 0) || (FRStepper.distanceToGo() != 0) || (BLStepper.distanceToGo() != 0) || (BRStepper.distanceToGo() != 0))
{
FRStepper.enableOutputs();
FLStepper.enableOutputs();
BRStepper.enableOutputs();
BLStepper.enableOutputs();
FLStepper.run();
BLStepper.run();
FRStepper.run();
BRStepper.run();
if ((FLStepper.distanceToGo() == 0) && (FRStepper.distanceToGo() == 0))
{
CommConfirm();
}
}
//if (movementComplete == true)
//{
//CommConfirm();
//}
//if (
//if ((FLStepper.distanceToGo() == 0) || (FRStepper.distanceToGo() == 0) || (BLStepper.distanceToGo() == 0) || (BRStepper.distanceToGo() == 0))
//{
//CommConfirm();
//}
}
void CommCheck()
{
if(Serial.available()) //checks to see if there is serial data has been received
{
//int len = Serial.available(); //stores the character lengh of the command that was sent
//this is used for command parsing later on
String command = Serial.readString(); //stores the command as a text string
int len = command.length();
//Serial.println(command);
Serial.flush();
//command.remove(len-2,1); //removes characters added by the pi's serial data protocol
//command.remove(0,2);
//len -= 3; //updates the string length value for parsing routine
int points[2] = {0, 0}; //offset points for where we need to split the command into its individual parts
for(int x = 0; x < len; x++) //this loop will go through the entire command to find the split points based on
{ //what the split variable declared at the top of the script is set to.
//Serial.print("Char ");
//Serial.print(x);
//Serial.print("- ");
//Serial.println(command[x]);
if(command[x] == split) //this goes through every character in the string and compares it to the split character
{
if(points[0] == 0) //if the first split point hasn't been found, set it to the current spot
{
points[0] = x;
}
else //if the first spot was already found, then set the second split point
{ //this routine is currently only set up for a command syntax that is as follows
points[1] = x; //command:datavalue1:datavalue2
}
}
}
CommParse(command, len, points[0], points[1]); //now that we know the command, command length, and split points,
} //we can then send that information out to a routine to split the data
} //into individual values.
void CommParse(String command, int len, int point1, int point2)
{
//Serial.print("Command Length: ");
//Serial.println(len);
//Serial.print("Split 1: ");
//Serial.println(point1);
//Serial.print("Split 2: ");
//Serial.println(point2);
String com = command; //copy the full command into all 3 parts
String val1 = command; //this is needed for the string manipulation
String val2 = command; //that follow
com.remove(point1, len - point1); //each of these use the string remove to delete
val1.remove(point2, len - point2); //the parts of the command that aren't needed
val1.remove(0, point1 + 1); //basically splitting the command up into its
val2.remove(0, point2 + 1); //individual pieces
val2.remove(val2.length()-1,1);
CommLookup(com, val1, val2); //these pieces are then sent to a lookup routine for processing
}
void CommLookup(String com, String val1, String val2)
{
int offset = 255; //create a variable for our lookup table's offest value
//we set this to 255 because there won't be 255 total commands
//and a valid command can be offset 0, so it's just to avoid
//any possible coding conflicts if the command sent doesn't
//match anything.
for(int x = 0; x < listSize; x++) //this goes through the list of commands and compares
{ //them against the command received
if(commands[x] == com)
{
offset = x; //if the command matches one in the table, store that command's offset
}
}
switch(offset) //this code compares the offset value and triggers the appropriate command
{
case 0: //essentially a hello world. | Syntax: hello:null:null
CommHello(); //this activates the hello world subroutine | returns Hello!
break;
case 1: //adds both values together and return the sum. | Syntax: add:value1:value2
CommAdd(val1.toInt(), val2.toInt()); //this activates the addition subroutine | returns value1 + value2
break;
case 2: //subtracts both values and return the difference | Syntax: subtract:value1:value2
CommSub(val1.toInt(), val2.toInt()); //this activates the subtraction subroutine | returns value1 - value2
break;
case 3:
yMovement(val1.toInt(), val2.toInt());
break;
case 4:
xMovement(val1.toInt(), val2.toInt());
default: //this is the default case for the command lookup and will only
Serial.println("Command not recognized"); //trigger if the command sent was not known by the arduino
break;
}
}
void CommHello() //each of these routines are what will be triggered when they are successfully processed
{
Serial.println("Hello!");
CommConfirm();
}
void CommAdd(int val1, int val2)
{
Serial.println(val1 + val2);
CommConfirm();
}
void CommSub(int val1, int val2)
{
Serial.println(val1 - val2);
CommConfirm();
}
void yMovement(int val1, int val2)
{
if (val1 < 0) {
//Serial.println("YMOVNEG");
int yMoveNew = (val1 * (-20.72));
//Serial.println(val1 * (-1));
//delay(500);
FRStepper.move(-yMoveNew);
BRStepper.move(-yMoveNew);
FLStepper.move(-yMoveNew);
BLStepper.move(-yMoveNew);
}
else {
//Serial.println(val1);
int yMoveNew = (val1 * (20.72));
//Serial.println(yMoveNew);
//Serial.println(val1);
//delay(500);
FRStepper.move(yMoveNew);
BRStepper.move(yMoveNew);
FLStepper.move(yMoveNew);
BLStepper.move(yMoveNew);
}
}
void xMovement(int val1, int val2)
{
if (val1 < 0) {
//Serial.println(val1);
int xMoveNew = (val1 * (-20.72));
//Serial.println(xMoveNew);
//Serial.println(val1 * (-1));
//delay(1000);
FLStepper.move(-xMoveNew);
BLStepper.move(xMoveNew);
FRStepper.move(xMoveNew);
BRStepper.move(-xMoveNew);
//delayMicroseconds(500);
}
else {
int xMoveNew = (val1 * (20.72));
//Serial.println(val1);
//delay(1000);
FLStepper.move(xMoveNew);
BLStepper.move(xMoveNew);
FRStepper.move(xMoveNew);
BRStepper.move(xMoveNew);
//delayMicroseconds(500);
}
}
void CommConfirm()
{
Serial.println("Done");
delay(750);
}
When I run my code, a Pi sends two values that equals step counts, however with the new drivers nothing happens. I tried also looking at and following the AccelStepper example on the git but I guess I have something wrong.
Any help would be appreciated.

SPI Problem Arduino Mega with pressure sensor MS5803-05BA

I need your help for a project.
I have actually 2 parallel sensors of the type: MS5803-05BA, which supports I2C and SPI connection. One sensor is on I2C bus and one sensor is on SPI. They are both sending to my Arduino Mega. The I2C works perfect with short cables.
Here the datasheet of the sensor:
https://www.amsys.de/downloads/data/MS5803-05BA-AMSYS-datasheet.pdf
For some informations who wants to do the same with I2C. Here you can find a good code. (You can find the other MS580X typs there too). For the communication between the sensor and the Arduino Mega you need an logic converter like this txs0108e, which can be bought with a break out board (you need pull up resistors on the sensor side!):
https://github.com/millerlp/MS5803_05
But to my problem: I have an sensor distance for about 3-5 meters and the I2C connections doesnt work. Yes I can try to fix the pullup resistors but it doesnt worked for me (I have tried some different lower resistors between 3-10kOhm). Therefore I want to switch to the SPI bus.
I have edit the code from https://github.com/millerlp/MS5803_05, https://github.com/vic320/Arduino-MS5803-14BA and https://arduino.stackexchange.com/questions/13720/teensy-spi-and-pressure-sensor.
The File is added. (You have to put the .h and .cpp files in the folder of the arduino code (.spi).
I have problems with the code from the SPI (ccp and header). There is no right communication. I have checked my cables twice. I couldnt find a problem and the connection with the txs0108e works for parallel I2C sensor. Both sensors are working on I2C.
Here is the main code (arduino .spi) for SPI and I2C parallel:
/_____ I N C L U D E S
#include <stdio.h>
#include <math.h>
#include <SPI.h>
#include <Wire.h>
#include "MS5803_05.h"
#include "MS5803_05_SPI.h"
const int miso_port = 50; //SDI
const int mosi_port = 51; //SDO
const int sck_port = 52; //SLCK
const int slaveSelectPin = 53; // CSB
MS_5803 sensor = MS_5803(512);
MS_5803_SPI sensor_spi = MS_5803_SPI(4096, slaveSelectPin);
void setup()
{
pinMode(miso_port, INPUT);
pinMode(mosi_port, OUTPUT);
pinMode(slaveSelectPin, OUTPUT);
pinMode(sck_port, OUTPUT);
Serial.begin(9600);
//SPI BUS
if (sensor_spi.initializeMS_5803_SPI()) {
Serial.println( "MS5803 SPI CRC check OK." );
}
else {
Serial.println( "MS5803 SPI CRC check FAILED!" );
}
//I2C BUS
delay(1000);
if (sensor.initializeMS_5803()) {
Serial.println( "MS5803 I2C CRC check OK." );
}
else {
Serial.println( "MS5803 I2C CRC check FAILED!" );
}
}
void loop()
{
Serial.println("SPI Sensor first pressure [mbar], than temperature[°C]:");
sensor_spi.readSensor();
// Show pressure
Serial.print("Pressure = ");
Serial.print(sensor_spi.pressure());
Serial.println(" mbar");
// Show temperature
Serial.print("Temperature = ");
Serial.print(sensor_spi.temperature());
Serial.println("C");
////********************************************************
Serial.println("");
Serial.println("I2C Sensor first pressure [mbar], than temperature[°C]:");
sensor.readSensor();
// Show pressure
Serial.print("Pressure = ");
Serial.print(sensor.pressure());
Serial.println(" mbar");
// Show temperature
Serial.print("Temperature = ");
Serial.print(sensor.temperature());
Serial.println("C");
delay(2000);
}
}
The first connection with SPI is here (.cpp):
#include "MS5803_05_SPI.h"
#include <SPI.h>
#define CMD_RESET 0x1E // ADC reset command
#define CMD_ADC_READ 0x00 // ADC read command
#define CMD_ADC_CONV 0x40 // ADC conversion command
#define CMD_ADC_D1 0x00 // ADC D1 conversion
#define CMD_ADC_D2 0x10 // ADC D2 conversion
#define CMD_ADC_256 0x00 // ADC resolution=256
#define CMD_ADC_512 0x02 // ADC resolution=512
#define CMD_ADC_1024 0x04 // ADC resolution=1024
#define CMD_ADC_2048 0x06 // ADC resolution=2048
#define CMD_ADC_4096 0x08 // ADC resolution=4096
#define CMD_PROM_RD 0xA0 // Prom read command
#define spi_write SPI_MODE3
#define spi_write2 SPI_MODE1
// Create array to hold the 8 sensor calibration coefficients
static unsigned int sensorCoeffs[8]; // unsigned 16-bit integer (0-65535)
// D1 and D2 need to be unsigned 32-bit integers (long 0-4294967295)
static uint32_t D1 = 0; // Store uncompensated pressure value
static uint32_t D2 = 0; // Store uncompensated temperature value
// These three variables are used for the conversion steps
// They should be signed 32-bit integer initially
// i.e. signed long from -2147483648 to 2147483647
static int32_t dT = 0;
static int32_t TEMP = 0;
// These values need to be signed 64 bit integers
// (long long = int64_t)
static int64_t Offset = 0;
static int64_t Sensitivity = 0;
static int64_t T2 = 0;
static int64_t OFF2 = 0;
static int64_t Sens2 = 0;
// Some constants used in calculations below
const uint64_t POW_2_33 = 8589934592ULL; // 2^33 = 8589934592
SPISettings settings_write(500000, MSBFIRST, spi_write);
SPISettings settings_write2(500000, MSBFIRST, spi_write2);
//-------------------------------------------------
// Constructor
MS_5803_SPI::MS_5803_SPI( uint16_t Resolution, uint16_t cs) {
// The argument is the oversampling resolution, which may have values
// of 256, 512, 1024, 2048, or 4096.
_Resolution = Resolution;
//Chip Select
_cs=cs;
}
boolean MS_5803_SPI::initializeMS_5803_SPI(boolean Verbose) {
digitalWrite( _cs, HIGH );
SPI.begin();
// Reset the sensor during startup
resetSensor();
if (Verbose)
{
// Display the oversampling resolution or an error message
if (_Resolution == 256 | _Resolution == 512 | _Resolution == 1024 | _Resolution == 2048 | _Resolution == 4096){
Serial.print("Oversampling setting: ");
Serial.println(_Resolution);
} else {
Serial.println("*******************************************");
Serial.println("Error: specify a valid oversampling value");
Serial.println("Choices are 256, 512, 1024, 2048, or 4096");
Serial.println("*******************************************");
}
}
// Read sensor coefficients
for (int i = 0; i < 8; i++ )
{
SPI.beginTransaction(settings_write2);
digitalWrite(_cs, LOW); //csb_lo(); // pull CSB low
unsigned int ret;
unsigned int rC = 0;
SPI.transfer(CMD_PROM_RD + i * 2); // send PROM READ command
/*
ret = SPI.transfer(0x00); // send 0 to read the MSB
rC = 256 * ret;
ret = SPI.transfer(0x00); // send 0 to read the LSB
rC = rC + ret;
*/
// send a value of 0 to read the first byte returned:
rC = SPI.transfer( 0x00 );
rC = rC << 8;
rC |= SPI.transfer( 0x00 ); // and the second byte
sensorCoeffs[i] = (rC);
digitalWrite( _cs, HIGH );
delay(3);
}
//SPI.endTransaction(); // interrupt can now be accepted
// The last 4 bits of the 7th coefficient form a CRC error checking code.
unsigned char p_crc = sensorCoeffs[7];
// Use a function to calculate the CRC value
unsigned char n_crc = MS_5803_CRC(sensorCoeffs);
if (Verbose) {
for (int i = 0; i < 8; i++ )
{
// Print out coefficients
Serial.print("C");
Serial.print(i);
Serial.print(" = ");
Serial.println(sensorCoeffs[i]);
delay(10);
}
Serial.print("p_crc: ");
Serial.println(p_crc);
Serial.print("n_crc: ");
Serial.println(n_crc);
}
// If the CRC value doesn't match the sensor's CRC value, then the
// connection can't be trusted. Check your wiring.
if (p_crc != n_crc) {
return false;
}
// Otherwise, return true when everything checks out OK.
return true;
}
// Sends a power on reset command to the sensor.
void MS_5803_SPI::resetSensor() {
SPI.beginTransaction(settings_write);
digitalWrite(_cs, LOW); //csb_lo(); // pull CSB low to start the command
SPI.transfer(CMD_RESET); // send reset sequence
delay(3); // wait for the reset sequence timing delay(3)
digitalWrite(_cs, HIGH); //csb_hi(); // pull CSB high to finish the command
SPI.endTransaction(); // interrupt can now be accepted
}
The Code can be downloaded at: https://forum.arduino.cc/index.php?topic=670661.0
There you can find the schematic and output picture too.
Thanks a lot :).

Having hard time achieving 1 Msps with external 12bit- ADC(LTC2365) using Arduino Due

I have an LTC2365/1 Msps 12bit-ADC with SPI pins. Somehow I only could achieve a maximum of 200 Ksps with this ADC rather than something close to 1 Msps using an Arduino Due. I wonder if anyone could help me with this issue. I tried many ways but couldn't figure it out.
Datasheet for the ADC:
http://cds.linear.com/docs/en/datasheet/23656fb.pdf
Here is the code I use for Arduino:
#include <SPI.h>
const int spi_ss = 10; // set SPI SS Pin
uint8_t byte_0, byte_1; // First and second bytes read
uint16_t spi_bytes; // final 12 bit shited value
long int starttime,endtime;
long int count=0;
void setup() {
SerialUSB.begin(2000000); // begin serial and set speed
pinMode(spi_ss, OUTPUT); // Set SPI slave select pin as output
digitalWriteDirect(spi_ss, HIGH); // Make sure spi_ss is held high
SPI.begin();
SPI.beginTransaction(SPISettings(16000000, MSBFIRST, SPI_MODE0));
loop2();
SPI.endTransaction();
}
void loop2() {
starttime=millis();
endtime=starttime;
while((endtime-starttime)<=1000) {
// write the LTC CS pin low to initiate ADC sample and data transmit
digitalWriteDirect(spi_ss, LOW);
byte_0 = spi_read(0x00); // read firt 8 bits
byte_1 = spi_read(0x00); // read second 8 bits
digitalWriteDirect(spi_ss, HIGH);
// wite LTC CS pin high to stop LTC from transmitting zeros.
spi_bytes = ( ( (byte_0 <<6) ) + (byte_1 >>2) );
SerialUSB.println(spi_bytes);
count=count+1;
endtime=millis();
}
//samples per second
SerialUSB.println(count);
}
static inline uint8_t spi_read(uint8_t b) {
return SPI.transfer(b);
}
inline void digitalWriteDirect(int pin, boolean val) {
if(val) g_APinDescription[pin].pPort -> PIO_SODR = g_APinDescription[pin].ulPin;
else g_APinDescription[pin].pPort -> PIO_CODR = g_APinDescription[pin].ulPin;
}

Using arduino to control leds as a pattern

I have this code here which sends some keys to windows and also lights up an led attached under each button. I think its right so the led will toggle with the button. What I wanted to achieve ontop of this was so that if no button states hadn't changed for 30 seconds then it goes into a mode where all three leds flash rapidly 3 times then the leds randomly flashes (Like a pinball machine when its not in use). After any input then it goes back to the normal mode
/* Arduino USB Keyboard HID demo
* Cut/Copy/Paste Keys
*/
#define KEY_LEFT_CTRL 0x01
#define KEY_LEFT_SHIFT 0x02
#define KEY_RIGHT_CTRL 0x10
#define KEY_RIGHT_SHIFT 0x20
uint8_t buf[8] = {
0 }; /* Keyboard report buffer */
#define PIN_COPY 5
#define PIN_CUT 6
#define PIN_PASTE 7
#define LED_COPY 8
#define LED_CUT 9
#define LED_PASTE 10
int state = 1;
void setup()
{
Serial.begin(9600);
pinMode(PIN_COPY, INPUT);
pinMode(PIN_CUT, INPUT);
pinMode(PIN_PASTE, INPUT);
// Enable internal pull-ups
digitalWrite(PIN_COPY, 1);
digitalWrite(PIN_CUT, 1);
digitalWrite(PIN_PASTE, 1);
delay(200);
}
void loop()
{
state = digitalRead(PIN_CUT);
if (state != 1) {
buf[0] = KEY_LEFT_CTRL; // Ctrl
buf[2] = 27; // Letter X
// buf[2] = 123; // Cut key: Less portable
Serial.write(buf, 8); // Ssend keypress
digitalWrite(LED_CUT, HIGH);
releaseKey();
}
state = digitalRead(PIN_COPY);
if (state != 1) {
buf[0] = KEY_LEFT_CTRL; // Ctrl
buf[2] = 6; // Letter C
// buf[2] = 124; // Copy key: Less portable
Serial.write(buf, 8); // Send keypress
digitalWrite(LED_COPY, HIGH);
releaseKey();
}
state = digitalRead(PIN_PASTE);
if (state != 1) {
buf[0] = KEY_LEFT_CTRL; // Ctrl
buf[2] = 25; // Letter V
// buf[2] = 125; // Paste key: Less portable
Serial.write(buf, 8); // Send keypress
digitalWrite(LED_PASTE, HIGH);
releaseKey();
}
}
void releaseKey()
{
buf[0] = 0;
buf[2] = 0;
Serial.write(buf, 8); // Release key
delay(500);
digitalWrite(LED_COPY, LOW);
digitalWrite(LED_CUT, LOW);
digitalWrite(LED_PASTE, LOW);
}
For refrence this is the article I was using http://mitchtech.net/arduino-usb-hid-keyboard/
i recomend you to look for Finite State Machine in Google.
Here is one link to implement it in C++
http://www.drdobbs.com/cpp/state-machine-design-in-c/184401236
here is other link to implement it in Arduino
http://playground.arduino.cc/Code/SMlib
it's exactly what you need to do what you want.
i hope this help you!

Resources