Processing to Arduino with Keyboard - keyboard

I decided to build a telepresence robot that would be controlled through a keyboard(using WASD) through serial. I've been waiting for my parts to arrive so I started doing some tests with processing and using the WASD keys to light up LED's.
import processing.serial.*;
import cc.arduino.*;
Serial myPort;
Arduino arduino;
void setup () {
println(Arduino.list());
arduino = new Arduino(this, Arduino.list() [1], 57600);
arduino.pinMode(12, Arduino.OUTPUT);
arduino.pinMode(11, Arduino.OUTPUT);
arduino.pinMode(9, Arduino.OUTPUT);
arduino.pinMode(10, Arduino.OUTPUT);
}
void draw() {
if (keyPressed == true) {
if (key == 'w' || key == 'W') {
arduino.digitalWrite (12, Arduino.HIGH);
}
if (key == 's' || key == 'S') {
arduino.digitalWrite (11, Arduino.HIGH);
}
if (key == 'a' || key == 'A') {
arduino.digitalWrite (9, Arduino.HIGH);
}
if (key == 'd' || key == 'D') {
arduino.digitalWrite (10, Arduino.HIGH);
}
else {
arduino.digitalWrite (12, Arduino.LOW);
arduino.digitalWrite (11, Arduino.LOW);
arduino.digitalWrite (9, Arduino.LOW);
arduino.digitalWrite (10, Arduino.LOW);
}
}
}
Everything works fine except when I press the 'D' key. Whenever I press it (or any other letter used in the last if) the LED lights up but doesn't turn off when I release the key. I've tried changing the LED pin, and the order in which the "if" statements are but the last one always has the same problem. The Arduino is running the StandardFirmata sketch. I'm using an Arduino Uno, Win 7 x64 and Processing 1.5.1 since 2.0.2 was giving me an error. Any help would be great.
Thanks

It looks like your 'else' statement is under the wrong 'if' block. Based on your goal, you should have it so that if a key is not pressed, you are writing Arduino.LOW to pins 9-12. Basically, just move a bracket:
void draw() {
if (keyPressed == true) {
if (key == 'w' || key == 'W') {
arduino.digitalWrite (12, Arduino.HIGH);
}
if (key == 's' || key == 'S') {
arduino.digitalWrite (11, Arduino.HIGH);
}
if (key == 'a' || key == 'A') {
arduino.digitalWrite (9, Arduino.HIGH);
}
if (key == 'd' || key == 'D') {
arduino.digitalWrite (10, Arduino.HIGH);
}
}
else {
arduino.digitalWrite (12, Arduino.LOW);
arduino.digitalWrite (11, Arduino.LOW);
arduino.digitalWrite (9, Arduino.LOW);
arduino.digitalWrite (10, Arduino.LOW);
}
}

Related

how to make button stop working once timer is over

i have created a 50 second timer. Once the timer reach zero a pop view will appear displaying the score and the button on the application should stop working but i am not sure how to make the button stop being clickable
equal.setOnClickListener{
++total
if(ans == ans4 || ans1 == ans4 || ans2 == ans4 || ans3 == ans4 || ans == ans5 || ans1 == ans5 || ans2 == ans5 || ans3 == ans5
|| ans == ans6 || ans1 == ans6 || ans2 == ans6 || ans3 == ans6){
answer.setText("Correct")
answer.setTextColor(Color.GREEN)
++correct
score.setText("Score: $correct/$total")
} else {
answer.setText("Wrong")
answer.setTextColor(Color.RED)
score.setText("Score: $correct/$total")
}
}
val timer = object: CountDownTimer(50000, 1000) {
override fun onTick(millisUntilFinished: Long) {
countTimer.setText("Remaining: " + millisUntilFinished / 1000);
if (correct >= 5){
countTimer.setText("Remaining: " + (millisUntilFinished + 10000 ) / 1000);
}
}
override fun onFinish() {
popup()
}
}
timer.start()
}
fun popup(){
var popupView: View = layoutInflater.inflate(R.layout.score, null)
var gameover_textView = popupView.findViewById<TextView>(R.id.endMessage)
gameover_textView.setText("Score: $correct/$total ")
var popupwindow = PopupWindow(this)
popupwindow.contentView = popupView
popupwindow.showAtLocation(popupView, Gravity.CENTER, 0, 100)
popupView.setOnClickListener{
popupwindow.dismiss()
}
}
equal.setClickable(false);
equal.setClickable(true);
//according to the requirement

How do you check if an array has some integers and then add them all up to get a result

const Discord = require('discord.js');
const bot2 = new Discord.Client();
const mark = '*interesting';
const marker = '*reverse'
const markir = '*fakereverse'
const markri = '*falsereverse'
const markre = '*randomise_'
const mrk = '*replace_'
const markro ='*math'
let para_meter = false
function reverseString(str) {
return str.split("").reverse().join("");
}
function randomise(str) {
randomnumber = Math.floor(Math.random() * str.length)
strarr = str.split('')
alphabet = ['A', 'a', 'B','b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p', 'Q', 'q', 'R', 'r', 'S', 's', 'T', 't', 'U', 'u', 'V', 'v', 'W', 'w', 'X', 'x', 'Y', 'y', 'Z', 'z']
alpharandom = alphabet[Math.floor(Math.random() * 52)]
strarr[randomnumber] = alpharandom
return strarr.join('')
}
bot2.on('message', msg =>{
let args = msg.content.substring(mark.length)
let sgra = msg.content.substring(marker.length)
let thisis = msg.content.substring(markir.length)
let sisiht = msg.content.substring(markri.length)
let argon = msg.content.substring(markre.length)
let goodgood = msg.content.substring(mrk.length)
let spited = msg.content.split(' ')
if(msg.content.startsWith(mark)){
let thee = args + ". I'm not dad. I'm bad discord bot"
msg.channel.send(thee)
}
if(msg.content.startsWith(marker)){
if(sgra == ''){
msg.channel.send('you need something to reverse')
return
}
let arg = reverseString(sgra)
msg.channel.send(arg)
}
if(msg.content.startsWith(markir)){
if(thisis == ''){
msg.channel.send('you need something to fakereverse')
return
}
let tese = thisis.split(' ')
let arrayI = []
tese.forEach(thing => {
arrayI.push(reverseString(thing))
})
msg.channel.send(arrayI.join(' '))
}
if(msg.content.startsWith(markri)){
if(sisiht == ''){
msg.channel.send('you need something to falsereverse')
return
}
let eset = sisiht.split(' ')
let arrayII = []
eset.forEach(gniht => {
arrayII.push(reverseString(gniht))
})
let somethingi = arrayII.join(' ')
msg.channel.send(reverseString(somethingi))
}
if(msg.content.startsWith(markre)){
if(argon == ''){
msg.channel.send('you need something to randomise')
return
}
let esci = argon.split(' ')
let arrayIII = []
esci.forEach(thing => {
let thingo = randomise(thing)
arrayIII.push(thingo)
})
msg.channel.send(arrayIII.join(' '))
}
if(msg.content.startsWith(mrk)){
if(goodgood == ''){
msg.channel.send('you need some words to replace')
return
}
let doog = goodgood.split(' ')
let arrayIV = []
doog.forEach(item => {
switch(item.length){
case 0:
arrayIV.push(' ')
break;
case 1:
arrayIV.push('a')
break;
case 2:
arrayIV.push('an')
break;
case 3:
arrayIV.push('the')
break;
case 4:
arrayIV.push('what')
break;
case 5:
arrayIV.push('where')
break;
case 6:
arrayIV.push('flight')
break;
case 7:
arrayIV.push('amazing')
break;
case 8:
arrayIV.push('censored')
break;
case 9:
arrayIV.push('wordcount')
break;
case 10:
arrayIV.push('everything')
break;
case 11:
arrayIV.push('magnificent')
break;
case 12:
arrayIV.push('mitochondria')
break;
case 13:
arrayIV.push('unlucky_number')
break;
default:
fakearray = ['\nAccording to all known laws', 'of aviation,', '', '', 'there is no way a bee', 'should be able to fly.', '', '','Its wings are too small to get','its fat little body off the ground.', '', '',`because bees don't care`,'what humans think is impossible.\n' ]
fakestring = fakearray.join('\n')
arrayIV.push(fakestring)
break;
}
})
msg.channel.send(arrayIV.join(' '))
}
if(spited[0] == markro){
if(!spited[1]){
msg.reply('there needs to be a math function to use')
return;
}
switch (spited[1]) {
case 'add':
if(!spited[2]){
msg.reply('you need something to add')
} else {
let thestuff = msg.content.split(' ').splice(markro, 1).splice('add', 1)
thestuff.forEach(elem => {
if(!isNaN(elem)){
para_meter = true
}
})
if(para_meter == true){
msg.reply('these are not integers')
para_meter = false
return;
}
var reduced = 0
thestuff.forEach(eleme => {
reduced += eleme
})
msg.channel.send(reduced)
}
break;
default:
break;
}
}
})
bot2.login(process.env.token2)
Focus on the last command. That is where I get my problem. In it I try to detect if a message has *math add in the start. Then I try check if the message has non-integers words(by turning the message into an array) and then I try to(if all the words are all integers) add up them and get a result I can send as a message. Here's the command that has the problem
if(spited[0] == markro){
if(!spited[1]){
msg.reply('there needs to be a math function to use')
return;
}
switch (spited[1]) {
case 'add':
if(!spited[2]){
msg.reply('you need something to add')
} else {
let thestuff = msg.content.split(' ').splice(markro, 1).slice('add', 1)
thestuff.forEach(elem => {
if(!isNaN(elem)){
para_meter = true
}
})
if(para_meter == true){
msg.reply('these are not integers')
para_meter = false
return;
}
var reduced = 0
thestuff.forEach(eleme => {
reduced += eleme
})
msg.channel.send(reduced)
}
break;
default:
break;
}
}
Whenever I actually try use it though the bots command it just responds with '0*math'. How do I fix this
(I'm grateful that long code is scrollable and is not in one block)
See update at the bottom of this answer
If you wanted to add all numbers together from an array, you could use reduce to do so. Just check for the type before adding.
Something like this should do the trick..
Original answer:
// ~ Original ~
// * Numbers are typed as such (not strings)
/** const myArray = [{}, [], "a", 1, "b", 3, "c", 5]; **/
// ~ Updated ~
// * Numbers are in string form (same as you are
// receiving the data from the API)
const myArray = [{}, [], "a", "1", "b", "3", "c", "5"];
const result = addNumbers(myArray);
console.log(result); // 9
function addNumbers (arr = []) {
if (!Array.isArray(arr)) {
throw new Error(
`[addNumbers] Parameter type is '${typeof arr}', need Array!`
);
}
return arr.reduce((a, v) =>
(isNaN(Number.parseInt(v)) ? 0 : Number(v)) + a, 0);
}
UPDATE 1
Rethinking the current solution as a whole
From what I can tell, whether it is for addition, multiplication, etc.. you are expecting a specific string. This means there is no need to iterate over an array..
Example:
// Set default value for input/query
setQuery("add");
/**
* parseInput is our main function that parses "chat" commands
*/
function parseInput(inputStr) {
// Replace multiple spaces with single space
// In case someone types '*math add 3 3' or something
const inputStrSingleSpaced = inputStr.replace(/\s\s+/g, " ");
// Turn our string into an array
const inputArr = inputStrSingleSpaced.split(" ");
// Our array should contain 4 elements regardless of operation (add/multiply/etc)
if (inputArr.length !== 4) return undefined; // Could throw an error here?
const firstNum = Number(inputArr[2]); // First number should always be 3rd element in array
const secondNum = Number(inputArr[3]); // You get the idea..
const operation = inputArr[1];
switch (operation) {
case "add": return firstNum + secondNum;
case "multiply": return firstNum * secondNum;
// case "subtract": ...etc
default: return undefined; // Throw an error if you want instead?
}
}
/**
* sendIt "sends" our chat/query string for parsing
*/
function sendIt() {
const el = document.querySelector("#textbox");
const resEl = document.querySelector("#results");
const calculation = parseInput(el.value);
resEl.innerHTML = `<h1>Result: ${calculation}</h1>`;
}
/**
* setQuery lets us set the input value to a demo query string
*/
function setQuery(kind) {
const el = document.querySelector("#textbox");
if (kind === "add") el.value = `*math add ${rando()} ${rando()}`;
if (kind === "add_with_spaces") el.value = `*math add ${rando()} ${rando()}`;
if (kind === "multiply") el.value = `*math multiply ${rando()} ${rando()}`;
}
/**
* rando returns a random number between 0 and 50
*/
function rando() {
return Math.floor(Math.random() * 50);
}
.mt20 {
margin-top: 20px;
}
<h3>Enter query string (simulating chatting) then hit 'Send'</h3>
<input type="text" id="textbox" />
<button onclick="sendIt()">Send</button>
<hr />
<div id="results" class="mt20"></div>
<hr />
<div class="mt20">
Example Queries: <small><i>Click one to set query</i></small>
<br />
<button onclick="setQuery('add')">Add</button>
<button onclick="setQuery('multiply')">Multiply</button>
<button onclick="setQuery('add_with_spaces')">Multiple Spaces</button>
</div>
UPDATE 2:
If you wanted to mirror the addNumbers function, but for multiplication:
const myArray = [{}, [], "a", "9", "b", "3", "c"];
const result = multiplyNumbers(myArray);
console.log(result); // 27
function multiplyNumbers (arr = []) {
if (!Array.isArray(arr)) {
throw new Error(
`[multiplyNumbers] Parameter type is '${typeof arr}', need Array!`
);
}
return arr.reduce((a, v) => {
if (!isNaN(Number.parseInt(v))) { // If we are able to parse the string into an int
if (a === 0) return Number(v); // If accumulator is 0, just return current value (don't want to multiply by 0)
return Number(v) * Number(a); // If accumulator is NOT 0, multiply
}
return Number(a);
}, 0);
}

Nested if statements...or use Switch Case?

I have a large nested if. One portion of the nested if works, however, in the second portion only some of the nested if works. I cannot get the switch case to work.
//Match Scoring //All work, when I flip Poker on top of Match the first and second ifs do not work
if playerMatchCardsArray[0] == playerMatchCardsArray[1] &&
playerMatchCardsArray[1] == playerMatchCardsArray[2]{
} else if playerMatchCardsArray[0] == playerMatchCardsArray[1] ||
playerMatchCardsArray[1] == playerMatchCardsArray[2] ||
playerMatchCardsArray[0] == playerMatchCardsArray[2]{
} else if playerMatchCardsArray[0] != playerMatchCardsArray[1] ||
playerMatchCardsArray[1] != playerMatchCardsArray[2] ||
playerMatchCardsArray[0] != playerMatchCardsArray[2] {
//Poker Scoring //All work, when I flip Poker on top of Match. However the following lines work do not work
// SUITED THREE OF A KIND //does not work
if firstRandomNumber == secondRandomNumber && secondRandomNumber == thirdRandomNumber {
// STRAIGHT FLUSH // works
} else if straightCardsArray[0] == 1 && straightCardsArray[1] == 2 && straightCardsArray[2] == 3 &&
flushFirstRandomNumber == flushSecondRandomNumber &&
flushFirstRandomNumber == flushThirdRandomNumber{
// THREE OF A KIND // does not work
} else if pairFirstRandomNumber == pairSecondRandomNumber &&
pairFirstRandomNumber == pairThirdRandomNumber {
//STRAIGHT FORMULA // works
} else if straightCardsArray[0] == 1 && straightCardsArray[1] == 2 && straightCardsArray[2] == 3 {
// SUITED PAIR // does not work
} else if firstRandomNumber == secondRandomNumber ||
secondRandomNumber == thirdRandomNumber ||
firstRandomNumber == thirdRandomNumber {
// PAIR // does not work
} else if pairFirstRandomNumber == pairSecondRandomNumber ||
pairFirstRandomNumber == pairThirdRandomNumber ||
pairSecondRandomNumber == pairThirdRandomNumber {
// FLUSH // works
} else if flushFirstRandomNumber == flushSecondRandomNumber &&
flushFirstRandomNumber == flushThirdRandomNumber {
Thank you in advance for your time and assistance. It's greatly appreciated!
It was the '}' that was causing the issue.

String Subscript out of range in C++

I'm trying to convert Roman Numerals into Decimal numbers but I keep encountering this error every time I enter a Roman Numeral. I've tried editing the code numerous times but so far I haven't been able to figure out what's going on.
Here's my code:
Header:
#include <string>
using namespace std;
class romanNumeralType
{
public:
string setNumeral() const;
string getNumeral();
int convert(string romanNumber);
int getDecimal();
void printRoman() const;
void printDecimal() const;
private:
string romanNumber;
int englishNumbers;
};
Implementation:
string romanNumeralType::setNumeral() const
{
string romanNumber;
cout << "Please enter the Roman Numeral you wish to use: ";
cin >> romanNumber;
cout << endl;
return romanNumber;
}
string romanNumeralType::getNumeral()
{
return romanNumber;
}
int romanNumeralType::convert(string romanNumber)
{
englishNumbers = 0;
for (size_t i = 0; i < romanNumber.length(); i++ )
{
switch (romanNumber[i])
{
case 'm':
case 'M':
if (romanNumber[i] == 'M')
{
englishNumbers += 1000;
}
break;
case 'd':
case 'D':
if(romanNumber[i+1] == 'M')
{
englishNumbers += 500;
}
else if(romanNumber[i-1] == 'M')
{
englishNumbers -= 500;
}
break;
case 'c':
case 'C':
if(romanNumber[i+1] == 'M' || romanNumber[i+1] == 'D')
{
englishNumbers += 100;
}
else if(romanNumber[i-1] == 'M' || romanNumber[i-1] == 'D')
{
englishNumbers += 100;
}
break;
case 'l':
case 'L':
if(romanNumber[i+1] == 'M' || romanNumber[i+1] == 'D' || romanNumber[i+1] == 'C')
{
englishNumbers -= 50;
}
else if(romanNumber[i-1] == 'M' || romanNumber[i-1] == 'D' || romanNumber[i-1] == 'C')
{
englishNumbers += 50;
}
break;
case 'x':
case 'X':
if(romanNumber[i+1] == 'M' || romanNumber[i+1] == 'D' || romanNumber[i+1] == 'C' || romanNumber[i+1] == 'L')
{
englishNumbers -= 10;
}
else if(romanNumber[i-1] == 'M' || romanNumber[i-1] == 'D' || romanNumber[i-1] == 'C' || romanNumber[i-1] == 'L')
{
englishNumbers += 10;
}
break;
case 'v':
case 'V':
if(romanNumber[i+1] == 'M' || romanNumber[i+1] == 'D' || romanNumber[i+1] == 'C' || romanNumber[i+1] == 'L' || romanNumber[i+1] == 'X')
{
englishNumbers -= 5;
}
else if(romanNumber[i-1] == 'M' || romanNumber[i-1] == 'D' || romanNumber[i-1] == 'C' || romanNumber[i-1] == 'L' || romanNumber[i-1] == 'X')
{
englishNumbers += 5;
}
break;
case 'i':
case 'I':
if(romanNumber[i+1] == 'M' || romanNumber[i+1] == 'D' || romanNumber[i+1] == 'C' || romanNumber[i+1] == 'L' || romanNumber[i+1] == 'X' || romanNumber[i+1] == 'V')
{
englishNumbers -= 5;
}
else if(romanNumber[i-1] == 'M' || romanNumber[i-1] == 'D' || romanNumber[i-1] == 'C' || romanNumber[i-1] == 'L' || romanNumber[i-1] == 'X' || romanNumber[i-1] == 'V')
{
englishNumbers += 1;
}
break;
default:
return 0;
}//end switch
}//end for
return englishNumbers;
}
int romanNumeralType::getDecimal()
{
return englishNumbers;
}
void romanNumeralType::printRoman() const
{
cout << "The Roman Numeral is: " << romanNumber;
}
void romanNumeralType::printDecimal() const
{
cout << "The Decimal is: " << englishNumbers;
}
Any help at all would be greatly appreciated!
We have 0 <= i < romanNumber.length(), but you are getting access to romanNumber[i-1] and romanNumber[i+1]. So it is possible to try to get access to romanNumber[-1] or to romanNumber[romanNumber.length()] - it is forbidden.
So, you have to add checks. For example, before if(romanNumber[i+1] == 'M') it is necessary to check that i+1<romanNumber.length(). And before if(romanNumber[i-1] == 'M') it is necessary to check that i > 0.
I think this is happening because some of your code looks at array indexes ahead of the current index, e.g. i+1. When the end of the array is reached, i+1 will not be a valid element of the array, giving you an error.

Formatting multiple line statement in vim

In vim a long statements like
if ( (image == null) || (image.getFileHash() == null) || (image.getFileImage() == null) )
gets indented like this when I hit an enter before the second OR
if ( (image == null) || (image.getFileHash() == null)
|| (image.getFileImage() == null) ) {
is there a way to set vim to indent it like
if ( (image == null) || (image.getFileHash() == null)
|| (image.getFileImage() == null) ) {
i.e., aligning it with the column after ( of the first previous line.
With dash-tom-bang's help was able to solve a part of the
problem. However, now the curly brackets are not aligned as expected
if { starts on the same line.
if ( (image == null) || (image.getFileHash() == null) ||
(image.getFileImage() == null) )
{
}
if ( (image == null) || (image.getFileHash() == null) ||
(image.getFileImage() == null) ) {
}
The setting that controls this is cinoptions, see :help cinoptions-values.
Add this to your .vimrc to align with the most local unclosed parenthesis. (You can give extra indent in spaces by giving a different number, including negatives. You can indent N tabstops by using Ns.)
set cinoptions=(0
The default value is 2s, which would indent two tabs past the open paren; hopefully this is what you're seeing. :)

Resources