Having issues with the Serial.read() command on my Arduino code. I have it connected to two 74HC595's shift registers connected to LED's.
I check if there is Serial data, then read two bytes. Then pass these bytes to a method that shifts them both out. When I check the bytes with Serial.print to print them out to the serial moniter I get for example
49
255
50
255
Why am I getting the two 255's I have read the documentation on arduino.cc and it says it reads a single byte only. Any ideas?
The end goal is to read two bytes on the serial line and shift them out to the shift reg's IE is the byte values of decimal 5 & 6 were passed the 1st 3rd LED's would light on one shift register then the 2nd and 3rd would on the other shift register
const int dataPin = 8;
const int latchPin = 9;
const int clockPin = 10;
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
byte low = Serial.read();
byte high = Serial.read();
Serial.println(low);
Serial.println(high);
sendBytes(low,high);
}
}
void sendBytes(byte l, byte h) {
digitalWrite(latchPin,LOW);
shiftOut(dataPin,clockPin,MSBFIRST,l);
shiftOut(dataPin,clockPin,MSBFIRST,h);
digitalWrite(latchPin,HIGH);
}
if (Serial.available() > 0) {
byte low = Serial.read();
byte high = Serial.read();
//...
This is a bug in your code. Very likely to trip, serial ports are not that fast. So high odds that Serial.available() only returns 1. You'll read the low byte okay but Serial.read() will then return -1 if there is no data to read. Which makes high equal to 0xff. The simple fix is:
if (Serial.available() >= 2)
I had the same problem reading from a program...
I had luck both letting the code loop until filled...
and before taking on new Serial data I flush the serial to get the latest bytes
While(Serial.read() != -1); //clears data in the PC Serial Port
Here's what it looks like all put together
int i = 0;
byte bytes[3];
interval = 150; //allows for this amount of time to read from serial
long previousMillis = 0;
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis < interval && i < 2) {
if(Serial.available() > 0) {
bytes[i] = Serial.read();
i++; }
}
if(currentMillis - previousMillis > 1000) { //waits 1 second to get new serial data
previousMillis = currentMillis; //resets the timer
i = 0;
While(Serial.read() != -1); //clears data in the PC Serial Port
}
Related
The base of the problem: I have an Arduino Due and a MPU6050 accelerometer and an 23lcv512. MPU gives me 16bit signed integer. I would like to save the datas to the SRAM and after the measurement read them back and via Serial send it to PC. Sending to PC is not a problem. The problem is that this SRAM has 128k pcs 8bit address. My numbers are 16 bit. I can't write them directly. Here is my code. I tested the RAM with this code:
`
void loop() {
int i = 0;
Serial.print("Write Byte: ");
for (i = 0; i < 70000; i++) {
//Serial.print("Write Byte: ");
//Serial.print(i);
//Serial.println();
SRAM.writeByte(START_ADDRESS, i);
START_ADDRESS = START_ADDRESS + 1;
}
Serial.print("Write End");
i = 0;
START_ADDRESS = 0;
for (i = 0; i < 300; i++) {
Serial.print("Read Byte: ");
Serial.print(SRAM.readByte(START_ADDRESS));
Serial.println();
Serial.println();
START_ADDRESS = START_ADDRESS + 1;
delay(100);
}
}`
I added the 23LC library. If it's run reads back the numbers from the RAM but after 255 it starts to read 0 again. I know why does it happen. But I don't know howto solve the problem.
I tried to use the writeBlock command but it only works for me with char variables. Char variable requires more space than integers. I have not too much.
Is there anyone who can write a sample code which can write 16 bit signed integer to sram?
I've commented the most obvious problems in your original code below:
void loop() {
int i = 0;
Serial.print("Write Byte: ");
for (i = 0; i < 70000; i++) { // since i is a 16bit int, 70,000 is out of range.
SRAM.writeByte(START_ADDRESS, i); // cool you wrote 1 byte, where is the other write?
START_ADDRESS = START_ADDRESS + 1; // try to keep all caps names for constants.
// this will make your code easier to read, trust me!
}
Serial.print("Write End");
i = 0;
START_ADDRESS = 0;
for (i = 0; i < 300; i++) {
Serial.print("Read Byte: ");
Serial.print(SRAM.readByte(START_ADDRESS)); // you read 1 byte, you can't expect a 16 bit
// value out of that.
Serial.println();
Serial.println();
START_ADDRESS = START_ADDRESS + 1;
delay(100);
}
}
Here's a more sound approach, it stores unsigned ints, but that can easily be changed to signed ints.
#define SRAM_SIZE (128UL << 10) // we have 128K of SRAM available.
// The U and L make this value an unsigned long.
// ALWAYS use unsigned values for addresses.
void loop()
{
Serial.print(F("Writing sequential numbers into SRAM...")); // _always_ store string constants in flash.
// save your RAM for more interesting stuff.
for (unsigned long i = 0; i < SRAM_SIZE; i += 2) // filling SRAM
{
// this is the (truncated from 0-65535) value we'll write.
unsigned int value = static_cast<unsigned int>(i & 0xFFFF);
SRAM.writeByte(i, value & 0xFF); // write lowest 8 bits
SRAM.writeByte(i + 1, (value >> 8) & 0xFF); // write next 8 bits.
}
Serial.println(F("done."));
// read back
Serial.println(F("SRAM contents (16-bits unsigned values):"));
for (unsigned long i = 0; i < SRAM_SIZE; i += 2) // reading all SRAM in 16-bit chunks.
{
Serial.print(i, HEX);
Serial.print(F(": "));
// read two consecutive bytes and pack them into a 16-bit integer.
unsigned int value = SRAM.readByte(i) + (static_cast<unsigned int>(SRAM.readByte(i+1)) << 8); // the cast is necessary.
Serial.println(value);
}
delay(100);
}
I'm working on an interface that reads serial data from a single wire bus on a car (BMW IBUS). I'm using an Microchip MCP2025 LIN bus transceiver chip to convert the single line bus to regular Rx/Tx to feed into the hardware serial pins (0 & 1) of an Arduino (Nano V3).
BMW's IBUS protocol uses Serial 8E1 at 9600 baud. Messages are variable length (between 5 and 37 bytes) Bus messages are separated by a pause of around 11 milliseconds (considerably longer than the bus high time when receiving) and I need to use this gap to detect the end of one message and the beginning of the next.
1st byte is the Source ID,
2nd byte is length of the packet excluding the first two bytes (source & length),
3rd byte is the destination ID,
4th byte onwards is the actual data,
Last byte is the checksum
Checksum is generated by XOR of the entire packet excluding the checksum itself.
My problem is that I don't know how to measure the bus idle time between messages. I think I can use bitRead(PIND,0) to tell when the bus is idle (high), but I'm not sure how to time this and go and process the message after a suitable time has passed.
I'm currently using the following code to read messages from the IBUS. It works for the most part, but gets out of sync when connected to the car. It's doesn't really know when messages have finished, but relies on the second byte of each message (the length byte) to know how many bytes to read in. As long as it reads the length byte correctly, it's fine, but if it gets out of sync, and the length byte is wrong, it reads in the wrong number of bytes and eventually overruns the array and the Arduino resets. If I can detect the idle time between messages I will know for sure that I have a complete message.
void ReadIBUS()
{
boolean inSTATE = 0;
byte IBUSbyte[40];
while(Serial.available() > 0 && inSTATE == 0 )
{
IBUSbyte[0] = Serial.read(); //read source byte
while (inSTATE == 0)
{
if(Serial.available() > 0)
{
IBUSbyte[1] = Serial.read(); //read length byte
inSTATE = 1;
}
delay(10);
}
inSTATE == 0;
LENGTH = IBUSbyte[1];
int i = 2;
while(i <= LENGTH + 1)
{
if(Serial.available() > 0)
{
IBUSbyte[i] = Serial.read();
i++;
delay(10);
}
}
checksumBYTE = 0;
byteSTATE = 0;
for (int i = 0; i < LENGTH + 1; i++){
checksumBYTE ^= IBUSbyte[i];
}
if (IBUSbyte[LENGTH + 1] == checksumBYTE){
for(int i = 0; i <= LENGTH + 1; i++)
{
mySerial.print(IBUSbyte[i], HEX);
mySerial.print(" ");
}
mySerial.println();
}
else {
debug();
inSTATE = 0;
byteSTATE = 0;
}
}
}
First off, delay is rarely a good thing to use. In this case, you can use millis to measure how long it is between characters, but only if you lose the delay:
void ReadIBUS()
{
byte IBUSbyte[40];
do {
// First, make sure we're between frames, in the quiet interval
uint32_t last_rx = millis();
while (millis() - last_rx < 5) {
// Hasn't been long enough, see if more chars are coming
if (Serial.available()) {
Serial.read(); // throw away partial frame chars
last_rx = millis();
}
}
// Haven't received any chars for a while, we must be
// between frames. Now wait for a frame.
while (!Serial.available())
; // waiting...
IBUSbyte[0] = Serial.read(); //read source byte
while (!Serial.available())
; // waiting...
IBUSbyte[1] = Serial.read(); //read length byte
LENGTH = IBUSbyte[1];
// Check the LENGTH to make sure it's not bogus. If it is, try again.
} while (LENGTH > sizeof(IBUSbyte)-1);
// LENGTH is reasonable, wait for the payload
uint8_t bytes_received = 2;
while (bytes_received <= LENGTH + 1) {
if (Serial.available()) {
IBUSbyte[ bytes_received++ ] = Serial.read(); // read frame payload byte
}
}
// All here, verify the checksum
checksumBYTE = 0;
for (int i = 0; i < LENGTH + 1; i++) {
checksumBYTE ^= IBUSbyte[i];
}
if (IBUSbyte[LENGTH + 1] == checksumBYTE) {
for(int i = 0; i <= LENGTH + 1; i++) {
mySerial.print(IBUSbyte[i], HEX);
mySerial.print(" ");
}
mySerial.println();
} else {
debug();
}
}
And the state variables are no longer needed.
BTW, this routine "blocks" the rest of the program from doing anything until a complete frame is received. It should probably be rewritten so that it is called frequently (like from loop), and last_rx and bytes_received are remembered across calls. It could return true when a complete frame has been received. This'll work, it's just sub-optimal because it blocks anything else from happening, except interrupts.
I have an arduino taking serial input and will turn on the leds. The code is below.
I have a strange problem that when I send multiples of 120x bytes e.g., 240, 480 the last 120 bytes never get read completely.
I see on the serial monitor 120 120 120 81 if I send 480 bytes of data. Could anyone point out the mistake?
#include "FastLED.h"
#define DATA_PIN 6
#define NUM_LEDS 40
byte colors[120];
CRGB leds[NUM_LEDS];
void setup(){
FastLED.addLeds<NEOPIXEL, DATA_PIN, RGB>(leds, NUM_LEDS);
Serial.begin(115200);
}
void loop(){
if (Serial.available()){
int i =0;
char incomingByte;
while(1) {
incomingByte = Serial.readBytes((char *)colors,120);
break;
}
Serial.print(incomingByte);
for(i=0;i<NUM_LEDS ;i++){
leds[i].green = colors[i];
leds[i].red = colors[i+1];
leds[i].blue = colors[i+2];
}
if(incomingByte==0x78){
FastLED.show();
}
}
}
your code is flawed in different ways.
First, please remove the useless use of while(1) {…; break;}, it's just adding an overhead and adds nothing to your algorithm.
Otherwise, your code is not working well because, I guess, at some point there's a lag happening in the serial communication that causes the read to timeout. Let's have a look at source code.
First, you take the readBytes() function. All it does is:
size_t Stream::readBytes(char *buffer, size_t length)
{
size_t count = 0;
while (count < length) {
int c = timedRead();
if (c < 0) break;
*buffer++ = (char)c;
count++;
}
return count;
}
i.e. it iterates length times over the blocking read function. But it breaks if that function's return value is less than zero, returning less than length bytes. So that what's happening to get less than length, so let's have a look at timedRead():
int Stream::timedRead()
{
int c;
_startMillis = millis();
do {
c = read();
if (c >= 0) return c;
} while(millis() - _startMillis < _timeout);
return -1; // -1 indicates timeout
}
what happens here, is that if the read succeeds, it returns the read value, otherwise it loops until timeout has passed, and returns -1, which will end readBytes immediately. The default value for the timeout is 1000ms, though you can make that value higher by using Serial.setTimeout(5000); in your setup() function.
Though you have nothing to earn by using the blocking readBytes() function. So you'd better instead write your loop so you read the values, and trigger an event only once all values have been read:
#define NB_COLORS 120
void loop() {
static byte colors[NB_COLORS];
static int colors_index=0;
if (colors_index < NB_COLORS) {
// let's read only one byte
colors[colors_index] = Serial.read();
// if a byte has been read, increment the index
if (colors[colors_index] != -1)
++colors_index;
} else {
// reset the index to start over
colors_index = 0;
// should'nt you iterate 3 by 3, i.e. having i=i+3 instead of i++ ?
for(i=0;i<NUM_LEDS ;i++){
leds[i].green = colors[i];
leds[i].red = colors[i+1];
leds[i].blue = colors[i+2];
}
FastLED.show();
}
}
HTH
As part of a simple Automation project, I was trying to control some LEDs through serial port. I cannot make the following code working
int pin =0;
int state = 0;
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
if(Serial.read() == 'S' && Serial.read() == 'S') {
// Command to set the pin
pin = Serial.read() - 65;
state = Serial.read() - '0';
Serial.print("Set State Command received");
// Set the Pin
pinMode(pin, OUTPUT);
digitalWrite(pin, state == 0? LOW:HIGH);
}
}
}
I am sending "SSN1" from my python program to the Arduino serial port for testing, and nothing happens (I have an LED connected on pin 13)
SS - Set State Command
N - (pin no) + 'A' - Pin number 13
1 - State ( 0 = LOW, 1= HIGH)
You want to wait until 4 serial bytes accumulate on the serial buffer.
void loop() {
// polls the serial buffer
while (Serial.available() < 4);
if (Serial.read() == 'S' && Serial.read() == 'S') {
char type = Serial.read();
char pin = Serial.read() - 65;
// do something with the results
}
}
Note that you may want to implement some kind of padding (adding a fixed length of spaces, for example) between inputs, because the serial buffer may drop a byte or overflow, which can lead to unexpected results. Also, some people will complain about the while (Serial.available() < 4) command because computer scientists have been trained to think "polling = bad!", but in the case of an Arduino it makes no difference since it is only running a single task.
By the way, you can also use interrupts with Serial data, but that's out of the scope of this response.
actually I have also battled to get something similar right. due to the problems experienced with serial communication (sometime the messages are slow and sent in pieces, the ACII codes are difficult to remember) I went for a different solution. Basically I added a header ">" and a tail "<"to the message sent to the serial and I featured the Arduino code to consider the message between >< as command. I have then used ATOI to convert string to integer.
In the following code you will see that I have used the following numbers to get Arduino changing the status of pin2 and pin13.
Here are the commands associated to this code:
1000< set pin 13 HIGH,
2000< set pin 13 LOW,
3000< set pin 2 HIGH,
4000< set pin 2 LOW
So, simply send out to the serial those numbers between >< and it should work.
I have used the above also to set PWM speed simply manipulating the strings associated to the received messages. I have not included in this sample the PWM commands but only those related to pin 13 and pin 2. I thought that would be much simpler and safe to use numbers and string identifier to open and close the message.
Load the sketch, open the serial monitor and send >1000<, you should see the internal led on pin 13 lighting up, and so on. let me know if you need any additional help.
char inData[10];
int index;
boolean started = false;
boolean ended = false;
String message = "I am ready!, Send your command....";
void setup(){
Serial.begin(9600);
Serial.println(message);
pinMode (13, OUTPUT);
pinMode (2, OUTPUT);
}
void loop()
{
while(Serial.available() > 0)
{
char aChar = Serial.read();
if(aChar == '>')
{
started = true;
index = 0;
inData[index] = '\0';
}
else if(aChar == '<')
{
ended = true;
}
else if(started)
{
inData[index] = aChar;
index++;
inData[index] = '\0';
}
}
if(started && ended)
{
int inInt = atoi(inData);
// set pin 13 HIGH
if (inInt < 1000)
{
digitalWrite(13, HIGH);
}
//set pin 13 LOW
else if (inInt < 2000)
{
digitalWrite(13, LOW);
}
//set pin 2 HIGH
else if (inInt < 3000)
{
digitalWrite(2, HIGH);
}
//set il pin 2 LOW
else if (inInt < 4000)
{
digitalWrite(2, LOW);
}
started = false;
ended = false;
index = 0;
inData[index] = '\0';
}
}
Look at this example code from Arduino's Physical Pixel Tutorial
const int ledPin = 13; // the pin that the LED is attached to
int incomingByte; // a variable to read incoming serial data into
void setup() {
// initialize serial communication:
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
}
void loop() {
// see if there's incoming serial data:
if (Serial.available() > 0) {
// read the oldest byte in the serial buffer:
incomingByte = Serial.read();
// if it's a capital H (ASCII 72), turn on the LED:
if (incomingByte == 'H') {
digitalWrite(ledPin, HIGH);
}
// if it's an L (ASCII 76) turn off the LED:
if (incomingByte == 'L') {
digitalWrite(ledPin, LOW);
}
}
Verify that you see SSN1 coming through on the serial monitor.
I improved my code as it look like this
int pin =0;
int state = 0;
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 3) { // I am using chunk of 4 characters/bytes as a command
// read the incoming byte:
if(Serial.read() == 'S' && Serial.read() == 'S') {
// Command to set the pin
pin = Serial.read() - 65;
state = Serial.read() - '0';
Serial.print("Set State Command received");
// Set the Pin
pinMode(pin, OUTPUT);
digitalWrite(pin, state == 0? LOW:HIGH);
}
delay(50);
}
}
It works perfectly for me. Due to the high frequency of looping, Arduino was not able pickup the bytes for consecutive read. So we are waiting for 4 bytes to accumulate in the buffer to read those (Arduino's serial buffer is 64 bytes).
I have a trouble with xbee s2b.
I try to receive two joystick values using only xbee placed on sparkfun regulated board (Coordinator API) and process these data on Arduino Uno connected to other xbee s2b placed on explorer board.(Router API). I configured xbees using X-CTU properly and I adjusted DIO0 and DIO1 to ADC[2] on Router Xbee. There is no problem when working with one joystick. But when I try to receive two joystick values at the same time, they are not working correctly. When I look the incoming data on serial monitor, I see;
https://lh3.googleusercontent.com/-20vjr0EchsQ/VqyZXgq84VI/AAAAAAAAA_0/WhEtoOU61vA/s1280-Ic42/Screenshot_3.jpg
My Arduino code is:
int packet[32];
void setup()
{
Serial.begin(9600);
}
void loop(){
if (Serial.available() > 0) {
if (Serial.read() == 0x7E) {
packet[0] = 0x7E; //start delimiter
packet[1] = readByte(); //MSB1
packet[2] = readByte(); //MSB2
int dataLength = (packet[1] << 8) | packet[2]; //between the length and the checksum
printPacket(dataLength+4);
Serial.println("");
}
}
delay(1000);
}
void printPacket(int k) {
for(int i=0; i < k; i++) {
Serial.print(packet, HEX);
Serial.print(" ");
delay(1000);
}
}
int readByte() {
while (true) {
if (Serial.available() > 0) {
return Serial.read();
}
}
}
What is the point I missed? Can you help me about this issue. Thank you in advance.
The delay(1000) statements may be causing you to lose characters from your serial buffer, and might not be necessary.
The code you shared appears incomplete. Where are you reading the dataLength bytes of the packet? How does printPacket() print the bytes?
Your inbound packet buffer should be larger -- I think the XBee S2B can have network payloads of up to 255 characters, in addition to the frame header and checksum.
You've created a blocking readByte() call, which isn't good program design. Consider something like this instead:
unsigned char packet[300];
int packet_index = 0;
int packet_length;
void loop() {
while (Serial.available() > 0) {
packet[packet_index++] = Serial.read();
if (packet_index == 3) {
packet_length = (packet[1] << 8) | packet[2];
}
if (packet_index > 2 && packet_index == packet_length) {
print_packet();
packet_index = 0;
}
}
}
void print_packet() {
int i;
for (i = 0; i < packet_length; ++i) {
Serial.print(packet[i], HEX);
Serial.print(" ");
}
Serial.println("");
}
If you have too much data to print and you're overflowing your outbound serial buffer, try increasing the speed of the console's serial port to 115200bps. Or print the bytes as you receive them instead of waiting until the packet is complete.