谢谢LZ的好资料呀,我也写了个程序, 串口输出:
与楼主有些不同
用中断
直接输出至串口
支持 公英制 自动判别
在LOOP中的输出部分 由于 有了公英制 复杂了些,为了显示4位小数,就在程序中用了整数
输出时再处理小数点。
///////////////////////////////////////////////////
//电子尺读数
// gnd data clk vcc1.5
// Pin Declarations
int dataIn = 3;
int clockIn = 2;
int isin=0; //英寸=1,mm=0
int isfs=0; //是负数
int index;
//float cal[20]={0.01,0.02,0.04,0.08,0.16,0.32,0.64,1.28,2.56,5.12,10.24,20.48,40.96,81.92,163.84,327.68,655.36,1310.72,2621.44,5242.88};//存放20位对应数值的数组
//float calin[20]={0.0005,0.001,0.002,0.004,0.008,0.016,0.032,0.064,0.128,0.256,0.512,1.024,2.048,4.096,8.192,16.384,32.768,65.536,131.072,262.144};//存放20位对应数值的数组
unsigned long cal[20]={1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288};//存放20位对应数值的数组
unsigned long calin[20]={5,10,20,40,80,160,320,640,1280,2560,5120,10240,20480,40960,81920,163840,327680,655360,1310720,2621440};//存放20位对应数值的数组
unsigned long xData,oData;//最终要输出的数据
int ledPin = 13; // the number of the LED pin
int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated
long interval = 500; // interval at which to blink (milliseconds)
long previousGetMillis = 0; //上次中断发生时间
long Timeout = 8; //超时时间 8ms
void setup(){
digitalWrite(dataIn, 1);
digitalWrite( clockIn, 1);
pinMode(dataIn, INPUT); //DATA line goes to Arduino digital pin 4
pinMode(clockIn, INPUT);
Serial.begin(9600);
delay(500);
attachInterrupt(0,getBit,RISING); //CLOCK line goes to Arduino digital pin 2 上升沿触发
index =0;
xData=0;
oData=999;
}
void loop(){
//超时处理
if ((index !=0) && (millis() - previousGetMillis > Timeout) ) {
index=0;
xData=0;
};
//输出
if (index >23) {
if (oData !=xData) {
if (isfs==1)
Serial.print('-');
if (isin==1){ //英寸
Serial.print(xData/10000);
Serial.print('.');
if ((xData % 10000)<1000){ //补0
if ((xData % 10000)<100){
if ((xData % 10000)<10){
Serial.print('0');
};
Serial.print('0');
};
Serial.print('0');
};
Serial.println(xData % 10000);
}else { //公制
Serial.print(xData/100);
Serial.print('.');
if ((xData % 100)<10) //补0
Serial.print('0');
Serial.println(xData % 100);
};
};
oData =xData;
index=0;
xData=0;
};
if (millis() - previousMillis > interval) {
previousMillis = millis();
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
digitalWrite(ledPin, ledState);
}
}
void getBit(){
previousGetMillis=millis();
if(index < 20){
if(digitalRead(dataIn)==1){
if (isin==0){
xData =xData+cal[index];
}else {
xData =xData+calin[index];
};
};
} else {
if (index==20) //第21位为符号位
isfs=digitalRead(dataIn);
if (index==23) //第24位为公英制 1=英制
isin=digitalRead(dataIn);
};
index++;
} |