I am doing a project with an arduino to make a bell ring, and when I first tried, it worked how I wanted it to (wait(Serial.read())), but now I need to send over 100 0‘s over the serial port just to make it show for 4 seconds. Here is my Java code:
prepare for longness
Main.ringBell("100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
public static void ringBell(String length) throws Exception {
output.write(length.getBytes());
output.flush();
}
Here is the Arduino sketch:
int ledPin = 13;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
if(Serial.available() > 0) {
digitalWrite(ledPin, HIGH);
delay(Serial.read());
digitalWrite(ledPin, LOW);
}
}
Does anyone see a error in my code? If so, please just let me know what’s wrong and I’ll fix it.
Thank you.
You are not sending one big number to the arduino but several ASCII bytes. The Arduino will see this sequence:
In each loop it will read one byte and wait for that number of milliseconds. 49 or 48 milliseconds are not a long time. So what you have is a constant flicker of the LED which is to fast to see with the eye.
The next thing is: You are sending the bytes in one flush. But the Arduino has only a small internal buffer of 64 byte (see available docu). The rest is simply forgotten.
Lets calculate roughly: 64 bytes * (48 ms delay per byte ) is 3072ms. Yes, this sounds plausible.
Next thing would be:
delayonly can handle arguments of typeunsigned longwhich is 32 bit which translates to ~4,000,000,000 milliseconds you can wait. Your argument inMainis way beyond this limit.So: The easiest thing is to use
parseIntinstead ofread. And inMainsupply only numbers in the range of a positiveint(0.. 32767). And also do some delays in yourMainbefore sending the nextringBell.