Arduino and Philips hue variable brightness in url - url

I am changing the code from a website. I removed the PIR sensor variable and added a distance sensor so i can change the brightness with my hand. I got it all figured out but i dont know how to change the brightness in the command for a variable "Brightness". Everything is local and the script works without the variable brightness.
Code for the state of the lights:
command = "{\"hue\":50100,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
setHue(2,command);
SetHue Method:
boolean setHue(int lightNum,String command)
{
if (client.connect(hueHubIP, hueHubPort))
{
while (client.connected())
{
client.print("PUT /api/");
client.print(hueUsername);
client.print("/lights/");
client.print(lightNum); // hueLight zero based, add 1
client.println("/state HTTP/1.1");
client.println("keep-alive");
client.print("Host: ");
client.println(hueHubIP);
client.print("Content-Length: ");
client.println(command.length());
client.println("Content-Type: text/plain;charset=UTF-8");
client.println(); // blank line before body
client.println(command); // Hue command
}
client.stop();
return true; // command executed
}
else
return false; // command failed
}
source: http://www.makeuseof.com/tag/control-philips-hue-lights-arduino-and-motion-sensor/

Related

Arduino Temboo Google Sheets response code 0 returned, still not working

So I'm trying to update a gooogle sheet through Temboo and an Arduino Yun. I can run the AppendValues choreo and AppendRow choreo from the Temboo site just fine and everything updates, but running the choreos through the arduino .ino shows no updates on the google sheet. I get a return code of 0 from running the choreo though. So I know Oauth is working and google and temboo are talking, so there must be a problem in my code?
I have double checked AccountName, Password, AppKey, refresh token, client secret, client id, spreadsheet id, spreadsheet name, etc in the Arduino code (tried AppendValuesChoreo and AppendRowChoreo).
AppendRow .ino:
// Include required libraries
#include <Bridge.h>
#include <Temboo.h>
// Debug mode ?
boolean debug_mode = true;
void setup() {
//start serial
Serial.begin(115200);
delay(4000);
while(!Serial);
// Start bridge
Bridge.begin();
Serial.println("Setup complete. Waiting for sensor input...\n");
}
void loop() {
Serial.println("\nCalling the /Library/Google/Spreadsheets/AppendRow Choreo...");
// Append data to Google Docs sheet
runAppendRow();
// Repeat every 10 seconds
delay(10000);
}
// Function to add data to Google Docs
void runAppendRow() {
TembooChoreo AppendRowChoreo;
// Invoke the Temboo client
AppendRowChoreo.begin();
// Set Temboo account credentials
AppendRowChoreo.setAccountName("");
AppendRowChoreo.setAppKeyName("myFirstApp");
AppendRowChoreo.setAppKey("");
// Identify the Choreo to run
AppendRowChoreo.setChoreo("/Library/Google/Spreadsheets/AppendRow");
// your Google username (usually your email address)
AppendRowChoreo.addInput("Username", "");
// your Google account password
AppendRowChoreo.addInput("Password", "");
// the title of the spreadsheet you want to append to
AppendRowChoreo.addInput("SpreadsheetTitle", "Yun");
// Format data
String data = "123,921";
// Set Choreo inputs
AppendRowChoreo.addInput("RowData", data);
// Run the Choreo
unsigned int returnCode = AppendRowChoreo.run();
// A return code of zero means everything worked
if (returnCode == 0) {
if (debug_mode == true){
Serial.println("Completed execution of the /Library/Google/Spreadsheets/AppendRow Choreo.\n");
Serial.println("Row added: " + data);
}
} else {
// A non-zero return code means there was an error
// Read and print the error message
while (AppendRowChoreo.available()) {
char c = AppendRowChoreo.read();
if (debug_mode == true){ Serial.print(c); }
}
if (debug_mode == true){ Serial.println(); }
}
AppendRowChoreo.close();
}
AppendVValues .ino:
#include <Bridge.h>
#include <Temboo.h>
int calls = 1; // Execution count, so this doesn't run forever
int maxCalls = 10; // Maximum number of times the Choreo should be executed
void setup() {
Serial.begin(9600);
// For debugging, wait until the serial console is connected
delay(4000);
while(!Serial);
Bridge.begin();
}
void loop() {
if (calls <= maxCalls) {
Serial.println("Running AppendValues - Run #" + String(calls++));
TembooChoreo AppendValuesChoreo;
// Invoke the Temboo client
AppendValuesChoreo.begin();
// Set Temboo account credentials
AppendValuesChoreo.setAccountName("");
AppendValuesChoreo.setAppKeyName("");
AppendValuesChoreo.setAppKey("");
// Set Choreo inputs
AppendValuesChoreo.addInput("RefreshToken", "");
AppendValuesChoreo.addInput("ClientSecret", "");
AppendValuesChoreo.addInput("Values", "[[15,49]]");
AppendValuesChoreo.addInput("ClientID", "");
AppendValuesChoreo.addInput("SpreadsheetID", "");
// Identify the Choreo to run
AppendValuesChoreo.setChoreo("/Library/Google/Sheets/AppendValues");
// Run the Choreo; when results are available, print them to serial
AppendValuesChoreo.run();
while(AppendValuesChoreo.available()) {
char c = AppendValuesChoreo.read();
Serial.print(c);
}
AppendValuesChoreo.close();
}
Serial.println("Waiting...");
delay(30000); // wait 30 seconds between AppendValues calls
}
Looks like they only support rev1, and the original shields. Hopefully they'll update services for the rev2 boards soon.

Is it possible to send lin frame from CANoe without using the LDF file

I'm new to CANoe and CAPL, currently using Vector CANoe 16 SP2 Demo version. I'm able to send a 8 bytes of CAN message as shown below with the help of CAPL script without CAN database file.
/*#!Encoding:1252*/
includes
{
}
variables
{
message 0x01 msg1;
msTimer tm;
}
on start
{
setTimer(tm,10);
}
on timer tm
{
Send_msg_1();
setTimer(tm,10);
}
void Send_msg_1()
{
int i;
msg1.msgChannel=1;
msg1.dlc=8;
for(i=0;i<8;i++)
{
msg1.byte(i)=0x1;
}
output(msg1);
}
enter image description here
Now, I want to send 8 bytes of lin frame with CAPL without the LDF file. I've written the following code for it
/*#!Encoding:1252*/
includes
{
}
variables
{
linFrame 0x01 msg1;
msTimer tm;
}
on start
{
setTimer(tm,10);
}
on timer tm
{
msg1();
setTimer(tm,10);
}
void msg1()
{
int i;
msg1.msgChannel=1;
msg1.dlc=8;
for(i=0;i<8;i++)
{
msg1.byte(i)=0x1;
}
msg1.rtr=0;
output(msg1);
msg1.rtr=1;
output(msg1);
write("Frame Transmitted");
}
But, I'm not sure if its getting really transmitted because it is showing like this in trace window
enter image description here
If its not correct. Please let me know the correct way of transmitting a lin frame in CANoe with CAPL scripting.
Thanks in advance :)

Why do builds for various projects fail with ‘Operation not permitted’ using iOS on-device compiler/toolchain?

I am an intermediately skilled Linux/Unix user trying to compile software for an iPad on a (jailbroken) iPad.
Many builds (for example, make and tex-live) fail with some Operation not permitted error. This will either look like Can't exec "blah": Operation not permitted or execvp: blah: Operation not permitted where blah is aclocal, a configure script, libtool, or just about anything. Curiously, finding the offending line in a Makefile or configure script and prefixing it with sudo -u mobile -E will solve the error for that line, only for it to reappear for on a later line or in another file. Since I am running the build scripts as mobile, I do not understand how this could possibly fix the issue, yet it does. I have confirmed that making these changes does actually allow for the script to work successfully up to that point. Running the build script with sudo or sudo -u mobile -E and/or running the entire build as root does not solve the issue; with either, I still must edit build scripts to add sudo’s.
I would like to know why this is happening, and if possible how I could address the issue without editing build scripts. Any information about these types of errors would be interesting to me even if they do not solve my problem. I am aware that the permissions/security/entitlements system is unusual on iOS and would like to learn more about how it works.
I am using an iPad Pro 4 on jailbroken iOS 13.5 with the build tools from sbingner’s and MCApollo’s repos (repo.bingner.com and mcapollo.github.io/Public). In particular, I am using a build of LLVM 5 (manually installed from sbingner’s old debs), Clang 10, Darwin CC tools 927 and GNU Make 4.2.1. I have set CC, CXX, CFLAGS, etc. to point to clang-10 and my iOS 13.5 SDK with -isysroot and have confirmed that these settings are working. I would like to replace these with updated versions, but I cannot yet build these tools for myself due to this issue and a few others. I do have access to a Mac for cross-compilation if necessary, but I would rather use only my iPad because I like the challenge.
I can attach any logs necessary or provide more information if that would be useful; I do not know enough about this issue to know what information is useful. Thanks in advance for helping me!
For anyone who ends up needing to address this issue on a jailbreak that does not have a fix for this issue, I have written (pasted below) a userland hook based on the posix_spawn implementation from the source of Apple’s xnu kernel.
Compile it with Theos, and inject it into all processes spawned by your shell by setting environment variable DYLD_INSERT_LIBRARIES to the path of the resulting dylib. Note: some tweak injectors (namely libhooker, see here) reset DYLD_INSERT_LIBRARIES, so if you notice this behavior, be sure to inject only your library.
Because the implementation of the exec syscalls in iOS call out to posix_spawn, this hook fixes all of the exec-related issue’s I’ve run into so far.
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <spawn.h>
// Copied from bsd/kern/kern_exec.c
#define IS_WHITESPACE(ch) ((ch == ' ') || (ch == '\t'))
#define IS_EOL(ch) ((ch == '#') || (ch == '\n'))
// Copied from bsd/sys/imgact.h
#define IMG_SHSIZE 512
// Here, we provide an alternate implementation of posix_spawn which correctly handles #!.
// This is based on the implementation of posix_spawn in bsd/kern/kern_exec.c from Apple's xnu source.
// Thus, I am fairly confident that this posix_spawn has correct behavior relative to macOS.
%hookf(int, posix_spawn, pid_t *pid, const char *orig_path, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *attrp, char *const orig_argv[], char *const envp[]) {
// Call orig before checking for anything.
// This mirrors the standard implementation of posix_spawn because it first checks if we are spawning a binary.
int err = %orig;
// %orig returns EPERM when spawning a script.
// Thus, if err is anything other than EPERM, we can just return like normal.
if (err != EPERM)
return err;
// At this point, we do not need to check for exec permissions or anything like that.
// because posix_spawn would have returned that error instead of EPERM.
// Now we open the file for reading so that we can check if it's a script.
// If it turns out not to be a script, the EPERM must be from something else
// so we just return err.
FILE *file = fopen(orig_path, "r");
if (file == NULL) {
return err;
}
if (fseek(file, 0, SEEK_SET)) {
return err;
}
// In exec_activate_image, the data buffer is filled with the first PAGE_SIZE bytes of the file.
// However, in exec_shell_imgact, only the first IMG_SHSIZE bytes are used.
// Thus, we read IMG_SHSIZE bytes out of our file.
// The buffer is filled with newlines so that if the file is not IMG_SHSIZE bytes,
// the logic reads an IS_EOL.
char vdata[IMG_SHSIZE] = {'\n'};
if (fread(vdata, 1, IMG_SHSIZE, file) < 2) { // If we couldn't read at least two bytes, it's not a script.
fclose(file);
return err;
}
// Now that we've filled the buffer, we don't need the file anymore.
fclose(file);
// Now we follow exec_shell_imgact.
// The point of this is to confirm we have a script
// and extract the usable part of the interpreter+arg string.
// Where they return -1, we don't have a shell script, so we return err.
// Where they return an error, we return that same error.
// We don't bother doing any SUID stuff because SUID scripts should be disabled anyway.
char *ihp;
char *line_startp, *line_endp;
// Make sure we have a shell script.
if (vdata[0] != '#' || vdata[1] != '!') {
return err;
}
// Try to find the first non-whitespace character
for (ihp = &vdata[2]; ihp < &vdata[IMG_SHSIZE]; ihp++) {
if (IS_EOL(*ihp)) {
// Did not find interpreter, "#!\n"
return ENOEXEC;
} else if (IS_WHITESPACE(*ihp)) {
// Whitespace, like "#! /bin/sh\n", keep going.
} else {
// Found start of interpreter
break;
}
}
if (ihp == &vdata[IMG_SHSIZE]) {
// All whitespace, like "#! "
return ENOEXEC;
}
line_startp = ihp;
// Try to find the end of the interpreter+args string
for (; ihp < &vdata[IMG_SHSIZE]; ihp++) {
if (IS_EOL(*ihp)) {
// Got it
break;
} else {
// Still part of interpreter or args
}
}
if (ihp == &vdata[IMG_SHSIZE]) {
// A long line, like "#! blah blah blah" without end
return ENOEXEC;
}
// Backtrack until we find the last non-whitespace
while (IS_EOL(*ihp) || IS_WHITESPACE(*ihp)) {
ihp--;
}
// The character after the last non-whitespace is our logical end of line
line_endp = ihp + 1;
/*
* Now we have pointers to the usable part of:
*
* "#! /usr/bin/int first second third \n"
* ^ line_startp ^ line_endp
*/
// Now, exec_shell_imgact copies the interpreter into another buffer and then null-terminates it.
// Then, it copies the entire interpreter+args into another buffer and null-terminates it for later processing into argv.
// This processing is done in exec_extract_strings, which goes through and null-terminates each argument.
// We will just do this all at once since that's much easier.
// Keep track of how many arguments we have.
int i_argc = 0;
ihp = line_startp;
while (true) {
// ihp is on the start of an argument.
i_argc++;
// Scan to the end of the argument.
for (; ihp < line_endp; ihp++) {
if (IS_WHITESPACE(*ihp)) {
// Found the end of the argument
break;
} else {
// Keep going
}
}
// Null terminate the argument
*ihp = '\0';
// Scan to the beginning of the next argument.
for (; ihp < line_endp; ihp++) {
if (!IS_WHITESPACE(*ihp)) {
// Found the next argument
break;
} else {
// Keep going
}
}
if (ihp == line_endp) {
// We've reached the end of the arg string
break;
}
// If we are here, ihp is the start of an argument.
}
// Now line_startp is a bunch of null-terminated arguments possibly padded by whitespace.
// i_argc is now the count of the interpreter arguments.
// Our new argv should look like i_argv[0], i_argv[1], i_argv[2], ..., orig_path, orig_argv[1], orig_argv[2], ..., NULL
// where i_argv is the arguments to be extracted from line_startp;
// To allocate our new argv, we need to know orig_argc.
int orig_argc = 0;
while (orig_argv[orig_argc] != NULL) {
orig_argc++;
}
// We need space for i_argc + 1 + (orig_argc - 1) + 1 char*'s
char *argv[i_argc + orig_argc + 1];
// Copy i_argv into argv
int i = 0;
ihp = line_startp;
for (; i < i_argc; i++) {
// ihp is on the start of an argument
argv[i] = ihp;
// Scan to the next null-terminator
for (; ihp < line_endp; ihp++) {
if (*ihp == '\0') {
// Found it
break;
} else {
// Keep going
}
}
// Go to the next character
ihp++;
// Then scan to the next argument.
// There must be another argument because we already counted i_argc.
for (; ihp < line_endp; ihp++) {
if (!IS_WHITESPACE(*ihp)) {
// Found it
break;
} else {
// Keep going
}
}
// ihp is on the start of an argument.
}
// Then, copy orig_path into into argv.
// We need to make a copy of orig_path to avoid issues with const.
char orig_path_copy[strlen(orig_path)+1];
strcpy(orig_path_copy, orig_path);
argv[i] = orig_path_copy;
i++;
// Now, copy orig_argv[1...] into argv.
for (int j = 1; j < orig_argc; i++, j++) {
argv[i] = orig_argv[j];
}
// Finally, add the null.
argv[i] = NULL;
// Now, our argv is setup correctly.
// Now, we can call out to posix_spawn again.
// The interpeter is in argv[0], so we use that for the path.
return %orig(pid, argv[0], file_actions, attrp, argv, envp);
}

XBee printout, void setup()

I'm having trouble with my XBee's printing out to the monitor a simple statement, within the void setup(), as shown in my program below.
It prints the GPS and various sensor data, but it skips the whole introductory sentences. Whenever I open the arduino serial monitor, with the board plugged into my computer, it works fine.
Any suggestions? I'm at a lost!
Thanks :)
// Temperature Sensor data, Air Quality, and GPS data update XBEE
//CSV format for user interpretation
//Last updated 11/5/14
//Amy Laguna
#include <Adafruit_GPS.h>
#include <math.h>
#include <SoftwareSerial.h>
SoftwareSerial XBee(2, 3);
SoftwareSerial mySerial(8, 7);
//Read temperature sensor on A1
int tempPin = 1;
//Read CO sensor on A0
int coPin = 0;
//Read Oxygen sensor on A2
int opin = 2;
//GPS setup
Adafruit_GPS GPS(&mySerial);
//Use to debug
//SET to 'fale' to turn off echoing the GPS data to Serial
//Set to 'true' to debug and listen to raw GPS data
#define GPSECHO false
// this keeps track of whether we're using the interrupt
boolean usingInterrupt = false;
void useInterrupt(boolean);
void setup()
{
// connect at 115200 so we can read the GPS fast enough and echo without dropping chars
XBee.begin(115200);
Serial.begin(115200);
delay(5000);
XBee.println("Vehicle GPS, Temperature, and Air Quality Data!");
delay(2000);
XBee.println("Note: Elevation in Pensacola Florida: ~ 31 m (102 ft)");
XBee.println();
XBee.println("\n Date: Time: Fix: Location: Speed (mph): Elevation: CO: O2: Temperature: ");
// 9600 NMEA is the default baud rate for Adafruit MTK GPS's
GPS.begin(9600);
// RMC (recommended minimum) and GGA (fix data) including altitude
GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
// Set the update rate
GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ); // 1 Hz update rate
// For the parsing code to work nicely and have time to sort thru the data, and
// print it out we don't suggest using anything higher than 1 Hz
useInterrupt(true);
delay(1500);
}
// Interrupt is called once a millisecond, looks for any new GPS data, and stores it
SIGNAL(TIMER0_COMPA_vect) {
char c = GPS.read();
// if you want to debug, this is a good time to do it!
#ifdef UDR0
if (GPSECHO)
if (c) UDR0 = c;
#endif
}
void useInterrupt(boolean v) {
if (v) {
// Timer0 is already used for millis() - we'll just interrupt somewhere
// in the middle and call the "Compare A" function above
OCR0A = 0xAF;
TIMSK0 |= _BV(OCIE0A);
usingInterrupt = true;
} else {
// do not call the interrupt function COMPA anymore
TIMSK0 &= ~_BV(OCIE0A);
usingInterrupt = false;
}
}
uint32_t timer = millis();
void loop() // run over and over again
{
if (! usingInterrupt) {
// read data from the GPS in the 'main loop'
char c = GPS.read();
// if you want to debug, this is a good time to do it!
if (GPSECHO)
if (c) XBee.print(c);
}
// if a sentence is received, we can check the checksum, parse it...
if (GPS.newNMEAreceived()) {
if (!GPS.parse(GPS.lastNMEA())) // this also sets the newNMEAreceived() flag to false
return; // we can fail to parse a sentence in which case we should just wait for another
}
// if millis() or timer wraps around, we'll just reset it
if (timer > millis()) timer = millis();
// approximately every 2 seconds or so, print out the current stats
if (millis() - timer > 2000) {
timer = millis(); // reset the timer
PrintGPS(); //Print GPS readings
PrintAirQuality(); //Print CO and Temperature readings
}
}
void PrintGPS()
{
//Print Date, Time, Fix
XBee.print("\n");
XBee.print(GPS.month, DEC); XBee.print('/');
XBee.print(GPS.day, DEC); XBee.print("/20");
XBee.print(GPS.year, DEC);
XBee.print(" , ");
XBee.print(GPS.hour, DEC); XBee.print(':');
XBee.print(GPS.minute, DEC); XBee.print(':');
XBee.print(GPS.seconds, DEC);
}
Maybe try a longer delay before the XBee.println() statements. If the radio modules haven't associated yet, they won't be ready for you to start sending data through them.
Alternatively, wait until the first call to PrintGPS() and send it then:
void PrintGPS()
{
static int first_time = 1;
if (first_time) {
print_headers();
first_time = 0;
}
//Print Date, Time, Fix
...

Why is RB interrupt routine running twice?

I have some code below that has a slight bug that I don't know how to fix. Essentially what is happening is my high ISR is running twice after the the flag is set. It only runs twice and is consistent. The subroutine should run only once because the flag is set when the input on RB changes, and the routine runs twice after one change to RB's input. The testing was conducted in MPLAB v8.6 using the workbook feature.
#include <p18f4550.h>
#include <stdio.h>
void init(void)
{
RCONbits.IPEN =1; //allows priority
INTCONbits.GIE = 1; //allows interrupts
INTCONbits.PEIE = 1; //allows peripheral interrupts
INTCONbits.RBIF = 0; //sets flag to not on
INTCONbits.RBIE = 1; //enables RB interrupts
INTCON2bits.RBPU = 1; //enable pull up resistors
INTCON2bits.RBIP = 1; //RB interrupts is high priority
PORTB = 0x00;
TRISBbits.RB7 = 1; //enable RB7 as an input so we can throw interrupts when it changes.
}
#pragma code
#pragma interrupt high_isr
void high_isr(void)
{
if(INTCONbits.RBIF == 1)
{
INTCONbits.RBIF = 0;
//stuff
}
}
#pragma code
#pragma code high_isr_entry = 0x08
void high_isr_entry(void)
{_asm goto high_isr _endasm}
void main(void)
{
init();
while(1);
}
The RB7 interrupt flag is set based on a compare of the last latched value and the current state of the pin. In the datasheet it says "The pins are compared with the old value latched on the last read of PORTB. The 'mismatch' outputs of RB7:RB4 are ORed together to generate the RB Port Change Interrupt with Flag bit."
To clear the mismatch condition the datasheet goes on to say "Any read or write of PORTB (except with the
MOVFF (ANY), PORTB instruction). This will end the mismatch condition."
You then wait one Tcy (execute a nop instruction) and then clear the flag. This is documented on page 116 of the datasheet.
So the simplest fix in this scenario is in the interrupt routine declare a dummy variable and set it to RB7 like this:
#pragma interrupt high_isr
void high_isr(void)
{
unsigned short dummy;
if(INTCONbits.RBIF == 1)
{
dummy = PORTBbits.RB7; // Perform read before clearing flag
Nop();
INTCONbits.RBIF = 0;
// rest of your routine here
// ...

Resources