Does anyone have a code example of using the NXT RGB Color Sensor in the Lejos programming language. I have tried several different uses of setType() and setMode() but to no avail.
Here is some working code:
ColorLightSensor cs = new ColorLightSensor(SensorPort.S1, SensorConstants.TYPE_LIGHT_ACTIVE);
for(int i = 0; i < 100 && !done; i++)
{
cs.setFloodlight(lejos.robotics.Colors.Color.RED);
sleep(1);
LCD.clearDisplay();
LCD.drawString("" + cs.getRedComponent(), 0,0);
cs.setFloodlight(lejos.robotics.Colors.Color.GREEN);
sleep(1);
LCD.clearDisplay();
LCD.drawString("" + cs.getGreenComponent(), 0,0);
cs.setFloodlight(lejos.robotics.Colors.Color.BLUE);
sleep(1);
LCD.clearDisplay();
LCD.drawString("" + cs.getBlueComponent(), 0,0);
}
Here is a simple example for monitoring the NXT 2 color sensor:
import lejos.nxt.*;
import lejos.robotics.*;
public class MyColorSensor {
public static void main(String argv[]) {
ColorSensor cs = new ColorSensor(SensorPort.S1);
for(int i = 0; i < 10; i++) {
Color color = cs.getColor();
System.out.println("Color = " + cs.getColorID() + " " + color.getColor() +
"(" + color.getRed() + "," + color.getGreen() + "," + color.getBlue()
+") " + color.getColor());
Button.waitForAnyPress();
}
}
}
Related
I want to find the distance between two points but when I convert the string into an int I cant seem to resolve the error, "NumberFormatException".
import java.util.Scanner;
public class Code{
static Scanner scanner = new Scanner(System.in);
public static void main(String\[\] args){
String coords = scanner.next();
int a = Integer.parseInt(coords);
int b = Integer.parseInt(coords);
int c = Integer.parseInt(coords);
int d = Integer.parseInt(coords);
int x = b-a;
int y = d-c;
double distance = Math.sqrt(x*x + y*y);
System.out.println("The distance between (" + a + ", " + b + ") and (" +
c + ", " + d + ") is " + distance);
}
}
I want to learn dart programming language for mobile and web development. I tried to solve writing some algorithm in dart language, guess and check algorithm is very basic but I could not run it. Please help me.
Here is my code:
import 'dart:math';
void main() {
int cube = 27;
double epsilon = 0.1;
double guess = 0.0;
double increment = 0.01;
int num_guess = 0;
while ((pow(guess, 3).abs() - cube) >= epsilon) {
guess += increment;
num_guess++;
print("num_guess =" + " " + num_guess.toString());
}
if ((pow(guess, 3).abs() - cube) >= epsilon) {
print("Failed on cube root of" +
" " +
cube.toString() +
" " +
guess.toString());
} else {
print(guess.toString() + " " + "is close to the cube " +
cube.toString());
}
}
I'm using TIdHTTP to make HTTP GET requests to get wiki pages (executed until x >= 9 times using a for loop statement).
I am trying to use TStopWatch to measure the HTTP round trip request/response time in milliseconds of each GET requests.
I have tried somes methods, but, I still in doubt that it was right or not. So, please tell me what's the right method to do that. Thank you.
Btw, the code I have is:
//---------------------------------------------------------------------------
int MSec = 0;
TTimeSpan TTSpan;
TDateTime StartTime;
DWORD AStartTime = 0;
DWORD CStartTime = 0;
String ACount, Codes, Milli, Result;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
IdHTTP->ConnectTimeout = 3048;
IdHTTP->ReadTimeout = 2048;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::IdHTTPWork(TObject *ASender, TWorkMode AWorkMode, __int64 AWorkCount)
{
if (AWorkMode == wmRead)
ACount = "size: [" + String(AWorkCount) + " bytes]";
}
//---------------------------------------------------------------------------
void __fastcall TForm1::WorkClick(TObject *Sender)
{
static int Number = 1;
TStopwatch SWatch = TStopwatch::StartNew();
// CStartTime = GetTickCount();
// DWORD Start = timeGetTime();
// AStartTime = GetTickCount();
// CStartTime = TTSpan.Milliseconds;
Work->Enabled = false;
ListBox->Items->Clear();
ListBox->Items->BeginUpdate();
for (int i = 0; i < 9; i++)
{
try
{
SWatch.Start();
try
{
IdHTTP->Get("http://en.wikipedia.org/");
Sleep(1000);
}
catch (const Exception &E)
{
Label1->Caption = E.Message;
}
SWatch.Stop();
TTSpan = SWatch.Elapsed;
MSec = TTSpan.Milliseconds;
// MSec = TTSpan.Milliseconds / 10;
// MSec = SWatch.ElapsedMilliseconds / 10;
// TTSpan = SWatch.Elapsed;
// MSec = TTSpan.Milliseconds - CStartTime;
Milli = " time: [" + String(MSec) + " ms]";
Codes = " code: [" + IdHTTP->Response->ResponseText.LowerCase() + "]";
ListBox->Items->Add("(" + String(Number++) + "). " + ACount + Codes + Milli);
// AStartTime = GetTickCount();
// ListBox->Items->Add("(" + String(Number++) + "). " + ACount + Codes + Result.sprintf(L" time: [%i ms]",(aStartTime-bStartTime)));
}
__finally
{
Work->Enabled = true;
IdHTTP->Disconnect(true);
ListBox->Items->EndUpdate();
}
}
}
this is my complete code for a small gui to take variables from user and return them to the rest of program(r.o.p) for calculations, however doesn't seem to be passing to r.o.p. and no output file is observerd.
Any help would be much appreciated, I think the problem is with the listener for the Draw New Graph command. Thanks
Code:
import java.text.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class RungeKutta {
// class to create slider and window
private static File file1;
public static double A(double v, double x, double wc, double beta) {
return (-2 * beta * v - (Math.pow(wc, 2)) * Math.sin(x));
}
public static File getFile1() {
return file1;
}
public static void setFile1(File file1) {
RungeKutta.file1 = file1;
}
public static void main(String[] argv) throws IOException, ParseException {
createAndShowGUI();
}
private static void createAndShowGUI() {
//create and set up the window.
JFrame frame = new JFrame("RungeKutta");
GridLayout first = new GridLayout(14,1);
frame.setLayout(first);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create, name and Populate TextField
JTextField PL = new JTextField("Pendulum Length", 20);
//Set TextField to Uneditable. Each will have Empty Field Below For Variables
PL.setEditable(false);
//Set Textfield for user entered dat
JTextField PLv = new JTextField();
//Allow input from text field to be taken
JTextField AD = new JTextField("Angular Displacement", 20);
AD.setEditable(false);
JTextField ADv = new JTextField();
JTextField AV = new JTextField("Angular Velocity", 20);
AV.setEditable(false);
JTextField Avv = new JTextField();
JTextField TS= new JTextField("Time Steps", 20);
TS.setEditable(false);
JTextField TSv = new JTextField();
JTextField MT = new JTextField("Max Time", 20);
MT.setEditable(false);
JTextField MTv = new JTextField();
JTextField V = new JTextField("Viscosity (0-1)", 20);
V.setEditable(false);
JTextField Vv = new JTextField();
//Create Button to Restart and Button to take in Values for usage
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(600,500));
frame.getContentPane().add(PL, first);
frame.getContentPane().add(PLv, first);
frame.getContentPane().add(AD, first);
frame.getContentPane().add(ADv, first);
frame.getContentPane().add(AV, first);
frame.getContentPane().add(Avv, first);
frame.getContentPane().add(TS, first);
frame.getContentPane().add(TSv, first);
frame.getContentPane().add(MT, first);
frame.getContentPane().add(MTv, first);
frame.getContentPane().add(V, first);
frame.getContentPane().add(Vv, first);
JButton BNewGraph = new JButton("Draw New Graph"); //Button to restart entire drawing process
frame.getContentPane().add(BNewGraph, first);
//display the window
frame.pack();
frame.setVisible(true);
class intakegui implements ActionListener
{
public intakegui()
{
BNewGraph.addActionListener((ActionListener) this);
BNewGraph.setActionCommand("Click to Draw");
}
#Override
public void actionPerformed(ActionEvent e) {
double l = Double.parseDouble(PLv.getText());
double xi = Double.parseDouble(ADv.getText());
double vi = Double.parseDouble(Avv.getText());
double dt = Double.parseDouble(TSv.getText());
double n = Double.parseDouble(MTv.getText());
double beta = Double.parseDouble(Vv.getText());
SimpleDateFormat dform = new SimpleDateFormat("ddMMyyyysmH");
Date d = Calendar.getInstance().getTime();
String dstr = dform.format(d);
String filename = ("result " + dstr + ".txt");
file1 = new File(filename);
PrintWriter savedValues = null;
try {
savedValues = new PrintWriter(filename);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//declare variable for gravity and omega*c
double g = 9.8;
double wc = Math.sqrt(g / l);
savedValues.println("#Initial Values Entered");
savedValues.println("#" + l + "," + vi + "," + xi + "," + dt + "," + n
+ "," + beta);
double[] dispTime = new double[(int) n];
double[] velTime = new double[(int) n];
// let a = angular acceleration
for (double j = 0; j < (int) n; j++) {
// int time = 1;
double k1v = dt * j * A(vi, xi, wc, beta);
double k1x = dt * j * vi;
double k2v = dt * j * A(vi, xi + (0.5 * k1x), wc, beta);
double k2x = dt * j * (vi + (0.5 * k1v));
double k3v = dt * j * A(vi, xi + (0.5 * k2x), wc, beta);
double k3x = dt * j * (vi + (0.5 * k2v));
double k4v = dt * j * A(vi, xi + k3x, wc, beta);
double k4x = dt * j * (vi + k3v);
xi += k1x / 6 + k2x / 3 + k3x / 3 + k4x / 6;
vi += k1v / 6 + k2v / 3 + k3v / 3 + k4v / 6;
dispTime[(int) j] = xi;
velTime[(int) j] = vi;
System.out.println(xi + "," + vi);
}
for (int i = 0; i < (int) n; i++) {
savedValues.println(dispTime[i] + " " + velTime[i]);
}
savedValues.close();
System.out.println("File saved. File name: " + filename);
}
}
}
}
You forgot to add listener to your button. You need to add listener as below:
BNewGraph.addActionListener(new intakegui());
Now when user clicks on button, you would see the file.
I try to make a grid of squares, where I could control every square's color parameters individually ie. make them flash one by one or all at the same time.
I'm trying to do it with tweens, running the parameters with for-loop.
The code below tries to flash all the squares at the same time, once in every second. but for some reason all of the squares don't tween, only some do. Or they tween partly and sometimes they don't tween at all. However, the pattern doesn't repeat itself.
Is this too many tweens at the same time? Is the for-loop right way to do this? Should I use MovieClips instead of Sprites? If I want to control colors in many differeng objects in a very fast phase, what would be the best way to do it?
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
import flash.display.*;
import flash.events.*;
import flash.display.Sprite;
import flash.geom.Rectangle;
import flash.geom.ColorTransform;
import Math;
import flash.utils.Timer;
import flash.events.TimerEvent;
import resolumeCom.*;
import resolumeCom.parameters.*;
import resolumeCom.events.*;
public class LightGrid extends MovieClip
{
private var t1:Tween;
private var resolume:Resolume = new Resolume();
private var tempo:FloatParameter = resolume.addFloatParameter("Tempo", 0.6);
private var pad = 3;
private var dim = 20;
private var posX = 0 + pad;
private var posY = 0 + pad;
private var a:Number = new Number();
private var b:Number = new Number();
private var blk:Number = new Number();
var newCol:ColorTransform = new ColorTransform();
public function LightGrid()
{
resolume.addParameterListener(parameterChanged);
for (var b = 0; b < 16; b++)
{
posY = (b*dim) + (b*pad) + pad;
trace("New row");
for (var a = 0; a < 24; a++)
{
posX = (a*dim) + (a*pad) + pad;
// l = line, f = fill
var l:Sprite = new Sprite;
l.graphics.lineStyle(2, 0xFFFFF, 1);
l.graphics.drawRect(posX, posY, dim, dim);
l.name = "line_Row" + b + "Col" + a;
addChild(l);
var f:Sprite = new Sprite;
f.graphics.beginFill(0x990000, 1);
f.graphics.drawRect(posX, posY, dim, dim);
f.graphics.endFill();
f.name = "fill_Row" + b + "Col" + a;
addChild(f);
trace(getChildByName("fill_Row" + b + "Col" + a).name);
}
}
var myTimer:Timer = new Timer(1000, 100);
myTimer.addEventListener("timer", timerHandler);
myTimer.start();
}
public function timerHandler(event:TimerEvent):void {
flashTheLights();
}
public function parameterChanged(e:ChangeEvent):void
{
if (e.object == tempo)
{
}
}
public function flashTheLights():void
{
blk = 0;
for (var blk = 0; blk < (24/3); blk++)
{
for (var d = 0; d < 16; d++)
{
for (var c = (0+(3*blk)); c < (3+(3*blk)); c++)
{
newCol.redOffset=30-(35*blk);
newCol.blueOffset=200+(7*blk);
newCol.greenOffset=200;
trace(getChildByName("fill_Row" + d + "Col" + c).name);
var fill:Sprite = getChildByName("fill_Row" + d + "Col" + c) as Sprite;
fill.transform.colorTransform.alphaMultiplier = -255;
fill.transform.colorTransform = newCol;
trace("Run tween");
var myTween = new Tween(fill,'alpha',Regular.easeIn,1,0,0.3,true);
}
}
trace("Done!" + blk);
}
}
}
I kinda solved the problem by stacking the sprites under movieclips so I only tween couple of elements instead of tens or hundreds
for (var k = 0; k < (grdX/ptrnSz); k++)
{
var ptrn:MovieClip = new MovieClip();
ptrn.name = "ptrn" + k;
addChild(ptrn);
ptrn.alpha = 0.01;
ptrnAm++;
for (var d = 0; d < grdY; d++)
{
posY = (d*dim) + (d*pad) + top;
for (var c = (0+(ptrnSz*k)); c < (ptrnSz+(ptrnSz*k)); c++)
{
posX = (c*dim) + (c*pad) + left;
// l = line, f = fill
var f:Sprite = new Sprite;
f.graphics.beginFill(0xFFFFFF, 1);
f.graphics.drawRect(posX-0.5, posY, dim, dim);
f.graphics.endFill();
f.name = "fill_Block" + k + "Row" + d + "Col" + c;
ptrn.addChild(f);
}
}
}
grdX = Grid size in X-axis (how many columns)
ptrnSz = size of the movieclips containing the Sprites (how many columns)
After that I just tween movieclips with TweenMax, calling them each with getChildByName.