So I am using Temboo after recently acquiring a Arduino Yun, however I am having an issue with getting and posting data by combining Choreos.
I am using the Yahoo GetWeatherByAddress Choreo and trying to post the individual values I want to a Xively Feed. I am using the Xively Write Choreo and inputting FeedData in JSON format.
So far I have had some success with posting 2 values (humidity and pressure) at a time. Unfortunately I want to use more than this and have Humidity, Temperature, WeatherConditions(Fair, Windy etc) and a LDR reading from a breadboard. So It loops every 10 seconds, reads all those values and then posts them to Xively. The Temperature value seems to have an issue with even printing to Serial Monitor if I have any more than the Temperature value uncommented. It also doesn't go through with the whole process (returning Http 200 for success) It posts the values and the just goes straight to "waiting" for the next set of values to be retrieved. Where am I going wrong here?
/*
YahooWeather
This example code is in the public domain.
*/
#include <Bridge.h>
#include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information
// the address for which a weather forecast will be retrieved
String ADDRESS_FOR_FORECAST = "Plymouth, United Kingdom";
int numRuns = 1; // execution count, so that this doesn't run forever
int maxRuns = 10; // max number of times the Yahoo WeatherByAddress Choreo should be run
String pData;
String qData;
String rData;
String tData;
String cData;
void setup() {
Serial.begin(9600);
// for debugging, wait until a serial console is connected
delay(4000);
while(!Serial);
Bridge.begin();
pinMode(A0, INPUT);
pinMode(13, OUTPUT);
}
void loop()
{
if (numRuns <= maxRuns) {
int sensorValue = analogRead(A0);
if (sensorValue < 100) {
digitalWrite(13,HIGH);
delay(1000);
digitalWrite(13,LOW);
}
// while we haven't reached the max number of runs...
Serial.println("Sensor value: " + String(sensorValue)); }
TembooChoreo WriteDataChoreo;
// Invoke the Temboo client
WriteDataChoreo.begin();
// Set Temboo account credentials
WriteDataChoreo.setAccountName(TEMBOO_ACCOUNT);
WriteDataChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
WriteDataChoreo.setAppKey(TEMBOO_APP_KEY);
// print status
Serial.println("Running GetWeatherByAddress - Run #" + String(numRuns++) + "...");
// create a TembooChoreo object to send a Choreo request to Temboo
TembooChoreo GetWeatherByAddressChoreo;
// invoke the Temboo client
GetWeatherByAddressChoreo.begin();
// add your temboo account info
GetWeatherByAddressChoreo.setAccountName(TEMBOO_ACCOUNT);
GetWeatherByAddressChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
GetWeatherByAddressChoreo.setAppKey(TEMBOO_APP_KEY);
// set the name of the choreo we want to run
GetWeatherByAddressChoreo.setChoreo("/Library/Yahoo/Weather/GetWeatherByAddress");
// set choreo inputs; in this case, the address for which to retrieve weather data
// the Temboo client provides standardized calls to 100+ cloud APIs
GetWeatherByAddressChoreo.addInput("Address", ADDRESS_FOR_FORECAST);
// add an output filter to extract the name of the city.
GetWeatherByAddressChoreo.addOutputFilter("pressure", "/rss/channel/yweather:atmosphere/#pressure", "Response");
GetWeatherByAddressChoreo.addOutputFilter("humidity", "/rss/channel/yweather:atmosphere/#humidity", "Response");
GetWeatherByAddressChoreo.addOutputFilter("text", "/rss/channel/item/yweather:condition/#text", "Response");
// GetWeatherByAddressChoreo.addOutputFilter("temperature", "/rss/channel/item/yweather:condition/#temp", "Response"); //
// add an output filter to extract the current temperature
// add an output filter to extract the date and time of the last report.
// run the choreo
GetWeatherByAddressChoreo.run();
// parse the results and print them to the serial monitor
while(GetWeatherByAddressChoreo.available()) {
// read the name of the next output item
String name = GetWeatherByAddressChoreo.readStringUntil('\x1F');
name.trim(); // use “trim” to get rid of newlines
// read the value of the next output item
String data = GetWeatherByAddressChoreo.readStringUntil('\x1E');
data.trim(); // use “trim” to get rid of newlines
if (name == "humidity") {
qData = data;
Serial.println("The humidity is " + qData);
}
else if (name == "temperature") {
tData = data;
Serial.println("The temperature is " + tData);
}
else if (name == "pressure") {
rData = data;
Serial.println("The pressure is " + rData);
}
else if (name == "text") {
cData = data;
Serial.println("The code is " + cData);
}
}
WriteDataChoreo.addInput("FeedID", "1508368369");
WriteDataChoreo.addInput("APIKey", "6Z4tvi6jUOC0VhFkgngijR3bZWMXr2NNu1PHl4Js0hHGqE6C");
// WriteDataChoreo.addInput("FeedData", "{\"version\":\"1.0.0\",\"datastreams\":[ {\"id\" : \"Pressure\",\"current_value\" : \"" + rData + "\"} ,{\"id\" : \"Humidity\",\"current_value\" : \"" + qData + "\"} ,{\"id\" : \"Conditions\",\"current_value\" : \"" + cData + "\"}]}");
WriteDataChoreo.addInput("FeedData", "{\"version\":\"1.0.0\",\"datastreams\":[{\"id\":\"Humidity\",\"current_value\":\""+qData+"\"},{\"id\":\"Pressure\",\"current_value\":\""+rData+"\"},{\"id\":\"Conditions\",\"current_value\":\""+cData+"\"},{\"id\":\"Temp\",\"current_value\":\""+tData+"\"}]}");
// Identify the Choreo to run
// Identify the Choreo to run
WriteDataChoreo.setChoreo("/Library/Xively/ReadWriteData/WriteData");
// Run the Choreo; when results are available, print them to serial
WriteDataChoreo.run();
while(WriteDataChoreo.available()) {
char c = WriteDataChoreo.read();
//Serial.print(c);
}
while(GetWeatherByAddressChoreo.available()) {
char c = GetWeatherByAddressChoreo.read();
//Serial.print(c);
}
WriteDataChoreo.close();
GetWeatherByAddressChoreo.close();
Serial.println("");
Serial.println("Waiting...");
Serial.println("");
delay(10000); // wait 30 seconds between GetWeatherByAddress calls
}
I work at Temboo. I believe we've resolved this issue already via Temboo support, so I'm answering here for posterity.
Generally, if a sketch is working intermittently and you haven't changed any code, then it's likely that you're running out of RAM (a common issue on resource-constrained devices). When your board is out of RAM it causes Choreo input data to get overwritten and corrupted on the 32U4 side of your Yún. Your sketch is probably right at the RAM limit, which explains why it's working sometimes but not others, dependent on the amount of String data involved.
You can free up some RAM by putting the inputs that don't change (your Temboo creds, your Xively creds, the address you're searching for, any other static strings) into settings files that are stored on the Linino side, as described at the link below:
https://temboo.com/arduino/using-settings-files
If that doesn't free enough memory, you can free some more by eliminating any unnecessary Serial or Console print statements.
Hopefully this will help solve the issue you're seeing. Please let me know if it doesn't and we will continue to investigate.
Finally, here's some info on how you can check on how much memory a sketch is using:
http://jeelabs.org/2011/05/22/atmega-memory-use/
Good luck,
Cormac
Related
I´m totally new to coding, this is even my first post here. Im tryng this because nobody sells what I want/need ;-).
I achived already quite a bit, but at this moment I´m getting lost with a lot of things (I read a lot about coding in general and in special with Arduino the last 8 dayas)... but let me explain first what my intention on this project is:
I want to build a "Stomp Box" to mute a Behringer X32 Rack (wireless) Channels/Mutegroups/Buses, just Mute On/Off.. nothing else.
This Box should have 4-6 "stompers" (buttons), each of this buttons should have a different Mute function.
Also the current state of the Channel/Mutegroup/Bus should be indicated by LED´s green if unmuted or red if muted.
Therfore the box needs to evaulate the current state of the designated Channel/Mutegroup/Bus, because it could change also from other remote devices.
And then switch to the opposite state when pressing/stomping on designated button.
I´d like to have code where I can easily change the action of a button, Like:
button1 = /ch/01/mix/on ,i 1
button2 = /config/mute/1 ,i 1
button3 = /dca/1/on ,i 1
so in case I need a differnt Channel/Mutegroup/Bus for another event simply edit and recode my ESP32 Node Kit
So here is my code I already have:
#include "WiFi.h"
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <SPI.h>
#include <OSCMessage.h> //https://github.com/CNMAT/OSC
#define WIFI_NETWORK "xxxxxxxxxx" //SSID of you Wifi
#define WIFI_PASSWORD "xxxxxxxxxxx" //Your Wifi Password
#define WIFI_TIMEOUT_MS 20000 // 20 second WiFi connection timeout
#define WIFI_RECOVER_TIME_MS 30000 // Wait 30 seconds after a failed connection attempt
int muteOn = 0;// 0=Mute
int muteOff = 1;// 1=Unmute
int input;
WiFiUDP Udp;
const IPAddress outIp (192, 168, 10, 129); //Mixers IP
const unsigned int outPort = 10023; //X32 Port
//variables for blinking an LED with Millis
const int led = 2; // ESP32 Pin to which onboard LED is connected
unsigned long previousMillis = 0; // will store last time LED was updated
const long interval = 300; // interval at which to blink (milliseconds)
int ledState = LOW; // ledState used to set the LED
void connectToWiFi(){
Serial.print("Zu WLAN verbinden...");
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_NETWORK, WIFI_PASSWORD);
unsigned long startAttemptTime = millis();
while(WiFi.status() != WL_CONNECTED && millis() - startAttemptTime < WIFI_TIMEOUT_MS){
Serial.println(".");
delay(100);
}
if(WiFi.status() != WL_CONNECTED){
Serial.println("Nicht Verbunden!");
//optional take action
}else{
Serial.print("WLAN Verbunden mit ");
Serial.println(WIFI_NETWORK);
Serial.println(WiFi.localIP( ));
}
}
void setup() {
Serial.begin(115200);
connectToWiFi();
Udp.begin(8888);
pinMode(led, OUTPUT);
// Port defaults to 3232
// ArduinoOTA.setPort(3232);
// Hostname defaults to esp3232-[MAC]
// ArduinoOTA.setHostname("myesp32");
// No authentication by default
// ArduinoOTA.setPassword("admin");
// Password can be set with it's md5 value as well
// MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
// ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
ArduinoOTA
.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
})
.onEnd([]() {
Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
Serial.println("Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop(){
ArduinoOTA.handle();
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
ledState = not(ledState);
// set the LED with the ledState of the variable:
digitalWrite(led, ledState);
}
input=Serial.read();
if (input=='0'){
// welcher status hat der kanal?
// wenn Kanal gemutet dann unmute und umgekehrt
Serial.println("Mute!");
delay(100);
sendMute(); //send Mute to Mixer
Serial.println("...");
}
if (input=='1'){
Serial.println("UnMute!");
delay(100);
sendUnMute();
Serial.println("...");
}
}
void sendMute() {
//the message wants an OSC address as first argument
OSCMessage msg("/ch/01/mix/on");
msg.add(muteOn);
Udp.beginPacket(outIp, outPort);
msg.send(Udp); // send the bytes to the SLIP stream
Udp.endPacket(); // mark the end of the OSC Packet
msg.empty(); // free space occupied by message
delay(20);
}
void sendUnMute() {
//the message wants an OSC address as first argument
OSCMessage msg("/ch/01/mix/on");
msg.add(muteOff);
Udp.beginPacket(outIp, outPort);
msg.send(Udp); // send the bytes to the SLIP stream
Udp.endPacket(); // mark the end of the OSC Packet
msg.empty(); // free space occupied by message
delay(20);
}
So I testet this via serial Monitor, when I input "0" and click send, the mixer mutes channel 1 and on input "1" channel 1 becomes unmuted, so far so good... (OSCMessage msg("/ch/01/mix/on"); ... section.
What bothers me here in special is, I had to hardcode the command "/ch/01/mix/on", because I am not able to declare a variable? for this string? I am already so confused that I don´t know if I even have the terms right :-(
BTW: There are a lot solutions out there how to do it with MIDI, but MIDI is not wireles and I think for my project overkill. I also did some some research on github.com/CNMAT/OSC but I don´t get it... (crying)...
I found also a post here, but this didn´t helped either... :-(
Any advice on that how I can reach my goal?--
Any help is much apprceiated... even in German (my native language... )
PS: Yes I´m a begginner and I admit it. But at least I managed how to connect and flash this thing even via OTA in the last 8 days, so please be easy on me.
Not wanting to hardcode your commands is a good instinct.
The Arduino language is C++, which is (mostly) a superset of C. C and C++ use a preprocessor which lets you define constants and test for their presence.
For instance, you could write:
#define CHAN01_MIX_ON_COMMAND "/ch/01/mix/on"
and then use CHAN01_MIX_ON_COMMAND anywhere you want to use that constant, like so:
void sendMute() {
//the message wants an OSC address as first argument
OSCMessage msg(CHAN01_MIX_ON_COMMAND);
Then if you ever need to change the string "/ch/01/mix/on" you can just change it in one location and not worry about finding every instance of it in your code.
Writing the names in #define statements is a convention people usually follow in order to make it more clear that they're constants.
You have to write the #define line before you use the constant you defined, so putting it at the start of the file (after any #include lines and before your first function) is a good practice. Or if you have several you might put them all in their own file called something like commands.h (the .h means header file)and then include that at the start of any file that needs it like so:
#include "commands.h"
This #include statement would insert the contents of the file commands.h into the file that the statement is in.
When you have several #define statements, keeping them all together in one place (whether it's at the top of the file or in their own file) is also a good practice so that you have one central place to find them and update them if you need to.
Some people will assign the string constant to a variable like so:
char *channel01_mix_on_cmd = "/ch/01/mix/on";
Here char means "a character" - like one letter or number or symbol. The * means pointer to, which lets you use an array of characters. Simple strings in C and C++ are just arrays of characters (or a pointer to the first character), with a special hidden character at the end set to numeric value 0 (not the character '0'). C++ also has a string datatype called std::string and Arduino programs have String but those are both overkill here. They all let you work with strings; String is much easier to use than char * but both have strengths and weaknesses.
Like the #define, you'd also place that outside a function near the start of the file. It defines a global variable that would be available to any function that references it.
You'd also use the variable anywhere they want the string. It's the same idea as using #define, just done slightly differently. For instance:
void sendMute() {
//the message wants an OSC address as first argument
OSCMessage msg(channel01_mix_on_cmd);
Using a variable here is an attempt to save storage by not having multiple copies of the string. It's not necessary; C/C++ compilers have for a very long time detected this and stored only one copy of the string. It might save space if your code is split into multiple files.
Saving space on CPUs like the ESP32 and ESP8266 is important because they have so little memory. #define is fine here because the compiler does it automatically for you.
You can create the command string with sprintf.
so for example:
#define CHANNELON "on"
#define CHANNELOFF "off"
int channel;
int mute;
char messageString[100];
// some code that calculates the channel number and the mute state:
channel = 1;
mute = 1;
// then check the mute state and create the command string:
if (mute)
{
// to turn off a channel:
sprintf(messageString,"/ch/%02d/mix/%s",channel,CHANNELOFF);
}
else
{
// to turn on a channel:
sprintf(messageString,"/ch/%02d/mix/%s",channel,CHANNELON);
}
// send the command:
OSCMessage msg(messageString);
the %02d will substitute an integer with a zero in front,
if it's smaller than 10 and that is always 2 characters long.
so if channel is 1, the result would be 01
I have a processing sketch which needs to set up 2 connections with USB devices. I cannot tell in advance which device is USB0 and which is USB1. (not that I am aware off atleast)
One of the devices awnsers with hello the other one does not answer at all. Therefor I have written code with a simple timeout. In the setup I check continously if there are bytes to read. But both a while and an if statement yield incorrect results
while( dccCentral.available() < 5 ) {
if( dccCentral.available() >= 5) break;
if(millis() > 5000 ) {
println("timeout occured");
println(dccCentral.available());
break;
}
}
These lines are in setup. The text "timeout occured" is always printed. Underneath it, the result of dccCentral.available() is printed. This number is 12 which is correct.
regardless, if dccCentral.available() prints 12 at that time. The first if-statement:
if( dccCentral.available() >= 5) break;
should already have break'ed out of the while loop before this time-out should occur. The while-loop itself should also quit itself when 5 or more bytes are received.
Why do both these lines
while( dccCentral.available() < 5 ) {
if( dccCentral.available() >= 5) break;
fail?
Personally I try to avoid while loops unless there isn't another way (e.g. inside a thread) and that is avoid both logic pitfalls and messing with the lifecycle of other objects that might need a bit of time to initialise.
If you send strings from Arduino and also use println() you could init the port to easily catch that using Serial's bufferUntil() in conjuction with serialEvent() to finally readString().
Once you start getting data in, you could:
use references to the serial ports you're after and a couple of extra ones until you know which port is which
use a boolean "toggle" to only handle the "hello" once
if the hello was received, you can use the serialEvent() Serial argument to assign dccCentral and by process of elimination assign the other port
Here's a commented sketch to illustrate the idea:
import processing.serial.*;
// be sure to set this to the baud rate your device use with Arduino as well
final int BAUD_RATE = 115200;
// reference to Serial port sending "Hello" (when that get's detected)
Serial dccCentral;
// reference to the other Serial port
Serial otherDevice;
// temporary references
Serial usb0;
Serial usb1;
// 'toggle' to keep track where the hello was received and handled or not (by default initialised as false)
boolean wasHelloReceived;
void setup(){
usb0 = initSerial("/dev/ttyUSB0", BAUD_RATE);
usb1 = initSerial("/dev/ttyUSB1", BAUD_RATE);
}
Serial initSerial(String portName, int baudRate){
Serial port = null;
try{
port = new Serial(this, portName, baudRate);
// if sending strings and using println() from Arduino
// you can buffer all chars until the new line ('\n') character is found
port.bufferUntil('\n');
}catch(Exception e){
println("error initialising port: " + portName);
println("double check name, cable connections and close other software using the same port");
e.printStackTrace();
}
return port;
}
void draw(){
background(0);
text("wasHelloReceived: " + wasHelloReceived + "\n"
+"dccCentral: " + dccCentral + "\n"
+"otherDevice: " + otherDevice , 10 ,15);
// do something with the devices once they're ready (e.g. send a message every 3 seconds)
if(millis() % 3000 == 0){
if(dccCentral != null){
dccCentral.write("ping\n");
}
if(otherDevice != null){
otherDevice.write("pong\n");
}
}
}
void serialEvent(Serial port){
try{
String serialString = port.readString();
// if the received string is not null, nor empty
if(serialString != null && !serialString.isEmpty()){
// for debugging purposes display the data received
println("received from serial: " + serialString);
// trim any white space
serialString = serialString.trim();
// check if "hello" was received
if(serialString.equals("hello")){
println("hello detected!");
// if the dccCEntral (hello sending) serial port wasn't assigned yet, assign it
// think of this as debouncing a button: setting the port once "hello" was received should happen only once
if(!wasHelloReceived){
// now what dccCentral is found, assign it to the named reference
dccCentral = port;
// by process elimiation, assign the other port
// (e.g. if dccCentral == usb0, then other is usb1 and vice versa)
otherDevice = (dccCentral == usb0 ? usb1 : usb0);
/*
the above is the same as
if(dccCentral == usb0){
otherDevice = usb1;
}else{
otherDevice = usb0;
}
*/
wasHelloReceived = true;
}
}
}
}catch(Exception e){
println("error processing serial data");
e.printStackTrace();
}
}
Note the above code hasn't been tested so it may include syntax errors, but hopefully the point gets across.
I can't help notice that USB0/USB1 are how serial devices sometimes show up on Linux.
If you're working with a Raspberry Pi I can recommend a slightly easier way if you're comfortable with Python. The PySerial has a few tricks up it's sleeve:
You can simply call: python -m serial.tools.list_ports -v which will list ports with extra information such as serial number of the serial converter chipset. This could be useful to tell which device is which, regardless of the manufacturer and USB port used
Other than the serial port name/location, it supports multiple ways (URLs) of accessing the port with a very clever: hwgrep:// will allow you to filter a device by it's unique serial number
Here's a basic list_ports -v output for two devices with the same chipset:
column 1
/dev/ttyUSB9
desc: TTL232R-3V3
hwid: USB VID:PID=0403:6001 SER=FT94O21P LOCATION=1-2.2
column 2
/dev/ttyUSB8
desc: TTL232R-3V3
hwid: USB VID:PID=0403:6001 SER=FT94MKCI LOCATION=1-2.1.4
To assign the devices using serial you would use something like:
"hwgrep://FT94O21P"
"hwgrep://FT94MKCI"
Update
It might help to step by step debug the system and try one port a time.
The idea is to get the bit of code reading the expected serial string tight.
Here's a basic example that should simply accumulate one char at a time into a string and display it:
import processing.serial.*;
Serial port;
String fromSerial = "";
void setup(){
size(300,300);
port = initSerial("/dev/ttyUSB0", 115200);
}
Serial initSerial(String portName, int baudRate){
Serial port = null;
try{
port = new Serial(this, portName, baudRate);
// if sending strings and using println() from Arduino
// you can buffer all chars until the new line ('\n') character is found
port.bufferUntil('\n');
}catch(Exception e){
println("error initialising port: " + portName);
println("double check name, cable connections and close other software using the same port");
e.printStackTrace();
}
return port;
}
void draw(){
if(port != null){
if(port.available() > 0){
char inChar = port.readChar();
fromSerial += inChar;
if(inChar == '\n'){
println("newline encountered");
println(fromSerial.split("\n"));
}
}
}
background(0);
text("from serial:" + fromSerial, 10,15);
}
If the data from dccCentral comes in a expected: great, the code can be simplfied and right conditions applied to filter the device in the future,
otherwise it should help pin point communication issues getting the "hello" in the first place (which would be 6 bytes ("hello"(5) + '\n') if sent with Serial.println() from Arduino)
Regarding Python, no problem at all. Should the idea help in the future you can check out this answer. (AFAIK Processing Serial uses JSSC behind the scenes)
I'm new to the PSoC board and I'm trying to read the x,y,z values from a Digital Compass but I'm having a problem in beginning the Transmission with the compass itself.
I found some Arduino tutorial online here but since PSoC doesn't have the library I can't duplicate the code.
Also I was reading the HMC5883L datasheet here and I'm suppose to write bytes to the compass and obtain the values but I was unable to receive anything. All the values I received are zero which might be caused by reading values from wrong address.
Hoping for your answer soon.
PSoC is sorta tricky when you are first starting out with it. You need to read over the documentation carefully of both the device you want to talk to and the i2c module itself.
The datasheet for the device you linked states this on page 18:
All bus transactions begin with the master device issuing the start sequence followed by the slave address byte. The
address byte contains the slave address; the upper 7 bits (bits7-1), and the Least Significant bit (LSb). The LSb of the
address byte designates if the operation is a read (LSb=1) or a write (LSb=0). At the 9
th clock pulse, the receiving slave
device will issue the ACK (or NACK). Following these bus events, the master will send data bytes for a write operation, or
the slave will clock out data with a read operation. All bus transactions are terminated with the master issuing a stop
sequence.
If you use the I2C_MasterWriteBuf function, it wraps all that stuff the HMC's datasheet states above. The start command, dealing with that ack, the data handling, etc. The only thing you need to specify is how to transmit it.
If you refer to PSoC's I2C module datasheet, the MasterWriteBuf function takes in the device address, a pointer to the data you want to send, how many bytes you want to send, and a "mode". It shows what the various transfer modes in the docs.
I2C_MODE_COMPLETE_XFER Perform complete transfer from Start to Stop.
I2C_MODE_REPEAT_START Send Repeat Start instead of Start.
I2C_MODE_NO_STOP Execute transfer without a Stop
The MODE_COMPLETE_XFRE transfer will send the start and stop command for you if I'm not mistaken.
You can "bit-bang" this also if you want but calling directly on the I2C_MasterSendStart, WriteByte, SendStop, etc. But it's just easier to call on their writebuf functions.
Pretty much you need to write your code like follows:
// fill in your data or pass in the buffer of data you want to write
// if this is contained in a function call. I'm basing this off of HMC's docs
uint8 writeBuffer[3];
uint8 readBuffer[6];
writeBuffer[0] = 0x3C;
writeBuffer[1] = 0x00;
writeBuffer[2] = 0x70;
I2C_MasterWriteBuf(HMC_SLAVE_ADDRESS, &writeBuffer, 3, I2C_MODE_COMPLETE_XFER);
while((I2C_MasterStatus() & I2C_MSTAT_WR_CMPLT) == 0u)
{
// wait for operation to finish
}
writeBuffer[1] = 0x01;
writeBuffer[2] = 0xA0;
I2C_MasterWriteBuf(HMC_SLAVE_ADDRESS, &writeBuffer, 3, I2C_MODE_COMPLETE_XFER);
// wait for operation to finish
writeBuffer[1] = 0x02;
writeBuffer[2] = 0x00;
I2C_MasterWriteBuf(HMC_SLAVE_ADDRESS, &writeBuffer, 3, I2C_MODE_COMPLETE_XFER);
// wait for operation to finish
CyDelay(6); // docs state 6ms delay before you can start looping around to read
for(;;)
{
writeBuffer[0] = 0x3D;
writeBuffer[1] = 0x06;
I2C_MasterWriteBuf(HMC_SLAVE_ADDRESS, &writeBuffer, 2, I2C_MODE_COMPLETE_XFER);
// wait for operation to finish
// Docs don't state any different sort of bus transactions for reads.
// I'm assuming it'll be the same as a write
I2C_MasterReadBuf(HMC_SLAVE_ADDRESS, readBuffer, 6, I2C_MODE_COMPLETE_XFER);
// wait for operation to finish, wait on I2C_MSTAT_RD_CMPLT instead of WR_COMPLT
// You should have something in readBuffer to work with
CyDelay(67); // docs state to wait 67ms before reading again
}
I just sorta wrote that off the top of my head. I have no idea if that'll work or not, but I think that should be a good place to start and try. They have I2C example projects to look at also I think.
Another thing to look at so the WriteBuf function doesn't just seem like some magical command, if you right-click on the MasterWriteBuf function and click on "Find Definition" (after you build the project) it'll show you what it's doing.
Following are the samples for I2C read and write operation on PSoC,
simple Write operation:
//Dumpy data values to write
uint8 writebuffer[3]
writebuffer[0] = 0x23
writebuffer[1] = 0xEF
writebuffer[2] = 0x0F
uint8 I2C_MasterWrite(uint8 slaveAddr, uint8 nbytes)
{
uint8 volatile status;
status = I2C_MasterClearStatus();
if(!(status & I2C_MSTAT_ERR_XFER))
{
status = I2C_MasterWriteBuf(slaveAddr, (uint8 *)&writebuffer, nbytes, I2C_MODE_COMPLETE_XFER);
if(status == I2C_MSTR_NO_ERROR)
{
/* wait for write complete and no error */
do
{
status = I2C_MasterStatus();
} while((status & (I2C_MSTAT_WR_CMPLT | I2C_MSTAT_ERR_XFER)) == 0u);
}
else
{
/* translate from I2CM_MasterWriteBuf() error output to
* I2C_MasterStatus() error output */
status = I2C_MSTAT_ERR_XFER;
}
}
return status;
}
Read Operation:
void I2C_MasterRead(uint8 slaveaddress, uint8 nbytes)
{
uint8 volatile status;
status = I2C_MasterClearStatus();
if(!(status & I2C_MSTAT_ERR_XFER))
{
/* Then do the read */
status = I2C_MasterClearStatus();
if(!(status & I2C_MSTAT_ERR_XFER))
{
status = I2C_MasterReadBuf(slaveaddress,
(uint8 *)&(readbuffer),
nbytes, I2C_MODE_COMPLETE_XFER);
if(status == I2C_MSTR_NO_ERROR)
{
/* wait for reading complete and no error */
do
{
status = I2C_MasterStatus();
} while((status & (I2C_MSTAT_RD_CMPLT | I2C_MSTAT_ERR_XFER)) == 0u);
if(!(status & I2C_MSTAT_ERR_XFER))
{
/* Decrement all RW bytes in the EZI2C buffer, by different values */
for(uint8 i = 0u; i < nbytes; i++)
{
readbuffer[i] -= (i + 1);
}
}
}
else
{
/* translate from I2C_MasterReadBuf() error output to
* I2C_MasterStatus() error output */
status = I2C_MSTAT_ERR_XFER;
}
}
}
if(status & I2C_MSTAT_ERR_XFER)
{
/* add error handler code here */
}
}
I try to control a stepper motor with a program that uses a protocol (see below)
I am able to control the stepper with the Accelstepper (see below) but have no idea how i can program the Arduino so it is able to communicate according te protocol through the serial port.
#include <AccelStepper.h>
// Define a stepper and the pins it will use
AccelStepper stepper(1, 3, 4);
int pos = 8192;
void setup()
{
stepper.setMaxSpeed(5000);
stepper.setAcceleration(1500);
}
void loop()
{
if (stepper.distanceToGo() == 0)
{
delay(500);
pos = -pos;
stepper.moveTo(pos);
}
stepper.run();
}
All commands sent to the rotary table are in simple character format including the motor numbers. Only the parts marked as xxx passed to the table as byte data. For example if you want table 1 rotate 4 steps instead of passing "I1M004" you pass "I1M" + (char)0 + (char)0 + (char)4
In general all commands get a reply in the form of: ^XXXXXX
Commands
V
Request the status of the rotary table. Usual reply would be ^R1R2R3R4 indicating rotary 1 ready, rotary 2 ready, etc. ^B1xxxR2R3R4 means rotary 1 is busy where xxx are 3 bytes indicates how many steps the rotary still has to perform.
SmMxxx
Sets the speed of the motor m to xxx, where xxx is a 3 bytes of data indicating the speed. Example code: port.Write("S1M" + (char)0 + (char)6 + (char)255); // set motor 1 to speed 1791. The standard speed range of our rotary table is: 0x000001 to 0x0012FF (1 to 4863). Controller will respond with ^mxx mirroring the motor number and 2 last bytes of speed setting.
ImMxxx
Turns motor m xxx number of steps. Controller will acknowledge with ^Bmxxx
DmCWLO
Set motor number m to rotate clockwise (So each consecutive command to rotate the motor m will rotate it clockwise).
DmCWHi
Sets rotary m to rotate counterclockwise.
EmHALT
Rotary m stop.
Rotary Sample Command Sequence
Motor numbers are passed as characters but the number of steps and speed are passed as 3 bytes of binary for simplicity.
send: V reply: ^R1R2R3R4
send: S1M1791 reply: ^191
send: D1CWLO reply: ^
send: I1M100 reply: ^B1100
I had a similar project for my dissertation work where I controlled an inverted pendulum from a PC via an arduino uno. I'm assuming you have a PC program what sends out the commands to the arduino, and the problem is to receive and interpret it on the Arduino board.
I wrote the code below with major help (some copy paste modify) from here
It basically opens the com port and then listens to the incoming commands from the PC. When a command is received, it breaks it up (the incoming commands come in a #00parameter format). All commands start with #. The following 2 digits define the command itself, and the following text/numbers are the parameters for the command.
Once the command and its parameters are known, the actual process related to the command can be executed. In your case this supposed to be the motor control related to the incoming commands. The below code obviously needs to be updated to match with your motor control functions, but the incoming command handling works just fine.
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the incloming string is complete
float kp = 10; //sample parameter 1
float kd = 5; //sample parameter 2
float ki = 2; //sample parameter 3
void setup()
{
Serial.begin(9600); //Start serial communication
inputString.reserve(200); //Reserves 200 bytes for the string
}
void loop()
{
//This becomes true when the serial port receives a "\n" character (end of line)
if (stringComplete)
{
SerialProc(); //the function which runs when a full line is received
inputString = ""; //once processed, the string is cleared
stringComplete = false; //set flag to false to indicate there is nothing in the buffer waiting
}
}
void serialEvent() //This serial event runs between each loop cycles
{
while (Serial.available()) //if there is anything in the incoming buffer this while loop runs
{
// get the next new byte:
char inChar = (char)Serial.read();
// 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; //This indicates the line is complete, and the main program can process it
}
}
}
void SerialProc() //the function which processes the incoming commands. It needs to be modified to your needs
{
//cmd is the first three characters of the incoming string / line
String cmd = inputString.substring(0,3); //first three characters in incoming string specifies the command
//param is the rest of the string to the end of the line (excluding the first three characters)
String param = inputString.substring(3, inputString.length()); //rest of incoming string is making up the parameter
//creating a buffer as an array of characters, same size as the length of the parameters string
char buf[param.length()];
//moving the parameters from string to the char array
param.toCharArray(buf,param.length());
//the above string to char array conversion is required for the string to float
//conversion below (atof)
//the below part is the command execution. Could have used a switch below, but the series of ifs
//just did the trick
if (cmd == "#00")
SendReply(); //Executing command 1
else if (cmd == "#01")
kp = atof(buf); //executing command 2 (setting parameter kp)
else if (cmd == "#02")
kd = atof(buf); //executing command 3 (setting parameter kd)
else if (cmd == "#03")
ki = atof(buf); //executing command 4 (setting parameter ki)
}
void SendReply()
{
//This is called from the SerialProc function when the #00 command is received
//After the last parameter (TimeDelay) it sends the carrige return characters via the Serial.println
Serial.println("reply");
}
I'm trying to read variable streams of characters and process them on the Arduino once a certain string of bytes is read on the Arduino. I have a sample sketch like the following, but I can't figure out how to compare the "readString" to process something on the Arduino. I would like the Arduino to process "commands" such as {blink}, {open_valve}, {close_valve}, etc.
// Serial - read bytes into string variable for string
String readString;
// Arduino serial read - example
int incomingByte;
// flow_A LED
int led = 4;
void setup() {
Serial.begin(2400); // Open serial port and set Baud rate to 2400.
Serial.write("Power on test");
}
void loop() {
while (Serial.available()) {
delay(10);
if (Serial.available() > 0) {
char c = Serial.read(); // Gets one byte from serial buffer
readString += c; // Makes the string readString
}
}
if (readString.length() > 0) {
Serial.println( readString); // See what was received
}
if (readString == '{blink_Flow_A}') {
digitalWrite(led, HIGH); // Turn the LED on (HIGH is the voltage level).
delay(1000); // Wait for one second.
digitalWrite(led, LOW); // Turn the LED off by making the voltage LOW.
delay(1000); // Wait for a second.
}
Some definitions first:
SOP = Start Of Packet (in your case, an opening brace)
EOP = End Of Packet (in your case, a closing brace)
PAYLOAD = the characters between SOP and EOP
PACKET = SOP + PAYLOAD + EOP
Example:
PACKET= {Abc}
SOP = {
EOP = }
PAYLOAD = Abc
Your code should process one character at a time, and should be structured as a state machine.
When the code starts, the parser state is "I'm waiting for the SOP character". While in this state, you throw away every character you receive unless it's equal to SOP.
When you find you received a SOP char, you change the parser state to "I'm receiving the payload". You store every character from now on into a buffer, until you either see an EOP character or exhaust the buffer (more on this in a moment). If you see the EOP char, you "close" the buffer by appending a NULL character (i.e. 0x00) so that it becomes a standard NULL-terminated C-string, and you can work on it with the standard functions (strcmp, strstr, strchr, etc.).
At this point you pass the buffer to a "process()" function, which executes the operation specified by the payload (1)
You have to specify the maximum length of a packet, and size the receive buffer accordingly. You also have to keep track of the current payload length during the "payload receive" state, so you don't accidentally try to store more payload bytes into the temporary buffer than it can hold (otherwise you get memory corruption).
If you fill the receive buffer without seeing an EOP character, then that packet is either malformed (too long) or a transmission error changed the EOP character into something else. In either case you should discard the buffer contents and go back to "Waiting for SOP" state.
Depending on the protocol design, you could send an error code to the PC so the person typing at the terminal or the software on that side knows the last command it sent was invalid or not received correctly.
Finally, the blink code in you snipped should be replaced by non-blocking "blink-without-delay"-style code (look at the example that come with the Arduino IDE).
(1) Example of a "process" function:
void process(char* cmd) {
if (strcmp(cmd, "open_valve") == 0) {
open_valve();
}
else if (strcmp(cmd, "close_valve") == 0) {
close_valve();
}
else {
print_error("Unrecognized command.");
}
}
It seems you are comparing the string in this statement:
if( readString == '{blink_Flow_A}' )
So I don't get your question re :
but I can't figure out how to compare the "readString" to process something
Are you really asking:
How do I extract the commands from an incoming stream of characters?
If that is the case then treat each command as a "packet". The packet is enclosed in brackets: {}. Knowing that the {} brackets are start and end of a packet, it is easy to write a routine to get at the command in the packet.
Once the command is extracted just go through a if-then-else statement to do what each command is supposed to do.
If I totally misunderstood your question I apologize :)
EDIT:
see http://arduino.cc/en/Tutorial/StringComparisonOperators
if( readString == "{blink_Flow_A}" ) should be correct syntax.
Since you have a statement
Serial.println( readString);
you should see the string received.