Why is TCNT1 not counting up on Atmega328? - arduino

I have the following code for the Arduino with Atmega328 and a common 16x2 LCD. The LCD is working, but it is always showing the starting value "333" of the Timer 1 counter TCNT1. Why? I have read the datasheet of the 328 over and over again, but I don't get it.
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
const int lcdContrastPin = 6, lcdBackligthPin = 10;
void setup()
{
// tutn on LCD backlight and contrast
pinMode(lcdContrastPin, OUTPUT);
pinMode(lcdBackligthPin, OUTPUT);
// fine-tuning contrast could be done by PWM on lcdContrastPin
digitalWrite(lcdContrastPin, LOW);
digitalWrite(lcdBackligthPin, HIGH);
lcd.begin(16, 2);
// configure Timer1
TCCR1A = 0; // no waveform generation
TCCR1B = 0x00000010; // frequency divider 8 (i.e. counting with 2 MHz)
TCCR1C = 0;
TIFR1 = 0x00100000; // clear Input Capture Flag
TCNT1 = 333;
}
void loop()
{
int currentTimerValue = TCNT1;
lcd.setCursor(0, 0);
lcd.print("TCNT1=");
lcd.print(currentTimerValue);
lcd.println(" ");
delay(50);
}

Stupid me! In a lapse of consciousness I took 0x00000010 as a binary number instead of as a hexadecimal which it is. As a result I set the all clock selection bits to 0 which means the timer stops.
After replacing 0x00000010 by 0b00000010 (the true binary number) everything works as expected now:
TCCR1B = 0b00000010; // frequency divider 8 (i.e. counting with 2 MHz)
TCCR1C = 0;
TIFR1 = 0b00100000; // clear Input Capture Flag

Related

Arduino I2C Slave to Master communication problem

I am having a problem with reading random data in my Arduino Mega (Master) from my Arduino Uno (Slave) while using I2C communication.
Some background: I am reading Encoder data from the Uno and sending to the Mega via I2C communication. The encoder data is been used in the MEga to adjust the speed of a motor so that the revolutions per second of the different wheels have the same value.
The issue of reading random data arises when I include an IF condition or function.
Even if the IF condition included is an empty one or a call to function which has an empty body it starts to read random wrong data from the Uno.
If i don't have the adjusting part (IF condition/ function) of the code the reading of the data from the Uno works fine.
If anybody can help, it would be greatly appreciated.
Master Code:
#include <SoftwareSerial.h>
#include <SabertoothSimplified.h>
// Include the required Wire library for I2C<br>#include
#include <Wire.h>
// RX on pin 17 (to S2), TX on pin 16 (to S1).
SoftwareSerial SWSerial(NOT_A_PIN, 16);
// Use SWSerial as the serial port.
SabertoothSimplified ST(SWSerial);
//////////////////ENCODER DATA//////////////////
unsigned int revolutions_L_rpm = 0;
unsigned int revolutions_R_rpm = 0;
int16_t x = 0;
int16_t y = 0;
////////////////////////////////////////////////
//////////////VARIABLES FOR ADJUST//////////////
int error = 0;
int kp = 12;
int adjusted = 0;
////////////////////////////////////////////////
////////////////////MOTORS//////////////////////
//Declare the arduino pins
int LEDg = 7;
int LEDr = 6;
int LEDy = 5;
int speedVar = 0;
int speedOne = 0;
int speedTwo = 0;
int power;
////////////////////END/////////////////////////
void setup() {
//initlize the mode of the pins
pinMode(LEDg,OUTPUT);
pinMode(LEDr,OUTPUT);
pinMode(LEDy,OUTPUT);
//set the serial communication rate
Serial.begin(9600);
SWSerial.begin(9600);
Wire.begin();
}
void loop()
{
//check whether arduino is reciving signal or not
if(Serial.available() > 0){
char val = Serial.read();//reads the signal
Serial.print("Recieved: ");
Serial.println(val);
switch(val){
/*********Increase speed by 1 as long as e(triangle) is held*********/
case 'a':
forward();
break;
/*********Decrease speed by 1 as long as g(x) is held*********/
case 'c':
reverse();
break;
/*********Increase speed by 1 as long as e(triangle) is held*********/
case 'd':
turnLeft();
break;
/*********Decrease speed by 1 as long as g(x) is held*********/
case 'b':
turnRight();
break;
/*********Toggle when Circle is held for 5 seconds*********/
case 'f':
toggleSwitch(LEDy);
break;
/*********Toggle when Square is held for 5 seconds*********/
case 'h':
stopMotors();
break;
}
Serial.print("sppedVar = ");
Serial.print(speedVar);
Serial.print("\tleftSpeed: ");
Serial.print(speedOne);
Serial.print("\trightSpeed: ");
Serial.println(speedTwo);
}
Wire.requestFrom(9,4); // Request 4 bytes from slave arduino (9)
byte a = Wire.read();
Serial.print("a: ");
Serial.print(a);
byte b = Wire.read();
Serial.print(" b: ");
Serial.print(b);
byte e = Wire.read();
Serial.print(" --- e: ");
Serial.print(e);
byte f = Wire.read();
Serial.print(" f: ");
Serial.print(f);
x = a;
x = (x << 8) | b;
Serial.print("\tX: ");
Serial.print(x);
y = e;
y = (y << 8) | f;
Serial.print("\tY: ");
Serial.print(y);
revolutions_L_rpm = x;
revolutions_R_rpm = y;
if ((revolutions_L_rpm != revolutions_R_rpm) && (speedVar != 0)){
error = 0;
error = revolutions_L_rpm - revolutions_R_rpm;
adjusted = error/kp;
Serial.print("Error: ");
Serial.print(error);
Serial.print("Error/kp: ");
Serial.println(adjusted);
if ((speedTwo < 20) && (speedTwo > -20)){
speedTwo -= adjusted;
power = speedTwo;
ST.motor(2, -power);
//delay(20);
}
}
// Print out rpm
Serial.print("Left motor rps*100: ");
Serial.print(revolutions_L_rpm);
Serial.print(" ///// Right motor rps*100: ");
Serial.println(revolutions_R_rpm);
// Print out speed
Serial.print("speedOne: ");
Serial.print(speedOne);
Serial.print("\tspeedTwo: ");
Serial.println(speedTwo);
delay(1000);
}
Slave code:
// Include the required Wire library for I2C<br>#include <Wire.h>
#include <Wire.h>
// Checked for main program
volatile boolean counterReady;
// Internal to counting routine
unsigned int timerPeriod;
unsigned int timerTicks;
unsigned long overflowCount;
// The pin the encoder is connected
int encoder_in_L = 2;
int encoder_in_R = 3;
// The number of pulses per revolution
// depends on your index disc!!
unsigned int pulsesperturn = 16;
// The total number of revolutions
int16_t revolutions_L = 0;
int16_t revolutions_R = 0;
int16_t revolutions_L_rpm = 0;
int16_t revolutions_R_rpm = 0;
// Initialize the counter
int16_t pulses_L = 0;
int16_t pulses_R = 0;
byte myData[4];
// This function is called by the interrupt
void count_L() {
pulses_L++;
}
void count_R() {
pulses_R++;
}
void startCounting(unsigned int ms) {
counterReady = false; // time not up yet
timerPeriod = ms; // how many ms to count to
timerTicks = 0; // reset interrupt counter
overflowCount = 0; // no overflows yet
// Reset timer 2
TCCR2A = 0;
TCCR2B = 0;
// Timer 2 - gives us our 1 ms counting interval
// 16 MHz clock (62.5 ns per tick) - prescaled by 128
// counter increments every 8 µs.
// So we count 125 of them, giving exactly 1000 µs (1 ms)
TCCR2A = bit (WGM21) ; // CTC mode
OCR2A = 124; // count up to 125 (zero relative!!!!)
// Timer 2 - interrupt on match (ie. every 1 ms)
TIMSK2 = bit (OCIE2A); // enable Timer2 Interrupt
TCNT2 = 0; // set counter to zero
// Reset prescalers
GTCCR = bit (PSRASY); // reset prescaler now
// start Timer 2
TCCR2B = bit (CS20) | bit (CS22) ; // prescaler of 128
}
ISR (TIMER2_COMPA_vect){
// see if we have reached timing period
if (++timerTicks < timerPeriod)
return;
TCCR2A = 0; // stop timer 2
TCCR2B = 0;
TIMSK2 = 0; // disable Timer2 Interrupt
counterReady = true;
if(counterReady){
Serial.print("Pulses_L: ");
Serial.print(pulses_L);
Serial.print(" Pulses_R: ");
Serial.println(pulses_R);
// multiplying by 100 to get a greater difference to compare
revolutions_L_rpm = (pulses_L * 100) / pulsesperturn;
revolutions_R_rpm = (pulses_R * 100) / pulsesperturn;
// Total revolutions
// revolutions_L = revolutions_L + (pulses_L / pulsesperturn);
// revolutions_R = revolutions_R + (pulses_R / pulsesperturn);
pulses_L = 0;
pulses_R = 0;
}
}
void requestEvent() {
myData[0] = (revolutions_L_rpm >> 8) & 0xFF;
myData[1] = revolutions_L_rpm & 0xFF;
myData[2] = (revolutions_R_rpm >> 8) & 0xFF;
myData[3] = revolutions_R_rpm & 0xFF;
Wire.write(myData, 4); //Sent 4 bytes to master
}
void setup() {
Serial.begin(9600);
pinMode(encoder_in_L, INPUT);
pinMode(encoder_in_R, INPUT);
attachInterrupt(0, count_L, RISING); //attachInterrupt(digitalPinToInterrupt(encoder_in_L, count_L, RISING);
attachInterrupt(1, count_R, RISING); //attachInterrupt(digitalPinToInterrupt(encoder_in_R, count_R, RISING);
// Start the I2C Bus as Slave on address 9
Wire.begin(9);
// Attach a function to trigger when something is received.
Wire.onRequest(requestEvent);
}
void loop() {
// stop Timer 0 interrupts from throwing the count out
byte oldTCCR0A = TCCR0A;
byte oldTCCR0B = TCCR0B;
TCCR0A = 0; // stop timer 0
TCCR0B = 0;
startCounting (1000); // how many ms to count for
while (!counterReady)
{ } // loop until count over
// Print out rpm
Serial.print("Left motor rps: ");
Serial.println(revolutions_L_rpm);
Serial.print("Right motor rps: ");
Serial.println(revolutions_R_rpm);
// Print out revolutions
// Serial.print("Left motor revolution count: ");
// Serial.println(revolutions_L);
// Serial.print("Right motor revolution count: ");
// Serial.println(revolutions_R);
// restart timer 0
TCCR0A = oldTCCR0A;
TCCR0B = oldTCCR0B;
delay(200);
}

using Ultrasonic sensor to find obstecles Arduino

Am trying to make a smart cane for blind ppl using 2 ultrasonic sensors
to detect obstacles, and use a buzzer and a flat vibrating motor as a feedback when an obstacle is detected, where the flat motor should be ON when an obstacle
between 1m - 3m is detected, and the buzzer when it's less than 1m.
now recently i used the NewPing library which solved some of the problems but
the code doesn't do exactly what i want, instead it triggers both the buzzer and motor together when object detected, i'd appreciate it if anyone could help.
#include <NewPing.h>
const int trigPin = 8;
const int trigPin1 = 13;
const int echoPin = 9;
const int echoPin1 = 12;
const int buzzer = 5;
const int motor = 3;
NewPing sonar1(trigPin,echoPin,maxout);
NewPing sonar2(trigPin1,echoPin1,maxout);
// defines variables
long duration;
long duration1;
int distance;
int distance1;
void setup() {
pinMode(buzzer, OUTPUT);
pinMode(motor, OUTPUT);
Serial.begin(9600);
}
void loop() {
distance = sonar1.ping_cm();
distance1 = sonar2.ping_cm();
if (distance > 100 || distance1 > 100) {
digitalWrite(buzzer,LOW);
digitalWrite(motor,HIGH);
}
else if (distance <= 100 || distance1 <= 100) {
digitalWrite(buzzer,HIGH);
digitalWrite(motor,LOW);
}
Serial.print("Distance1: ");
Serial.println(distance);
Serial.print("Distance2: ");
Serial.println(distance1);
}
this is the ultrasonic pins:
first sensor (Vcc = 5V, trig = 8, echo = 9, GND = GND)
second sensor(Vcc = 5V, trig = 13 , echo = 12 , GND = GND)
and this is the buzzer and motor pins:
buzzer = 5 , GND
motor = 3 , GND
Separate the logic for the motor and the buzzer:
if (distance >= 100 && distance <= 300) {
// Motor on
digitalWrite(motor, HIGH);
}
else {
// Motor off
digitalWrite(motor, LOW);
}
if (distance1 < 100) {
// Buzzer on
digitalWrite(buzzer, HIGH);
}
else {
// Buzzer off
digitalWrite(buzzer, LOW);
}

Arduino pulse train

I will give you a little introduction:
I am working on a water fuel cell of Stanley Meyer. For those who don't know the water fuel cell you can see it here.
For the water fuel cell one has to build a circuit. Here is the diagram:
Right now I am working on the pulse generator (variable) and the pulse gate (variable) to generate this waveform.
So, I want to do this with Arduino timers. I already can generate a "high frequency" pulse generator (1 kHz - 10 kHz, depending on the prescaling at the TCCR2B register) PWM at pin 3 with this code:
pinMode(3, OUTPUT);
pinMode(11, OUTPUT);
TCCR2A = _BV(COM2A0) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(WGM22) | _BV(CS21) | _BV(CS20);
OCR2A = 180;
OCR2B = 50;
I can modify the frequency and pulse with:
sensorValue = analogRead(analogInPin);
sensorValue2 = analogRead(analogInPin2);
// Map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 30, 220);
outputValue2 = map(sensorValue2, 0, 1023, 10, 90);
OCR2A = outputValue;
This is working fine.
Now I want to modulate this pulse with another pulse train with "low frequency" (20 Hz to 100 Hz approximately) to act as a pulse gate. I was thinking to use Timer 0 to count and shutdown the signal when it counts some value and activate when arrives at the same value again, like this
TCCR0A = _BV(COM0A0) | _BV(COM0B0) | _BV(WGM01);
TCCR0B = _BV(CS02);
OCR0A = 90;
OCR0B = OCR0A * 0.8;
And compare with the counter
if (TCNT0 <= OCR0A)
TCCR2A ^= (1 << COM2A0);
But it does not work well. Any ideas for this?
These days I have tried to create a wave generator like the one that comes in your question. I can not eliminate the jitter or mismatch that appears, but I can create a wave like that. Try this example and modify it:
#include <TimerOne.h>
const byte CLOCKOUT = 11;
volatile byte counter=0;
void setup() {
Timer1.initialize(15); // Every 15 microseconds change the state
// of the pin in the wave function giving
// a period of 30 microseconds
Timer1.attachInterrupt(Onda);
pinMode(CLOCKOUT, OUTPUT);
digitalWrite(CLOCKOUT, HIGH);
}
void loop() {
if (counter>=29) { // With 29 changes I achieve the amount of pulses I need.
Timer1.stop(); // Here I create the dead time, which must be in HIGH.
PORTB = B00001000;
counter = 0;
delayMicroseconds(50);
Timer1.resume();
}
}
void Onda(){
PORTB ^= B00001000; // Change pin status
counter += 1;
}

Arduino sensor data

Hi I am using an Arduino Flex sensor to control a video game character.
The sensor data is being averaged and remapped to a value of between 0-6.
When the player flexes their bicep it reads the max value (this is perfect) however if the player flexes their arm hard and the sensor reads a max value of 6 for some reason as the player relaxes their arm the declining flex values are being passed into the game engine (instead of going from 6 to zero it drops from 6 to 5 to 4 to 3 to 2 to 1 before reaching zero). Can someone please advise how I should alter my code to make the sensor reading return to 0 instead of declining gradually?
#define NUM_LED 6 //sets the maximum numbers of LEDs
#define MAX_Low 75 //for people with low EMG activity
#define MAX_High 150//for people with high EMG activity
#define Threshold 3 // this sets the light to activate TENS
int reading[10];
int finalReading;
int MAX = 0;
int TENS =3;
int ledState = LOW;
byte litLeds = 0;
byte multiplier = 1;
byte leds[] = {8, 9, 10, 11, 12, 13};
char ch;
char contact;
void setup(){
Serial.begin(9600); //begin serial communications
digitalWrite(TENS, LOW);
for(int i = 0; i < NUM_LED; i++){ //initialize LEDs as outputs
pinMode(leds[i], OUTPUT);
pinMode(TENS, OUTPUT); // Set TENS output to StimPin
}
MAX = MAX_High; //This sets the default to people with high EMG activity.
}
void loop(){
for(int i = 0; i < 10; i++){ //take ten readings in ~0.02 seconds
reading[i] = analogRead(A0) * multiplier;
delay(2);
}
for(int i = 0; i < 10; i++){ //average the ten readings
finalReading += reading[i];
}
finalReading /= 10;
for(int j = 0; j < NUM_LED; j++)
{
digitalWrite(leds[j], LOW);//write all LEDs low and stim pin low
}
finalReading = constrain(finalReading, 0, MAX);
litLeds = map(finalReading, 0, MAX, 0, NUM_LED);
Serial.println(litLeds);
for(int k = 0; k < litLeds; k++){
digitalWrite(leds[k], HIGH); // This turns on the LEDS
}
{
// send data only when you receive data:
if (Serial.available() > 0)
{
ch = Serial.read();
contact=digitalRead(TENS);
if (ch == 'A' && contact==LOW)
{
digitalWrite(TENS, HIGH);
}
else if (ch == 'B' && contact==HIGH)
{
digitalWrite(TENS, LOW);
}
}
}
delay(80);
}
Your sensor doesn't read 6 and immediately 0, you are reading it so fast that you can read the intermediate values. For example: if player opens the arm very fast (250-300 ms, it is fast), you can take up to 3 readings then you can read 3 intermediate values.
You can add more time to the last delay() or use only a value that is the same that the 3 last readings to ensure that there isn't a fast change.

Why does XBee transmit fail sometimes?

I doing a project with Arduino Uno R3 and XBee S2 transmission. I use a couple of sensors like a wireless (RF) temperature sensor, two SHT75 sensors, a 3-axis accelerometer and an illumination sensor. And after collecting the data, we use XBee (S2, API mode) to send the data to the gateway. Every round is about one second.
The first problem is the data is about 16 bytes, but the packet does not send successful every round. Sometime it works, and sometimes it doesn't, but the payload of XBee can be 60 or 70 bytes in the datasheet... But if I put the payload as some simply an integer (like 1, 2, 3), not the data from sensor, and the transmission will be stable.
After meeting the problem above, I divided the data into two packets (each with an eight bytes payload), and the first packet is very stable, but the second is very unstable. As mentioned above, if I put some number into the second packets instead of the sensing data the second packet will become stable and send successfully every round.
So I think it's the code problem, but idk where is the problem. I try to change the baud rate or increasing the delay time between the two packets. Where is the problem? The following is my code:
#include <XBee.h>
#include <i2cmaster.h>
#include <string.h>
#include <ctype.h>
#include <Sensirion.h>
#include "Wire.h"
#include "MMA845XQ.h"
**///////////////////////////// XBee setup //////////////////////////////////**
XBee xbee = XBee();
XBeeAddress64 remoteAddress = XBeeAddress64(0x00000000, 0x00000000);
ZBRxResponse zbRx = ZBRxResponse();
ZBTxStatusResponse zbTxStus = ZBTxStatusResponse();
uint8_t payload[] = {0,0,0,0,0,0,0,0,0};
uint8_t payload1[] = {0,0,0,0,0,0,0,0,0};
**///////////////////////////// Accelerometer //////////////////////////////////**
MMA845XQ accel;
**////////////////////////// SHT1 serial data and clock ////////////////////**
const byte dataPin = 2;
const byte sclkPin = 3;
Sensirion sht = Sensirion(dataPin, sclkPin);
unsigned int rawData;
float temperature;
float humidity;
byte stat;
**////////////////////////// SHT2 serial data and clock ////////////////////**
const byte dataPin1 = 4;
const byte sclkPin1 = 5;
Sensirion sht1 = Sensirion(dataPin1, sclkPin1);
unsigned int rawData1;
float temperature1;
float humidity1;
byte stat1;
**//////////////////////////// Illumination sensor ////////////////////////**
int sensorPin = A0; // Select the input pin for the potentiometer
int sensorValue = 0; // Variable to store the value coming from the sensor
long int pardata, pardata_low, pardata_hi, real_pardata;
uint16_t illumindata = 0;
void setup () {
i2c_init(); //Initialise the I²C bus
PORTC = (1 << PORTC4) | (1 << PORTC5); //Enable pullups
Wire.begin();
accel.begin(false, 2);
Serial.begin(115200);
xbee.begin(Serial);
}
void loop () {
payload[0] = 10;
payload1[0] = 11;
**/////////////////////RF temperature sensor/////////////////////////////**
int dev = 0x5A<<1;
int data_low = 0;
int data_high = 0;
int pec = 0;
i2c_start_wait(dev + I2C_WRITE);
i2c_write(0x07);
i2c_rep_start(dev + I2C_READ);
data_low = i2c_readAck(); //Read 1 byte and then send ack
data_high = i2c_readAck(); //Read 1 byte and then send ack
pec = i2c_readNak();
i2c_stop();
double tempFactor = 0.02; // 0.02 degrees per LSB (measurement resolution of the MLX90614)
double tempData = 0x0000; // Zero out the data
int frac; // Data past the decimal point
// This masks off the error bit of the high byte, then moves it left 8 bits and adds the low byte.
tempData = (double)(((data_high & 0x007F) << 8) + data_low);
tempData = (tempData * tempFactor)-0.01;
float celcius = tempData - 273.15;
float fahrenheit = (celcius*1.8) + 32;
celcius *= 100;
int a = int(celcius) + 1;
payload[1] = a >> 8 & 0xff;
payload[2] = a & 0xff;
**//////////////////////////// Illumination sensor ////////////////////////////////**
sensorValue = analogRead(sensorPin);
TSR(sensorValue);
payload[3] = pardata_low >> 8 & 0xff;
payload[4] = pardata_low & 0xff;
**//////////////////////////// 3-axis accelemeter sensor ////////////////////////////////**
accel.update();
payload[5] = accel.getX()*10;
payload[6] = accel.getY()*10;
payload[7] = accel.getZ()*10;
delay(100);
**////////////////////////////// XBee send first packet///////////////////////////////////////////////**
xbee = XBee();
xbee.begin(Serial);
ZBTxRequest zbTx = ZBTxRequest(remoteAddress, payload, sizeof(payload));
zbTx.setAddress16(0xfffe);
xbee.send(zbTx);
delay(500);
**//////////////// SHT 1x temperature and humidity sensor /////////////////////////**
sht.readSR(&stat); // Read sensor status register
sht.writeSR(LOW_RES); // Set sensor to low resolution
sht.readSR(&stat); // Read sensor status register again
sht.measTemp(&rawData); // sht.meas(TEMP, &rawData, BLOCK)
sht.meas(TEMP, &rawData, NONBLOCK);
temperature = sht.calcTemp(rawData);
sht.measHumi(&rawData); // sht.meas(HUMI, &rawData, BLOCK)
humidity = sht.calcHumi(rawData, temperature);
sht.meas(HUMI, &rawData, NONBLOCK);
humidity = sht.calcHumi(rawData, temperature);
temperature *= 100;
a = int(temperature) + 1;
payload1[1] = a >> 8 & 0xff;
payload1[2] = a & 0xff;
humidity *= 100;
a = int(humidity) + 1;
payload1[3] = a >> 8 & 0xff;
payload1[4] = a & 0xff;
delay(10);
sht1.readSR(&stat1);
sht1.writeSR(LOW_RES); // Set sensor to low resolution
sht1.readSR(&stat1);
sht1.measTemp(&rawData1); // sht.meas(TEMP, &rawData, BLOCK)
temperature1 = sht1.calcTemp(rawData1);
sht1.measHumi(&rawData1); // sht.meas(HUMI, &rawData, BLOCK)
humidity1 = sht1.calcHumi(rawData1, temperature1);
delay(10);
temperature1 *= 100;
a = int(temperature1) + 1;
payload1[5] = a >> 8 & 0xff;
payload1[6] = a & 0xff;
humidity1 *= 100;
a = int(humidity1) + 1;
payload1[7] = a >> 8 & 0xff;
payload1[8] = a & 0xff;
**////////////////////////////// XBee send second packet ///////////////////////////////////////////////**
xbee = XBee();
xbee.begin(Serial);
zbTx = ZBTxRequest(remoteAddress,payload1, sizeof(payload1));
zbTx.setAddress16(0xfffe);
xbee.send(zbTx);
delay(500);
}
void TSR(int sensorValue)
{
illumindata = (sensorValue * 4 * 5) / 1.5;
pardata = 6250/6144*illumindata*10;
if(pardata > 0)
{
if(pardata < 11500)
{
real_pardata = 0.0000000020561*pardata*pardata*pardata -
0.00002255*pardata*pardata +
0.25788*pardata -
6.481;
if (real_pardata < 0)
{
real_pardata = 0;
}
pardata_hi = real_pardata/65535;
pardata_low = real_pardata%65535;
}
else
{
real_pardata = 0.0000049204*pardata*pardata*pardata -
0.17114*pardata*pardata +
1978.7*pardata -
7596900;
if (real_pardata < 0)
{
real_pardata = 0;
}
pardata_hi = real_pardata/65535;
pardata_low = real_pardata%65535;
}
}
else
{
pardata_hi = 0;
pardata_low = 0;
}
}
as I am writing this I have solved the same problem you have, though with similar hardware setup. I have used bare avr atxmega128a3u (so no arduino board) and an Xbee S1 communicating on baud rate 115200. After a few days trying to figure this out I came to conclusion, that if your avr is not running at precise clock (external xtal) and you use slightly "faster" baud rate ( >= 115200 ) Xbee's serial hardware has probably trouble recovering clock signal resulting in errors in transmission. (Maybe Xbee has slow bit sampling rate).
Anyway, by ensuring your microprocessor is running at stable clock (you should be safe here 'cause arduino has an external xtal) and by using slower baud rate (try 57600, 19200 or 9600) should solve your problem. I hope so. :) ...And don't forget to reconfigure Xbee's baud rate in XCTU.
And also it might help if you initliaze xbee only once.Move these lines into setup() function:
setup(){
// This is changed
Serial.begin(9600);
// This is new
xbee = XBee();
xbee.begin(Serial);
// ...
}
EDIT: Also you might be interested in this website where you can see what is the % of error for given clock frequency and baud rate (as well as direct register values to set if you were using bare avr) http://www.wormfood.net/avrbaudcalc.php?postbitrate=9600&postclock=16&hidetables=1

Resources